import 'package:absenkuv3/Bloc/NavigatorBloc.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_bloc.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'
    as monthPicker;
import 'package:absenkuv3/UI/Template/Snackbar/CustomSnackbar.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 TemplateFilterToggle extends StatefulWidget {
  List<DateTime>? initialData;
  double height;
  DateTime? firstDate;
  DateTime? lastDate;
  TemplateFilterToggle(
      {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
  _TemplateFilterToggleState createState() => _TemplateFilterToggleState();
}

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

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

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: PengaturanBahasa().getDataBahasa(),
        builder: (context, snapshot) {
          String language = snapshot.data.toString();
          return BlocBuilder<DateRangePickerBloc, DateRangePickerState>(
            builder: (BuildContext context,
                DateRangePickerState dateRangePickerState) {
              String label = '-';
              DateTime startDate = DateTime(DateTime.now().year,
                  DateTime.now().month, DateTime.now().day);
              DateTime endDate = DateTime(DateTime.now().year,
                  DateTime.now().month, DateTime.now().day);
              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])}';
                }
                startDate = dateRangePickerState.date[0];
                endDate = dateRangePickerState.date[1];
              }
              return BlocListener<ToogleFilterBloc, ToogleFilterState?>(
                  listener: (BuildContext context, ToogleFilterState? state) {
                    if (state is SuccessToogleChangeState)
                      _selectedFilterTanggal = state.toogleChange;
                  },
                  child: GestureDetector(
                    onTap: () {
                      BlocProvider.of<ToogleFilterBloc>(context)
                          .add(InitStateEvent(context));
                      _showModalBottomSheet(context, _selectedFilterTanggal);
                    },
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.fromLTRB(16, 7, 16, 7),
                          decoration: BoxDecoration(
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.grey.withOpacity(0.3),
                                  spreadRadius: 2,
                                  blurRadius: 5,
                                  offset: Offset(
                                      0, 1), // changes position of shadow
                                ),
                              ],
                              gradient: LinearGradient(
                                  begin: Alignment.centerLeft,
                                  end: Alignment.centerRight,
                                  stops: [
                                    0.0,
                                    0.5,
                                    1.0
                                  ],
                                  colors: [
                                    CustomStyle.color1,
                                    CustomStyle.color1,
                                    // Colors.lightBlue,
                                    CustomStyle.color1,
                                  ]),
                              borderRadius: new BorderRadius.all(
                                Radius.circular(20),
                              )),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                snapshot.data == null
                                    ? "Filter Tanggal Pengajuan"
                                    : snapshot.data == 'id'
                                        ? "Filter Tanggal Pengajuan"
                                        : "Date Range",
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.w600,
                                    fontSize: CustomStyle.fontSizeSmall),
                              ),
                              SizedBox(
                                height: 1,
                              ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  SizedBox(
                                    width: 8,
                                  ),
                                  Text(
                                    label,
                                    style: TextStyle(
                                        fontSize: CustomStyle.fontSizeSmall - 1,
                                        color: Colors.white),
                                  ),
                                  SizedBox(
                                    width: 4,
                                  ),
                                  Icon(Icons.keyboard_arrow_down,
                                      color: Colors.white, size: 18)
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ));
            },
          );
        });
  }

  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) {
    return TemplateButton(
      label: snapshot == 'id' ? 'Terapkan' : 'Apply',
      heightButton: 50,
      fontSize: 15,
      color: CustomStyle.color1,
      widthButton: MediaQuery.of(context).size.width - 20,
      onClick: () {
        if (_selectedFilterTanggal == 'Semua Tanggal Pengajuan') {
          BlocProvider.of<DateRangePickerBloc>(context).add(
              SetDate([DateTime(DateTime.now().year - 1000), DateTime.now()]));
          BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
        } else if (_selectedFilterTanggal == 'Bulan Lalu') {
          final now = DateTime.now();
          final firstDayOfLastMonth = DateTime(now.year, now.month - 1, 1);
          final lastDayOfLastMonth =
              DateTime(now.year, now.month, 1).subtract(Duration(days: 1));
          BlocProvider.of<DateRangePickerBloc>(context)
              .add(SetDate([firstDayOfLastMonth, lastDayOfLastMonth]));
          BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
        } else if (_selectedFilterTanggal == 'Bulan Ini') {
          BlocProvider.of<DateRangePickerBloc>(context).add(SetDate([
            DateTime(DateTime.now().year, DateTime.now().month, 1),
            DateTime(DateTime.now().year, DateTime.now().month + 1, 1)
                .subtract(Duration(days: 1))
          ]));
          BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
        } else if (_selectedFilterTanggal == 'Pilih Tanggal Sendiri') {
          if (startDate == null) {
            CustomSnackBar.show(
                    context,snapshot == 'id'
                    ? 'Tanggal Mulai Belum Di Pilih'
                    : 'Start Date Not Selected',
                    SnackBarType.warning);
          } else if (endDate == null) {
            CustomSnackBar.show(
                    context,snapshot == 'id'
                    ? 'Tanggal Selesai Belum Di Pilih'
                    : 'End Date Not Selected',
                    SnackBarType.warning);
          } else {
            BlocProvider.of<DateRangePickerBloc>(context)
                .add(SetDate([startDate, endDate]));
            BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
          }
        }
      },
    );
  }

  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;
      } else {
        minimumDate = currentState.startDate;
        initialDateTime = currentState.startDate.isAfter(DateTime.now())
            ? currentState.startDate
            : currentState.endDate ?? DateTime.now();
      }
    }
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      isScrollControlled: true,
      // showDragHandle: 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);
                      },
                    ),
                  )
                  
                ],
              );
            } else {
              return Container();
            }
          },
        );
      },
    );
  }

}
