import 'package:absenkuv3/Bloc/CustomFunction.dart';
import 'package:absenkuv3/Bloc/NavigatorBloc.dart';
import 'package:absenkuv3/Bloc/SalesActivity/TotalKambanBloc.dart';
import 'package:absenkuv3/Repository/Model/SalesActivity/mDataKanban.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Repository/Model/SalesActivity/mPerusahaan.dart';
import 'package:absenkuv3/Repository/Model/mSplashScreen.dart';
import 'package:absenkuv3/Repository/Service/SalesActivityApi.dart';
import 'package:absenkuv3/Repository/Service/serviceInfo.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sn_progress_dialog/sn_progress_dialog.dart';
import 'package:absenkuv3/Bloc/CustomFunction.dart' as customFunction;

abstract class KambanEvent {
  BuildContext? context;
  GlobalKey<ScaffoldState>? scaffoldKey;
}

class getListDataKambanEvent extends KambanEvent {
  String? idTahapanM;
  ModelFilter? modelFilter;
  getListDataKambanEvent(BuildContext _context, this.idTahapanM, this.modelFilter) {
    context = _context;
  }
}

class addKambanEvent extends KambanEvent {
  DataPerusahaan? dataKamban;
  String? firstTahapan;
  GlobalKey<ScaffoldState>? _scaffoldKey;
  addKambanEvent(BuildContext _context, this._scaffoldKey, this.dataKamban, this.firstTahapan) {
    context = _context;
  }
}

class deleteKambanEvent extends KambanEvent {
  String? idPipelineMain;
  String? idTahapanM;
  GlobalKey<ScaffoldState>? _scaffoldKey;
  deleteKambanEvent(BuildContext _context, this._scaffoldKey, this.idPipelineMain, this.idTahapanM) {
    context = _context;
  }
}

class batalkanKambanEvent extends KambanEvent {
  String? idPipelineMain;
  String? idTahapanM;
  GlobalKey<ScaffoldState>? _scaffoldKey;
  batalkanKambanEvent(BuildContext _context, this._scaffoldKey, this.idPipelineMain, this.idTahapanM) {
    context = _context;
  }
}

class pindahBulanKambanEvent extends KambanEvent {
  String? idPipelineMain;
  String? idPipelineMainLog;
  String? idTahapanM;
  GlobalKey<ScaffoldState>? _scaffoldKey;
  pindahBulanKambanEvent(BuildContext _context, this._scaffoldKey, this.idPipelineMain, this.idPipelineMainLog, this.idTahapanM) {
    context = _context;
  }
}

class ubahTahapanKambanEvent extends KambanEvent {
  BuildContext? ctx;
  DataKanban? dataKamban;
  String? idTahapanM;
  String? statusPengajuan;
  String? tahapanSebelumId;
  String? tahapanSebelumNm;
  String? tahapanSesudahId;
  String? tahapanSesudahNm;
  bool? detail;
  String? pageSelected;
  String? ketPO;
  String? ketFailed;
  ubahTahapanKambanEvent(this.ctx, this.dataKamban, this.idTahapanM, this.statusPengajuan, this.tahapanSebelumId, this.tahapanSebelumNm, this.tahapanSesudahId, this.tahapanSesudahNm, this.detail, this.pageSelected, this.ketPO, this.ketFailed) {
    // context = _context;
    // context = _context;
  }
}

// class deleteKambanEvent extends KambanEvent {
//   DataKanban? dataKamban;
//   String? idTahapanM;
//   String? statusPengajuan;
//   String? tahapanSebelumId;
//   String? tahapanSebelumNm;
//   String? tahapanSesudahId;
//   String? tahapanSesudahNm;
//   deleteKambanEvent(BuildContext _context, this.dataKamban, this.idTahapanM, this.statusPengajuan, this.tahapanSebelumId, this.tahapanSebelumNm, this.tahapanSesudahId, this.tahapanSesudahNm) {
//     context = _context;
//   }
// }

class loadMoreEvent extends KambanEvent {
  late ScrollController scrollController;
  loadMoreEvent(BuildContext _context, GlobalKey<ScaffoldState> _scaffoldKey, ScrollController _scrollController) {
    context = _context;
    scaffoldKey = _scaffoldKey;
    scrollController = _scrollController;
  }
}

abstract class KambanState {
  int? totalLayanan;
  String? totalHarga;
  List<DataKanban>? data;
}

class getListDataKambanSuccessState extends KambanState {
  getListDataKambanSuccessState(KambanEvent _event, List<DataKanban>? _data) {
    data = _data;
  }
}

class KambanProgressState extends KambanState {}

class LoadMoreProgressState extends KambanState {
  LoadMoreProgressState(List<DataKanban>? _data) {
    data = _data;
  }
}

class KambanErrorState extends KambanState {}

class KambanBloc extends Bloc<KambanEvent, KambanState> {
  ModelFilter? modelFilter;
  KambanState? initialState;
  List<DataKanban>? listDataLayanan;
  String? idTahapanM;
  int offset = 0;
  int limit = ServerInfo.limit;

  KambanBloc(KambanState initialState) : super(initialState);

  @override
  Stream<KambanState> mapEventToState(KambanEvent event) async* {
    if (event is getListDataKambanEvent) {
      offset = 0;
      modelFilter = event.modelFilter;
      idTahapanM = event.idTahapanM;
      yield KambanProgressState();
      DataKanbanRespon dataKanbanRespon = await SalesActivityApi().getDataKanban(event.idTahapanM, offset, modelFilter!);
      if (dataKanbanRespon.success!) {
        listDataLayanan = dataKanbanRespon.dataKanban;
        yield getListDataKambanSuccessState(event, listDataLayanan);
      } else
        yield KambanErrorState();
    }
    else if (event is loadMoreEvent) {
      if (event.scrollController.offset >= event.scrollController.position.maxScrollExtent && !event.scrollController.position.outOfRange) {
        offset = offset + limit;
        yield LoadMoreProgressState(listDataLayanan);
        DataKanbanRespon dataKanbanRespon = await SalesActivityApi().getDataKanban(idTahapanM, offset, modelFilter!);
        if (dataKanbanRespon.success!) {
          listDataLayanan!.addAll(dataKanbanRespon.dataKanban!);
        }
        yield getListDataKambanSuccessState(event, listDataLayanan);
      }
    } else if(event is addKambanEvent){
      ProgressDialog pd = ProgressDialog(context: event.context);
      ProgressDialogDelayed.show(pd, isDismissible: true);
      BasicRespon dtp = await SalesActivityApi().addKamban(event.dataKamban!);
      ProgressDialogDelayed.hide(pd);
      if (dtp.success!) {
        showSnackBarDelayed(event._scaffoldKey, dtp.message, event.context);
        // customFunction.CustomPopUp.show(dtp.message, event.context, "Tutup", isDismissible: false, doublePop: true);
        Future.delayed(Duration(milliseconds: 3000)).then((value) {
          BlocProvider.of<NavigatorBloc>(event.context!).add(NavigatePop(event.context));
          BlocProvider.of<NavigatorBloc>(event.context!).add(NavigatePop(event.context));
          BlocProvider.of<NavigatorBloc>(event.context!)
              .add(NavigateToKambanBoardSalesActivityPage(event.context!));
        });
        // BlocProvider.of<KambanBloc>(event.context!)
        //     .add(getListDataKambanEvent(event.context!, event.firstTahapan, ModelFilter(monthYear: DateTime.now())));
      }else{
        customFunction.CustomPopUp.show(
            dtp.message, 
            event.context, 
            "Tutup", 
            isDismissible: false, 
            doublePop: false,
            color: Colors.red,
            icon: Icon(Icons.clear, color: Colors.red, size: 50,)
        );
      }
    }
    else if(event is ubahTahapanKambanEvent) {
      ProgressDialog pd = ProgressDialog(context: event.ctx);
      ProgressDialogDelayed.show(pd, isDismissible: false);
      BasicRespon dtp = await SalesActivityApi().ubahTahapan(
          event.dataKamban!, event.statusPengajuan, event.tahapanSebelumId,
          event.tahapanSebelumNm, event.tahapanSesudahId,
          event.tahapanSesudahNm, event.ketPO, event.ketFailed);
      ProgressDialogDelayed.hide(pd);
      if (dtp.success!) {
        BlocProvider.of<NavigatorBloc>(event.ctx!).add(NavigatePop(event.ctx));
        BlocProvider.of<NavigatorBloc>(event.ctx!).add(NavigatePop(event.ctx));
        if(event.ketPO != "" || event.ketFailed != ""){
          BlocProvider.of<NavigatorBloc>(event.ctx!).add(NavigatePop(event.ctx));
        }
        showSnackBarDelayed(event.scaffoldKey, dtp.message, event.ctx);
        Future.delayed(Duration(milliseconds: 600)).then((value) {
          BlocProvider.of<TotalKambanBloc>(event.ctx!).add(getTotalKambanEvent(event.ctx!, event.idTahapanM, ModelFilter(monthYear: DateTime.now())));
          BlocProvider.of<KambanBloc>(event.ctx!)
              .add(getListDataKambanEvent(event.ctx!, event.idTahapanM, ModelFilter(monthYear: DateTime.now())));
          if(event.detail!){
            DataKanban _dataKamban = event.dataKamban!;
            _dataKamban.idTahapanM = event.tahapanSesudahId;
            // _dataKamban.button!.buttonUbahTahapan = true;
            // BlocProvider.of<NavigatorBloc>(event.ctx!).add(NavigatePop(event.ctx));
            Navigator.pop(event.ctx!, ['refresh', event.idTahapanM]);
            BlocProvider.of<NavigatorBloc>(event.ctx!)
                .add(NavigateToDetailSalesActivityPage(event.ctx!, [_dataKamban, event.pageSelected, 'refresh', event.idTahapanM]));
          }
        });
      }else{
        BlocProvider.of<NavigatorBloc>(event.context!).add(NavigatePop(event.context));
        showSnackBarDelayed(event.scaffoldKey, dtp.message, event.context);
      }
    }
    else if(event is deleteKambanEvent){
      ProgressDialog pd = ProgressDialog(context: event.context);
      ProgressDialogDelayed.show(pd, isDismissible: false);
      BasicRespon dtp = await SalesActivityApi().deleteKanban(event.idPipelineMain!);
      ProgressDialogDelayed.hide(pd);
      showSnackBarDelayed(event._scaffoldKey, dtp.message, event.context);
      if (dtp.success!) {
        // customFunction.CustomPopUp.show(dtp.message, event.context, "Tutup", isDismissible: false);
        Future.delayed(Duration(milliseconds: 600)).then((value) {
          BlocProvider.of<NavigatorBloc>(event.context!).add(NavigatePop(event.context));
          BlocProvider.of<TotalKambanBloc>(event.context!).add(getTotalKambanEvent(event.context!, event.idTahapanM, modelFilter));
          BlocProvider.of<KambanBloc>(event.context!)
              .add(getListDataKambanEvent(event.context!, event.idTahapanM, modelFilter));
          });

      }
    }
    else if(event is batalkanKambanEvent){
      ProgressDialog pd = ProgressDialog(context: event.context);
      ProgressDialogDelayed.show(pd, isDismissible: false);
      BasicRespon dtp = await SalesActivityApi().batalkanKanban(event.idPipelineMain!);
      ProgressDialogDelayed.hide(pd);
      showSnackBarDelayed(event._scaffoldKey, dtp.message, event.context);
      if (dtp.success!) {
        // customFunction.CustomPopUp.show(dtp.message, event.context, "Tutup", isDismissible: false);
        Future.delayed(Duration(milliseconds: 600)).then((value) {
          BlocProvider.of<NavigatorBloc>(event.context!).add(NavigatePop(event.context));
          BlocProvider.of<TotalKambanBloc>(event.context!).add(getTotalKambanEvent(event.context!, event.idTahapanM, modelFilter));
          BlocProvider.of<KambanBloc>(event.context!)
              .add(getListDataKambanEvent(event.context!, event.idTahapanM, modelFilter));
        });

      }
    }
    else if(event is pindahBulanKambanEvent){
      ProgressDialog pd = ProgressDialog(context: event.context);
      ProgressDialogDelayed.show(pd, isDismissible: false);
      BasicRespon dtp = await SalesActivityApi().pindahBulanKanban(event.idPipelineMain!, event.idPipelineMainLog!);
      ProgressDialogDelayed.hide(pd);
      showSnackBarDelayed(event._scaffoldKey, dtp.message, event.context);
      if (dtp.success!) {
        // customFunction.CustomPopUp.show(dtp.message, event.context, "Tutup", isDismissible: false);
        Future.delayed(Duration(milliseconds: 600)).then((value) {
          // Navigator.pop(event.context!);
          BlocProvider.of<NavigatorBloc>(event.context!).add(NavigatePop(event.context));
          BlocProvider.of<TotalKambanBloc>(event.context!).add(getTotalKambanEvent(event.context!, event.idTahapanM, modelFilter));
          BlocProvider.of<KambanBloc>(event.context!)
              .add(getListDataKambanEvent(event.context!, event.idTahapanM, modelFilter));
        });

      }
    }
  }
}
