
import 'package:absenkuv3/Bloc/AuthBloc.dart';
import 'package:absenkuv3/Bloc/Dropdown/DropdownStatus.dart' as status;
import 'package:absenkuv3/Bloc/FilterBottomSheetBloc.dart';
import 'package:absenkuv3/Bloc/NavigatorBloc.dart';
import 'package:absenkuv3/Repository/Model/mDropdown.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Repository/Model/mLogin.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/UI/Modul/Absensi/KomponenAbsensi.dart';
import 'package:absenkuv3/UI/Modul/Dropdown/DropdownCabang.dart';
import 'package:absenkuv3/UI/Modul/Dropdown/DropdownDepartemen.dart';
import 'package:absenkuv3/UI/Modul/Dropdown/DropdownStatus.dart';
import 'package:absenkuv3/UI/Template/AutoComplete/Bloc/AutoCompletePegawaiBloc.dart';
import 'package:absenkuv3/UI/Template/DateRangePicker/Bloc/DateRangePickerBloc.dart' as dateRangePicker;
import 'package:absenkuv3/UI/Template/MonthPicker/UI/templateMonthPickerNonFloating.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:absenkuv3/Bloc/Dropdown/DropdownCabangBloc.dart' as cabang;
import 'package:absenkuv3/Bloc/Dropdown/DropdownDepartemenBloc.dart' as departemen;
import 'AutoComplete/UI/AutoCompletePegawai.dart';
import 'DateRangePicker/UI/templateDateRangePicker.dart';
import 'MonthPicker/Bloc/MonthPickerBloc.dart' as monthPicker;
import 'MonthPicker/Bloc/MonthPickerBloc.dart';

class FilterBottomSheet extends StatefulWidget {
  bool adaFilterTanggal;
  bool adaFilterStatus;
  bool adaFilterRangeTanggal;
  FilterBottomSheet({this.adaFilterTanggal=true, this.adaFilterStatus=false, this.adaFilterRangeTanggal=true});
  @override
  _FilterBottomSheetState createState() => _FilterBottomSheetState();
}

class _FilterBottomSheetState extends State<FilterBottomSheet> {
  DataDropdown? dataDepartemen;
  DataDropdown? dataCabang;
  DataDropdown? dataPegawai;
  DataDropdown? dataStatus;
  DateTime? monthYear;
  List<DateTime>? dateRange;
  ModelFilter? modelFilter;

  @override
  void initState() {
    super.initState();
    initialFilter();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(create: (context) {
      return monthPicker.MonthPickerBloc(MonthPickerProgressState());
    },
    child: BlocBuilder<AuthBloc, LoginRespon>(
        builder: (BuildContext context, LoginRespon loginRespon){
          return TombolIcon(
            onClick: ()=>_settingModalBottomSheet(loginRespon),
            icon : Icons.filter_alt,
            bgnColor: Colors.white,
            size: 32,
            iconColor: CustomStyle.color1,);
        }),
    );
    return BlocBuilder<AuthBloc, LoginRespon>(
        builder: (BuildContext context, LoginRespon loginRespon){
          return TombolIcon(onClick: ()=>_settingModalBottomSheet(loginRespon),icon : Icons.filter_alt, bgnColor: Colors.white, size: 32, iconColor: CustomStyle.color1,);
        });
    }

    void initialFilter(){
      modelFilter = null;
      BlocProvider.of<AutoCompletePegawaiBloc>(context).add(GetPegawai(null, null));
      BlocProvider.of<cabang.DropdownCabangBloc>(context).add(cabang.GetDataDropdown());
      BlocProvider.of<departemen.DropdownDepartemenBloc>(context).add(departemen.GetDataDropdown());
      BlocProvider.of<monthPicker.MonthPickerBloc>(context).add(monthPicker.SetDate(null));
      BlocProvider.of<dateRangePicker.DateRangePickerBloc>(context).add(dateRangePicker.InitialDate());
      if(widget.adaFilterStatus) BlocProvider.of<status.DropdownStatusBloc>(context).add(status.GetDataDropdown());
    }
    void resetFilter(){
      modelFilter = null;
      BlocProvider.of<AutoCompletePegawaiBloc>(context).add(SetPegawai(null));
      BlocProvider.of<cabang.DropdownCabangBloc>(context).add(cabang.SelectDataDropdown(null));
      BlocProvider.of<departemen.DropdownDepartemenBloc>(context).add(departemen.SelectDataDropdown(null));
      BlocProvider.of<monthPicker.MonthPickerBloc>(context).add(monthPicker.SetDate(null));
      BlocProvider.of<dateRangePicker.DateRangePickerBloc>(context).add(dateRangePicker.InitialDate());
      if(widget.adaFilterStatus) BlocProvider.of<status.DropdownStatusBloc>(context).add(status.GetDataDropdown());
    }

    void _settingModalBottomSheet(LoginRespon loginRespon){

    showModalBottomSheet(
        backgroundColor: Colors.transparent,
        elevation: 0,
        context: context,
        isDismissible: false,
        isScrollControlled: true,
        builder: (context) => StatefulBuilder(
            builder: (BuildContext context, StateSetter setState /*You can rename this!*/) {
              return FutureBuilder<String>(
                  future: PengaturanBahasa().getDataBahasa(),
                  builder: (context, snapshot) {
                    return SingleChildScrollView(
                      child: Padding(
                        padding: EdgeInsets.only(
                            bottom: MediaQuery.of(context).viewInsets.bottom),
                        child: ConstrainedBox(
                          constraints: BoxConstraints(
                              minHeight: widget.adaFilterTanggal?MediaQuery.of(context).size.height/3:MediaQuery.of(context).size.height/4
                          ),
                          child: Container(
                            color: Colors.white,
                            padding: EdgeInsets.fromLTRB(
                                18,14,18,14
                            ),
                            child: Column(
                              children: [
                                Row(children: [
                                  GestureDetector(
                                      onTap: (){
                                        BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
                                        resetFilter();
                                      },
                                      child: Icon(Icons.close, color: CustomStyle.fontColorBlack, size: 23,)),
                                  SizedBox(width: 8,),
                                  Text(snapshot.data == null || snapshot.data == 'en' ? "Search Filters" : "Filter Pencarian", style: TextStyle(color: CustomStyle.fontColorBlack, fontSize: CustomStyle.fontSizeTitle, fontWeight: FontWeight.w700),)
                                ],),
                                SizedBox(height: 24,),
                                loginRespon.dataLogin!.level==4||loginRespon.dataLogin!.level==1||loginRespon.dataLogin!.level==5?
                                BlocListener<cabang.DropdownCabangBloc, cabang.DropdownState>(
                                  listener: (BuildContext context, cabang.DropdownState state){
                                    if(state is cabang.DropdownSuccessState){
                                      dataCabang = state.selectedValue;
                                    }
                                  },
                                  child: DropdownCabang(color: CustomStyle.fontColorBlack, formHeight: 34, radius: 14,),
                                ):Container(),
                                loginRespon.dataLogin!.level==4||loginRespon.dataLogin!.level==5||loginRespon.dataLogin!.level==1||loginRespon.dataLogin!.level==2?
                                BlocListener<departemen.DropdownDepartemenBloc, departemen.DropdownState>(
                                  listener: (BuildContext context, departemen.DropdownState state){
                                    if(state is departemen.DropdownSuccessState) {
                                      BlocProvider.of<AutoCompletePegawaiBloc>(context).add(SetPegawai(null));
                                      dataDepartemen = state.selectedValue;
                                    }
                                  },
                                  child: DropdownDepartemen(color: CustomStyle.fontColorBlack, formHeight: 34, radius: 14,),
                                ):Container(),
                                BlocBuilder<FilterBottomSheetBloc, FilterBottomSheetState>(builder: (context, filterBottomSheetState){
                                  if(filterBottomSheetState is setFilterSuccess){
                                    // print('set success');
                                    // print(filterBottomSheetState.modelFilter!.idPegawai);
                                    return BlocListener<AutoCompletePegawaiBloc, AutoCompletePegawaiState>(
                                      listener: (BuildContext context, AutoCompletePegawaiState state){
                                        if(state is SetPegawaiSuccess) dataPegawai = state.pegawai;
                                        // print(dataPegawai!=null?dataPegawai!.nama:'pegawai kosong');
                                      },
                                      child: AutoCompletePegawai(filterBottomSheetState.modelFilter, fontSize:CustomStyle.fontSizeSmall,radius: 14, formHeight: 34, title: snapshot.data == null || snapshot.data == 'en' ? 'Employee Name' : 'Nama Pegawai', prefixIcon: Icon(Icons.search, size: 20,),),
                                    );
                                  }
                                  else return BlocListener<AutoCompletePegawaiBloc, AutoCompletePegawaiState>(
                                    listener: (BuildContext context, AutoCompletePegawaiState state){
                                      if(state is SetPegawaiSuccess) dataPegawai = state.pegawai;
                                    },
                                    child: AutoCompletePegawai(null, fontSize:CustomStyle.fontSizeSmall,radius: 14, formHeight: 34, title: snapshot.data == null || snapshot.data == 'en' ? 'Employee Name' : 'Nama Pegawai', prefixIcon: Icon(Icons.search, size: 20,),),
                                  );
                                }),
                                widget.adaFilterStatus?BlocListener<status.DropdownStatusBloc, status.DropdownState>(
                                  listener: (BuildContext context, status.DropdownState state){
                                    if(state is status.DropdownSuccessState){
                                      dataStatus = state.selectedValue;
                                    }
                                  },
                                  child: DropdownStatus(color: CustomStyle.fontColorBlack, formHeight: 34, radius: 14,),
                                ):Container(),
                                widget.adaFilterTanggal?Container(
                                  margin: EdgeInsets.only(bottom: 12),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Padding(
                                        padding: const EdgeInsets.only(bottom: 8),
                                        child: Text(
                                          snapshot.data == null || snapshot.data == 'en' ? 'Date' : 'Tanggal',
                                          style: TextStyle(color: CustomStyle.fontColorBlack, fontWeight: FontWeight.bold, fontSize: CustomStyle.fontSizeSmall+1),
                                        ),
                                      ),
                                      Row(
                                        children: [
                                          Expanded(
                                            flex: 3,
                                            child: BlocListener<monthPicker.MonthPickerBloc, monthPicker.MonthPickerState>(
                                              listener: (BuildContext context, monthPicker.MonthPickerState state){
                                                monthYear = state.dateTime;
                                              },
                                              child: TemplateMonthPickerNonFloating(),
                                            ),
                                          ),
                                          SizedBox(width: 8,),
                                          widget.adaFilterRangeTanggal?Expanded(
                                            flex: 5,
                                            child: BlocListener<dateRangePicker.DateRangePickerBloc, dateRangePicker.DateRangePickerState>(
                                              listener: (BuildContext context, dateRangePicker.DateRangePickerState dateRangePickerState){
                                                if(dateRangePickerState is dateRangePicker.DateAvailable) dateRange = dateRangePickerState.date;
                                              },
                                              child: TemplateDateRangePicker(),
                                            ),
                                          ):Container()
                                        ],
                                      ),
                                    ],
                                  ),
                                ):Container(),
                                SizedBox(height: 24,),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                    TemplateButton(
                                      onClick: ()=>resetFilter(),
                                      label: "Reset", expand: true, color: Colors.transparent, contentColor: CustomStyle.color1, fontSize: CustomStyle.fontSizeNormal, bold: true, paddingTopBottom: 0, heightButton: 34,paddingLeftRight: 8,),
                                    TemplateButton(
                                      onClick: (){
                                        modelFilter = ModelFilter(idCabang: dataCabang!=null?dataCabang!.id:null, idDepartemen: dataDepartemen!=null?dataDepartemen!.id:null, dateRange: dateRange, monthYear: monthYear, idPegawai: dataPegawai!=null?dataPegawai!.id:null,namaPegawai: dataPegawai!=null?dataPegawai!.nama:null, status: dataStatus!=null?dataStatus!.id:null);
                                        BlocProvider.of<FilterBottomSheetBloc>(context).add(setFilterBottomSheet(modelFilter)
                                        );
                                        BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
                                      },
                                      label: snapshot.data == null || snapshot.data == 'en' ? "Apply" : "Terapkan", expand: true, color: Colors.transparent, contentColor: CustomStyle.color1, fontSize: CustomStyle.fontSizeNormal, bold: true, paddingTopBottom: 0, heightButton: 34, paddingLeftRight: 8,),
                                  ],
                                )
                              ],
                            ),
                          ),
                        ),
                      ),
                    );
                  }
              );
            }));
  }
}
