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/Bloc/NavigatorBloc.dart';
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/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';

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

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

  DataDropdown? dataCabang;
  DataDropdown? dataDepartemen;
  DataDropdown? dataKaryawan;
  @override
  void initState() {
    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<DateRangePickerBloc, DateRangePickerState>(
                builder: (BuildContext context,
                    DateRangePickerState dateRangePickerState) {
                  String label = language == 'id'?'Filter Tanggal':'Date Filter';
                  bool aktif = false;
                  if (dateRangePickerState is DateAvailable) {
                    if (dateRangePickerState.date[0] ==
                        DateTime(DateTime.now().year - 1000)) {
                      label =  language == 'id'?'Semua Tanggal':'All Date';
                    } else if (dateRangePickerState.date[0] ==
                        DateTime(
                            DateTime.now().year, DateTime.now().month - 1, 1)) {
                      label = language == 'id'? 'Bulan Lalu':'Last Month';
                    } else if (dateRangePickerState.date[0] ==
                        DateTime(
                            DateTime.now().year, DateTime.now().month, 1)) {
                      label =  language == 'id'?'Bulan Ini':'Current Month';
                    } else {
                      label =
                          '${dateFormat.format(dateRangePickerState.date[0])} s/d ${dateFormat.format(dateRangePickerState.date[1])}';
                    }
                    if (dateRangePickerState.date[0] != null) {
                      aktif = true;
                    }
                  }
                  return BlocListener<ToogleFilterBloc, ToogleFilterState?>(
                      listener:
                          (BuildContext context, ToogleFilterState? state) {
                        if (state is SuccessToogleChangeState)
                          _selectedFilterTanggal = state.toogleChange;
                      },
                      child: GestureDetector(
                          onTap: () {
                            _showModalBottomSheet(
                                context, _selectedFilterTanggal);
                          },
                          child: Chip(
                              backgroundColor:
                                  aktif ? CustomStyle.color1 : Colors.grey.shade200,
                              label: Text(
                                label,
                                style: TextStyle(
                                    color: aktif
                                        ? Colors.white
                                        : CustomStyle.color1),
                              ))));
                },
              );
            }));
  }

  void _showModalBottomSheet(
      BuildContext context, String? _selectedFilterTanggal) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      // showDragHandle: true,
      barrierColor: Colors.black.withOpacity(0.5),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20), topRight: Radius.circular(20)),
      ),
      builder: (context) {
        return FutureBuilder(
          future: PengaturanBahasa().getDataBahasa(),
          builder: (context, snapshot) {
            final String language = snapshot.data ?? 'id';
            final Map<String, String> filterOptions = {
              'Semua Tanggal Pengajuan':
                  language == 'id' ? 'Semua Tanggal Pengajuan' : 'All Dates',
              'Bulan Lalu': language == 'id' ? 'Bulan Lalu' : 'Last Month',
              'Bulan Ini': language == 'id' ? 'Bulan Ini' : 'Current Month',
              'Pilih Tanggal Sendiri': language == 'id'
                  ? 'Pilih Tanggal Sendiri'
                  : 'Choose Your Own Date',
            };
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  padding: EdgeInsets.only(top: 15, bottom: 10),
                  child: Container(
                    height: 5,
                    width: 50,
                    decoration: BoxDecoration(
                      color: Colors.grey,
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                ),
                Container(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
                  margin: EdgeInsets.only(right: 10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // SizedBox(width: 10),
                      Padding(
                        padding: const EdgeInsets.only(left: 10),
                        child: Text(
                            language == 'id'
                                ? 'Filter Tanggal Pengajuan'
                                : 'Submission Date Filter',
                            style: TextStyle(
                                fontSize: 19, fontWeight: FontWeight.w500)),
                      ),
                      GestureDetector(
                        onTap: () => BlocProvider.of<NavigatorBloc>(context)
                            .add(NavigatePop(context)),
                        child: Icon(Icons.close, color: Colors.black, size: 23),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 15,
                ),
                BlocBuilder<ToogleFilterBloc, ToogleFilterState?>(
                  builder: (BuildContext context, ToogleFilterState? state) {
                    if (state is SuccessToogleChangeState) {
                      DateTime? startdate;
                      DateTime? enddate;
                      return Container(
                        padding: EdgeInsets.only(left: 10),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            ...filterOptions.entries.map((entry) {
                              return _buildFilterOption(
                                context: context,
                                label: entry.value,
                                value: entry.key,
                                selectedValue: _selectedFilterTanggal,
                                onChanged: (value) {
                                  _selectedFilterTanggal = value;
                                  BlocProvider.of<ToogleFilterBloc>(context)
                                      .add(ChangeEvent(context, value));
                                  if (value == 'Pilih Tanggal Sendiri') {
                                    context
                                        .read<DatePickBloc>()
                                        .add(ClearDatesEvent());
                                  }
                                },
                              );
                            }).toList(),
                            if (_selectedFilterTanggal ==
                                'Pilih Tanggal Sendiri')
                              BlocBuilder<DatePickBloc, DatePickState>(
                                builder: (context, state) {
                                  DateTime? pickstartDate;
                                  DateTime? pickendDate;
                                  if (state is DateSelected) {
                                    pickstartDate = state.startDate;
                                    pickendDate = state.endDate;
                                  }
                                  return Column(
                                    children: [
                                      _buildDatePick(context, pickstartDate,
                                          pickendDate, language),
                                      SizedBox(height: 20),
                                      _buildApplyButton(
                                          context,
                                          _selectedFilterTanggal,
                                          pickstartDate,
                                          pickendDate,
                                          language),
                                      SizedBox(height: 20),
                                    ],
                                  );
                                },
                              ),
                            if (_selectedFilterTanggal !=
                                'Pilih Tanggal Sendiri')
                              Column(
                                children: [
                                  SizedBox(height: 10),
                                  _buildApplyButton(
                                      context,
                                      _selectedFilterTanggal,
                                      startdate,
                                      enddate,
                                      language),
                                  SizedBox(height: 20),
                                ],
                              )
                          ],
                        ),
                      );
                    } else {
                      return Container();
                    }
                  },
                ),
              ],
            );
          },
        );
      },
    );
  }

  Widget _buildDatePick(
      context, DateTime? startDate, DateTime? endDate, String language) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 10.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    language == 'id' ? 'Mulai Dari' : 'Start Date',
                    style: TextStyle(fontSize: 14, fontWeight: FontWeight.w400),
                  ),
                  GestureDetector(
                    onTap: () {
                      cupertinoPicker(context, true);
                    },
                    child: Container(
                      padding:
                          EdgeInsets.symmetric(horizontal: 10, vertical: 15),
                      child: Text(startDate == null
                          ? 'DD-MM-YYYY'
                          : DateFormat('dd-MM-yyyy').format(startDate)),
                    ),
                  ),
                  Container(
                    decoration: BoxDecoration(color: Colors.grey),
                    height: 0.5,
                    width: MediaQuery.of(context).size.width / 2 - 30,
                  ),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(right: 10.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    language == 'id' ? 'Sampai Dengan' : 'End Date',
                    style: TextStyle(fontSize: 14, fontWeight: FontWeight.w400),
                  ),
                  GestureDetector(
                    onTap: startDate == null
                        ? null
                        : () {
                            cupertinoPicker(context, false);
                          },
                    child: Container(
                      padding:
                          EdgeInsets.symmetric(horizontal: 10, vertical: 15),
                      child: Text(endDate == null
                          ? 'DD-MM-YYYY'
                          : DateFormat('dd-MM-yyyy').format(endDate)),
                    ),
                  ),
                  Container(
                    decoration: BoxDecoration(color: Colors.grey),
                    height: 0.5,
                    width: MediaQuery.of(context).size.width / 2 - 30,
                  ),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildFilterOption({
    required BuildContext context,
    required String label,
    required String value,
    required String? selectedValue,
    required Function(String) onChanged,
  }) {
    return Column(
      children: [
        GestureDetector(
          onTap: () => onChanged(value),
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(label,
                    style:
                        TextStyle(fontWeight: FontWeight.w500, fontSize: 15)),
                Radio<String>(
                  visualDensity: VisualDensity(vertical: -3),
                  value: value,
                  groupValue: selectedValue,
                  activeColor: selectedValue == value
                      ? CustomStyle.color1
                      : Colors.transparent,
                  onChanged: (value) => onChanged(value!),
                ),
              ],
            ),
          ),
        ),
        Divider(
          thickness: 0.5,
          color: CustomStyle.fontColorGrey,
          // indent: 10,
          // endIndent: 10
        ),
      ],
    );
  }

  Widget _buildApplyButton(
    BuildContext context,
    String? _selectedFilterTanggal,
    DateTime? startDate,
    DateTime? endDate,
    String snapshot,
  ) {
    final DateTime now = DateTime.now();
    final DateTime startOfMonth = DateTime(now.year, now.month, 1);

    // Helper function to set the filter
    void _applyFilter(DateTime startDate, DateTime endDate) {
      final modelFilter = ModelFilter(
        idCabang: dataCabang?.id,
        idDepartemen: dataDepartemen?.id,
        idPegawai: dataKaryawan?.id,
        dateRange: [startDate, endDate],
      );
      BlocProvider.of<DateRangePickerBloc>(context)
          .add(SetDate([startDate, endDate]));
      BlocProvider.of<FilterBottomSheetBloc>(context)
          .add(setFilterBottomSheet(modelFilter));
      BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
    }

    // Helper function to show toast error message
    void _showToast(String messageId, String messageEn) {
      showToastMessageError(
        context: context,
        message: snapshot == 'id' ? messageId : messageEn,
      );
    }

    // Determine date range based on selected filter
    void _handleFilter() {
      switch (_selectedFilterTanggal) {
        case 'Semua Tanggal Pengajuan':
          _applyFilter(DateTime(now.year - 1000), now);
          break;
        case 'Bulan Lalu':
          final DateTime firstDayOfLastMonth =
              DateTime(now.year, now.month - 1, 1);
          final DateTime lastDayOfLastMonth =
              startOfMonth.subtract(Duration(days: 1));
          _applyFilter(firstDayOfLastMonth, lastDayOfLastMonth);
          break;
        case 'Bulan Ini':
          final DateTime lastDayOfThisMonth =
              DateTime(now.year, now.month + 1, 1).subtract(Duration(days: 1));
          _applyFilter(startOfMonth, lastDayOfThisMonth);
          break;
        case 'Pilih Tanggal Sendiri':
          if (startDate == null) {
            _showToast(
                'Tanggal Mulai Belum Dipilih', 'Start Date Not Selected');
          } else if (endDate == null) {
            _showToast(
                'Tanggal Selesai Belum Dipilih', 'End Date Not Selected');
          } else {
            _applyFilter(startDate, endDate);
          }
          break;
        default:
          _showToast('Pilihan Tidak Valid', 'Invalid Selection');
          break;
      }
    }

    return TemplateButton(
      label: snapshot == 'id' ? 'Terapkan' : 'Apply',
      heightButton: 40,
      fontSize: 15,
      color: CustomStyle.color1,
      widthButton: MediaQuery.of(context).size.width - 20,
      onClick: _handleFilter,
    );
  }

  void cupertinoPicker(BuildContext context, bool isStartDate) {
    final currentState = BlocProvider.of<DatePickBloc>(context).state;
    DateTime initialDateTime = DateTime.now();
    DateTime? minimumDate;

    if (currentState is DateSelected) {
      if (isStartDate) {
        initialDateTime = currentState
            .startDate; // Set initialDateTime to the chosen startDate
      } else {
        minimumDate = currentState.startDate;
        initialDateTime = currentState.startDate.isAfter(DateTime.now())
            ? currentState.startDate
            : DateTime.now();
      }
    }
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      isScrollControlled: true,
      builder: (context) {
        DateTime selectedDateTime = initialDateTime;
        return FutureBuilder(
          future: PengaturanBahasa().getDataBahasa(),
          builder: (BuildContext context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    height: 5,
                    width: 50,
                    margin: EdgeInsets.symmetric(horizontal: 10, vertical: 15),
                    decoration: BoxDecoration(
                        color: Colors.grey,
                        borderRadius: BorderRadius.circular(10)),
                  ),
                  Divider(),
                  SizedBox(
                    height: 300,
                    child: CustomCupertinoDatePicker(
                      itemExtent: 50,
                      minDate: minimumDate,
                      selectedDate:
                          isStartDate ? initialDateTime : initialDateTime,
                      // selectedDate: isStartDate && (currentState is DateSelected) currentState.startDate ?,
                      diameterRatio: 4.0,
                      magnification: 0.9,
                      bahasa: snapshot.data,
                      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,
                    margin: EdgeInsets.all(10),
                    child: TemplateButton(
                      label: snapshot.data == 'id' ? "Terapkan" : 'Apply',
                      heightButton: 45,
                      fontSize: 15,
                      color: CustomStyle.color1,
                      widthButton: MediaQuery.of(context).size.width - 20,
                      onClick: () {
                        if (isStartDate) {
                          context
                              .read<DatePickBloc>()
                              .add(PickStartDateEvent(selectedDateTime));
                        } else {
                          context
                              .read<DatePickBloc>()
                              .add(PickEndDateEvent(selectedDateTime));
                        }
                        Navigator.pop(context);
                      },
                    ),
                  )
                  // Container(
                  //   width: MediaQuery.sizeOf(context).width - 30,
                  //   padding: EdgeInsets.only(bottom: 10),
                  //   child: ElevatedButton(
                  //     style: ElevatedButton.styleFrom(
                  //         backgroundColor: Colors.blue,
                  //         foregroundColor: Colors.white,
                  //         shape: RoundedRectangleBorder(
                  //             borderRadius: BorderRadius.circular(20))),
                  //     onPressed: () {
                  //       if (isStartDate) {
                  //         context
                  //             .read<DatePickBloc>()
                  //             .add(PickStartDateEvent(selectedDateTime));
                  //       } else {
                  //         context
                  //             .read<DatePickBloc>()
                  //             .add(PickEndDateEvent(selectedDateTime));
                  //       }
                  //       Navigator.pop(context);
                  //     },
                  //     child: Text(snapshot.data == 'id' ? "Terapkan" : 'Apply'),
                  //   ),
                  // )
                ],
              );
            } else {
              return Container();
            }
          },
        );
      },
    );
  }

}
