import 'package:absenkuv3/Bloc/Dropdown/DropdownCabangBloc.dart' as cabang;
import 'package:absenkuv3/Bloc/Dropdown/DropdownDepartemenBloc.dart'
    as departemen;
import 'package:absenkuv3/Bloc/Dropdown/DropdownKaryawanBloc.dart';
import 'package:absenkuv3/Bloc/FilterBottomSheetBloc.dart';
import 'package:absenkuv3/UI/Template/CupertinoPicker/UI/CustomCupertinoMonthYearPicker.dart';
// import 'package:absenkuv3/Bloc/FilterBottomSheetBloc.dart';
// import 'package:absenkuv3/Bloc/NavigatorBloc.dart';
import 'package:absenkuv3/UI/Template/DateRangePicker/Bloc/DateRangePickerBloc.dart'
    as dateRangePicker;
import 'package:absenkuv3/Repository/Model/mDropdown.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
// import 'package:absenkuv3/UI/Template/CupertinoPicker/UI/CustomCupertinoDatePicker.dart';
// import 'package:absenkuv3/UI/Template/FilterToggle/Bloc/ToogleFilterBloc.dart';
// import 'package:absenkuv3/UI/Template/CupertinoPicker/Bloc/date_pick_bloc.dart';
// import 'package:absenkuv3/UI/Template/DateRangePicker/Bloc/DateRangePickerBloc.dart';
import 'package:absenkuv3/UI/Template/MonthPicker/Bloc/MonthPickerBloc.dart';
import 'package:absenkuv3/UI/Template/style.dart';
// import 'package:absenkuv3/UI/Template/showToast.dart';
// import 'package:absenkuv3/UI/Template/style.dart';
// import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:month_picker_dialog/month_picker_dialog.dart';

// ignore: must_be_immutable
class MonthYearHeaderChip extends StatefulWidget {
  List<DateTime>? initialData;
  double height;
  DateTime? firstDate;
  DateTime? lastDate;
  bool lastMonth;
  MonthYearHeaderChip(
      {this.initialData,
      this.height = 46,
      this.firstDate,
      this.lastDate,
      this.lastMonth = false}) {
    firstDate = firstDate ?? DateTime(DateTime.now().year - 1);
    lastDate = lastDate ??
        DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day);
  }
  @override
  _MonthYearHeaderChipState createState() => _MonthYearHeaderChipState();
}

class _MonthYearHeaderChipState extends State<MonthYearHeaderChip> {
  DateTime selectedDate = DateTime.now();
  final dateFormat = new DateFormat('MM-yyyy');
  DateTime? maxDate;
  String _selectedFilterTanggal = 'Semua Tanggal Pengajuan';
  ModelFilter modelFilter = ModelFilter();

  DataDropdown? dataCabang;
  DataDropdown? dataDepartemen;
  DataDropdown? dataKaryawan;
  @override
  void initState() {
     BlocProvider.of<MonthPickerBloc>(context)
        .add(SetDate(DateTime.now()));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MultiBlocListener(
        listeners: [
          BlocListener<cabang.DropdownCabangBloc, cabang.DropdownState>(
            listener: (BuildContext context, cabang.DropdownState state) {
              if (state is cabang.DropdownSuccessState) {
                dataCabang = state.selectedValue;
                BlocProvider.of<departemen.DropdownDepartemenBloc>(context).add(
                    departemen.GetDataDropdown(
                        idCabang: state.selectedValue?.id));
              }
            },
          ),
          BlocListener<departemen.DropdownDepartemenBloc,
              departemen.DropdownState>(
            listener: (BuildContext context, departemen.DropdownState state) {
              if (state is departemen.DropdownSuccessState) {
                dataDepartemen = state.selectedValue;
              }
            },
          ),
          BlocListener<DropdownKaryawanBloc, DropdownState>(
            listener: (BuildContext context, DropdownState state) {
              if (state is DropdownSuccessState) {
                dataKaryawan = state.selectedValue;
              }
            },
          ),
        ],
        child: FutureBuilder(
            future: PengaturanBahasa().getDataBahasa(),
            builder: (context, snapshot) {
              String language = snapshot.data.toString();
              return BlocBuilder<MonthPickerBloc, MonthPickerState>(
                  builder: (BuildContext context, MonthPickerState state) {
                if (state is ChangeMonthSuccessState) {
                  return GestureDetector(
                    onTap: () async {
                      _picker(context, true, DateTime.now());
                      // BlocProvider.of<dateRangePicker.DateRangePickerBloc>(
                      //         context)
                      //     .add(dateRangePicker.InitialDate());
                      // final DateTime? picked = await showMonthPicker(
                      //     locale: Locale(snapshot.data ?? 'en'),
                      //     context: context,
                      //     cancelWidget: Text(
                      //         snapshot.data == null || snapshot.data == "en"
                      //             ? "Cancel"
                      //             : "Batal"),
                      //     confirmWidget: Text(
                      //         snapshot.data == null || snapshot.data == "en"
                      //             ? "Apply"
                      //             : "Terapkan"),
                      //     initialDate: state.dateTime != null
                      //         ? state.dateTime!
                      //         : DateTime.now(),
                      //     firstDate: DateTime(2015, 8),
                      //     lastDate: widget.lastMonth
                      //         ? DateTime(
                      //             DateTime.now().year, DateTime.now().month)
                      //         : DateTime(2101));

                      // if (picked != null && picked != selectedDate) {
                      //   BlocProvider.of<MonthPickerBloc>(context)
                      //       .add(SetDate(picked));
                      //   final modelFilter = ModelFilter(
                      //       idPegawai: dataKaryawan?.id,
                      //       namaPegawai: dataKaryawan?.nama,
                      //       monthYear: picked);
                      //   BlocProvider.of<FilterBottomSheetBloc>(context)
                      //       .add(setFilterBottomSheet(modelFilter));
                      // }
                    },
                    child: Chip(
                      backgroundColor: state.dateTime == null ?Colors.grey.shade200:CustomStyle.color1,
                      label: Text(
                        state.dateTime != null
                            ? dateFormat.format(state.dateTime!)
                            : '-',
                        style: TextStyle(
                            fontSize: CustomStyle.fontSizeSmall - 1,
                            color: state.dateTime == null
                                          ? CustomStyle.color1
                                          : Colors.white),
                      ),
                    ),
                  );
                } else
                  return Container();
              });
            }));
  }

  void _picker(
      BuildContext context, bool isStartDate, DateTime initalDateTime) {
    final currentState = BlocProvider.of<MonthPickerBloc>(context).state.dateTime;
    print(currentState);
    DateTime? position;

    if (currentState is DateTime) {
      if (isStartDate) {
        initalDateTime = currentState;
        position = currentState;
      }
    }
    showCupertinoModalPopup(
        context: context,
        builder: (context) {
          DateTime selectedDateTime = initalDateTime;
          return Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(20),
                    topRight: Radius.circular(20))),
            height: 430,
            child: Container(
                child: Column(
              children: [
                Container(
                  height: 10,
                  width: 60,
                  margin: EdgeInsets.symmetric(horizontal: 5, vertical: 5),
                  decoration: BoxDecoration(
                      color: Colors.grey,
                      borderRadius: BorderRadius.circular(20)),
                ),
                Divider(),
                SizedBox(
                  height: 320,
                  child: CustomCupertinoMonthYearPicker(
                    itemExtent: 60,
                    // diameterRatio: 4.0,
                    // magnification: 1.1,
                    selectedDate: isStartDate ? position : initalDateTime,
                    bahasa: 'id',
                    selectionOverlay: Container(
                      width: double.infinity,
                      height: 50,
                      decoration: const BoxDecoration(
                        border: Border.symmetric(
                          horizontal: BorderSide(color: Colors.grey, width: 1),
                        ),
                      ),
                    ),
                    selectedStyle: const TextStyle(
                      color: Colors.blue,
                      fontWeight: FontWeight.w600,
                      fontSize: 24,
                    ),
                    unselectedStyle: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.w600,
                      fontSize: 18,
                    ),
                    disabledStyle: TextStyle(
                      color: Colors.grey[500],
                      fontSize: 18,
                    ),
                    onSelectedItemChanged: (date) {
                      selectedDateTime = date;
                    },
                  ),
                ),
                Divider(),
                Container(
                  width: MediaQuery.sizeOf(context).width - 30,
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.indigo,
                        foregroundColor: Colors.white,
                        minimumSize: Size(double.infinity, 50),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20))),
                    onPressed: () {
                      if (isStartDate) {
                        BlocProvider.of<MonthPickerBloc>(context)
                            .add(SetDate(selectedDateTime));
                        final modelFilter = ModelFilter(
                            idPegawai: dataKaryawan?.id,
                            namaPegawai: dataKaryawan?.nama,
                            monthYear: selectedDateTime);
                        BlocProvider.of<FilterBottomSheetBloc>(context)
                            .add(setFilterBottomSheet(modelFilter));
                        // context
                        //     .read<DatePickBloc>()
                        //     .add(PickStartDateEvent(selectedDateTime));
                      }
                      Navigator.pop(context);
                    },
                    child: Text("Terapkan"),
                  ),
                )
              ],
            )),
          );
        });
  }
}
