import 'package:absensi_sas/app/constant.dart';
import 'package:absensi_sas/model/approval_type_model.dart';
import 'package:absensi_sas/provider/approval_filter_provider.dart';
import 'package:absensi_sas/widget/custom_button_approval.dart';
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:intl/intl.dart';

class FilterBottomSheet extends HookConsumerWidget {
  const FilterBottomSheet({
    super.key,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final currApprovalTypeState = ref.read(approvalFilterProvider);
    final approvalTypeList = [
      ApprovalTypeModel(id: "1", name: "Presensi", isActive: false, value: "p"),
      ApprovalTypeModel(id: "2", name: "Cuti", isActive: true, value: "c"),
      ApprovalTypeModel(id: "3", name: "Lembur", isActive: false, value: "l"),
    ];
    final staffFocuseNode = useFocusNode();
    final startDateFocusNode = useFocusNode();
    final endDateFocusNode = useFocusNode();
    final staffCtr =
        useTextEditingController(text: currApprovalTypeState.keyword);
    final startDateCtr = useTextEditingController(
        text: DateFormat('dd-MM-yyyy').format(currApprovalTypeState.startDate));
    final startDateState = useState(currApprovalTypeState.startDate);
    final endDateCtr = useTextEditingController(
        text: DateFormat('dd-MM-yyyy').format(currApprovalTypeState.endDate));
    final endDateState = useState(currApprovalTypeState.endDate);
    final dateKey = useState(0);

    final selectedApprovalTypeState = useState<List<String>>(
        currApprovalTypeState.selectedApprovalType.toList());
    final checkboxKey = useState(1000);

    selectApprovalTypeFunction(String value) {
      var tmp = selectedApprovalTypeState.value;
      var cek = tmp.contains(value);
      if (cek) {
        tmp.remove(value);
      } else {
        tmp.add(value);
      }
      selectedApprovalTypeState.value = tmp;
      checkboxKey.value = checkboxKey.value + 1;
    }

    return Container(
      padding: EdgeInsets.only(
          bottom: MediaQuery.of(context).viewInsets.bottom * 0.75),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(32), topRight: Radius.circular(32))),
      child: SingleChildScrollView(
        child: Container(
          margin: EdgeInsets.symmetric(
              horizontal: Constant.getActualXPhone(context: context, x: 24)),
          height: MediaQuery.of(context).size.height * 0.75,
          child: Column(
            children: [
              Container(
                height: MediaQuery.of(context).size.height * 0.1,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      "Filter",
                      style: Constant.titleH1_700(context: context),
                    ),
                    IconButton(
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        icon: Icon(Icons.close))
                  ],
                ),
              ),
              Container(
                height: MediaQuery.of(context).size.height * 0.55,
                // color: Colors.green,

                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "Staff",
                        style: Constant.titleH1_700_18(context: context)
                            .copyWith(fontWeight: FontWeight.w700),
                      ),
                      SizedBox(
                        height:
                            Constant.getActualYPhone(context: context, y: 16),
                      ),
                      TextFormField(
                        controller: staffCtr,
                        focusNode: staffFocuseNode,
                        style: Constant.titleH1_500_18(context: context),
                        decoration: InputDecoration(
                            focusColor: Constant.textOrange,
                            // hoverColor: Constant.textOrange,
                            suffixIcon: Icon(
                              EvaIcons.searchOutline,
                              color: staffFocuseNode.hasFocus
                                  ? Constant.textOrange
                                  : Color(0xff212B36),
                            ),
                            label: Text(
                              "Cari Staff",
                              style: Constant.titleH1_500_18(context: context)
                                  .copyWith(
                                      color: staffFocuseNode.hasFocus
                                          ? Constant.textOrange
                                          : Colors.grey.shade400),
                            ),
                            hintText: "Cari Staff",
                            isDense: false,
                            contentPadding: EdgeInsets.symmetric(
                                vertical: Constant.getActualYPhone(
                                    context: context, y: 16),
                                horizontal: Constant.getActualXPhone(
                                    context: context, x: 14)),
                            hintStyle:
                                Constant.titleH1_500_18(context: context),
                            focusedBorder: OutlineInputBorder(
                                borderSide:
                                    BorderSide(color: Constant.textOrange),
                                borderRadius: BorderRadius.circular(8)),
                            enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(
                                    color: Colors.grey.shade500, width: 1),
                                borderRadius: BorderRadius.circular(8)),
                            border: OutlineInputBorder(
                                borderSide:
                                    BorderSide(color: Colors.grey.shade500),
                                borderRadius: BorderRadius.circular(8))),
                      ),
                      SizedBox(
                        height:
                            Constant.getActualYPhone(context: context, y: 20),
                      ),
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              "Tanggal Awal",
                              style: Constant.titleH1_700_18(context: context)
                                  .copyWith(fontWeight: FontWeight.w700),
                            ),
                          ),
                          SizedBox(
                            width: Constant.getActualXPhone(
                                context: context, x: 20),
                          ),
                          Expanded(
                            child: Text(
                              "Tanggal Akhir",
                              style: Constant.titleH1_700_18(context: context)
                                  .copyWith(fontWeight: FontWeight.w700),
                            ),
                          )
                        ],
                      ),
                      SizedBox(
                        height:
                            Constant.getActualYPhone(context: context, y: 20),
                      ),
                      Row(
                        children: [
                          Expanded(
                            child: TextFormField(
                              key: ValueKey(dateKey.value),
                              controller: startDateCtr,
                              focusNode: startDateFocusNode,
                              readOnly: true,
                              style: Constant.titleH1_500_18(context: context),
                              decoration: InputDecoration(
                                  focusColor: Constant.textOrange,
                                  // hoverColor: Constant.textOrange,
                                  suffixIcon: Icon(
                                    EvaIcons.calendar,
                                    color: startDateFocusNode.hasFocus
                                        ? Constant.textOrange
                                        : Color(0xff212B36),
                                  ),
                                  label: Text(
                                    "Tanggal Awal",
                                    style: Constant.titleH1_500_18(
                                            context: context)
                                        .copyWith(
                                            overflow: TextOverflow.ellipsis,
                                            color: startDateFocusNode.hasFocus
                                                ? Constant.textOrange
                                                : Colors.grey.shade400),
                                  ),
                                  hintText: "Tanggal Awal",
                                  isDense: false,
                                  contentPadding: EdgeInsets.symmetric(
                                      vertical: Constant.getActualYPhone(
                                          context: context, y: 16),
                                      horizontal: Constant.getActualXPhone(
                                          context: context, x: 14)),
                                  hintStyle:
                                      Constant.titleH1_500_18(context: context)
                                          .copyWith(
                                              overflow: TextOverflow.ellipsis),
                                  focusedBorder: OutlineInputBorder(
                                      borderSide: BorderSide(
                                          color: Constant.textOrange),
                                      borderRadius: BorderRadius.circular(8)),
                                  enabledBorder: OutlineInputBorder(
                                      borderSide: BorderSide(
                                          color: Colors.grey.shade500,
                                          width: 1),
                                      borderRadius: BorderRadius.circular(8)),
                                  border: OutlineInputBorder(
                                      borderSide: BorderSide(
                                          color: Colors.grey.shade500),
                                      borderRadius: BorderRadius.circular(8))),
                              onTap: () async {
                                startDateFocusNode.requestFocus();
                                dateKey.value = dateKey.value + 1;
                                DateTime? pickedDate = await showDatePicker(
                                    helpText: "Tanggal Awal",
                                    // locale: Locale('id', 'ID'),
                                    builder: (context, child) {
                                      return Theme(
                                          data: ThemeData().copyWith(
                                              datePickerTheme:
                                                  DatePickerThemeData(
                                                      dayBackgroundColor:
                                                          MaterialStateProperty
                                                              .resolveWith(
                                                                  (states) {
                                                        if (states.contains(
                                                            MaterialState
                                                                .selected)) {
                                                          return Constant
                                                              .textOrange;
                                                        }
                                                        return Colors.white;
                                                      }),
                                                      todayBackgroundColor:
                                                          MaterialStateProperty
                                                              .resolveWith(
                                                                  (states) {
                                                        if (states.contains(
                                                            MaterialState
                                                                .selected)) {
                                                          return Constant
                                                              .textOrange;
                                                        }
                                                        return Colors.white;
                                                      }),
                                                      todayBorder: BorderSide(
                                                          style:
                                                              BorderStyle.solid,
                                                          color: Constant
                                                              .textOrange,
                                                          width: 1),
                                                      headerBackgroundColor:
                                                          Constant.textOrange,
                                                      headerForegroundColor:
                                                          Colors.white,
                                                      surfaceTintColor:
                                                          Colors.white,
                                                      backgroundColor:
                                                          Colors.white),
                                              primaryColor: Constant.textOrange,
                                              primaryColorDark:
                                                  Constant.textOrange,
                                              primaryColorLight:
                                                  Constant.textOrange),
                                          child: child!);
                                    },
                                    confirmText: "OK",
                                    cancelText: "Batal",
                                    context: context,
                                    initialDate: startDateState.value,
                                    firstDate: DateTime(1950),
                                    initialEntryMode:
                                        DatePickerEntryMode.calendarOnly,
                                    lastDate: DateTime(2100));

                                if (pickedDate != null) {
                                  print(
                                      pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                                  String formattedDate =
                                      DateFormat('dd-MM-yyyy')
                                          .format(pickedDate);
                                  print(
                                      formattedDate); //formatted date output using intl package =>  2021-03-16
                                  startDateCtr.text =
                                      formattedDate; //set output date to TextField value.
                                  startDateState.value = pickedDate;
                                  startDateFocusNode.requestFocus();
                                } else {}
                              },
                            ),
                          ),
                          SizedBox(
                            width: Constant.getActualXPhone(
                                context: context, x: 20),
                          ),
                          Expanded(
                            child: TextFormField(
                              key: ValueKey(dateKey.value),
                              controller: endDateCtr,
                              focusNode: endDateFocusNode,
                              readOnly: true,
                              style: Constant.titleH1_500_18(context: context),
                              decoration: InputDecoration(
                                  focusColor: Constant.textOrange,
                                  // hoverColor: Constant.textOrange,
                                  suffixIcon: Icon(
                                    EvaIcons.calendar,
                                    color: endDateFocusNode.hasFocus
                                        ? Constant.textOrange
                                        : Color(0xff212B36),
                                  ),
                                  label: Text(
                                    "Tanggal Akhir",
                                    style: Constant.titleH1_500_18(
                                            context: context)
                                        .copyWith(
                                            overflow: TextOverflow.ellipsis,
                                            color: endDateFocusNode.hasFocus
                                                ? Constant.textOrange
                                                : Colors.grey.shade400),
                                  ),
                                  hintText: "Tanggal Akhir",
                                  isDense: false,
                                  contentPadding: EdgeInsets.symmetric(
                                      vertical: Constant.getActualYPhone(
                                          context: context, y: 16),
                                      horizontal: Constant.getActualXPhone(
                                          context: context, x: 14)),
                                  hintStyle:
                                      Constant.titleH1_500_18(context: context)
                                          .copyWith(
                                              overflow: TextOverflow.ellipsis),
                                  focusedBorder: OutlineInputBorder(
                                      borderSide: BorderSide(
                                          color: Constant.textOrange),
                                      borderRadius: BorderRadius.circular(8)),
                                  enabledBorder: OutlineInputBorder(
                                      borderSide: BorderSide(
                                          color: Colors.grey.shade500,
                                          width: 1),
                                      borderRadius: BorderRadius.circular(8)),
                                  border: OutlineInputBorder(
                                      borderSide: BorderSide(
                                          color: Colors.grey.shade500),
                                      borderRadius: BorderRadius.circular(8))),
                              onTap: () async {
                                endDateFocusNode.requestFocus();
                                dateKey.value = dateKey.value + 1;
                                DateTime? pickedDate = await showDatePicker(
                                    helpText: "Tanggal Akhir",
                                    // locale: Locale('id', 'ID'),
                                    builder: (context, child) {
                                      return Theme(
                                          data: ThemeData().copyWith(
                                              datePickerTheme:
                                                  DatePickerThemeData(
                                                      dayBackgroundColor:
                                                          MaterialStateProperty
                                                              .resolveWith(
                                                                  (states) {
                                                        if (states.contains(
                                                            MaterialState
                                                                .selected)) {
                                                          return Constant
                                                              .textOrange;
                                                        }
                                                        return Colors.white;
                                                      }),
                                                      todayBackgroundColor:
                                                          MaterialStateProperty
                                                              .resolveWith(
                                                                  (states) {
                                                        if (states.contains(
                                                            MaterialState
                                                                .selected)) {
                                                          return Constant
                                                              .textOrange;
                                                        }
                                                        return Colors.white;
                                                      }),
                                                      todayBorder: BorderSide(
                                                          style:
                                                              BorderStyle.solid,
                                                          color: Constant
                                                              .textOrange,
                                                          width: 1),
                                                      headerBackgroundColor:
                                                          Constant.textOrange,
                                                      headerForegroundColor:
                                                          Colors.white,
                                                      surfaceTintColor:
                                                          Colors.white,
                                                      backgroundColor:
                                                          Colors.white),
                                              primaryColor: Constant.textOrange,
                                              primaryColorDark:
                                                  Constant.textOrange,
                                              primaryColorLight:
                                                  Constant.textOrange),
                                          child: child!);
                                    },
                                    confirmText: "OK",
                                    cancelText: "Batal",
                                    context: context,
                                    initialDate: startDateState.value,
                                    firstDate: DateTime(1950),
                                    initialEntryMode:
                                        DatePickerEntryMode.calendarOnly,
                                    lastDate: DateTime(2100));

                                if (pickedDate != null) {
                                  print(
                                      pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                                  String formattedDate =
                                      DateFormat('dd-MM-yyyy')
                                          .format(pickedDate);
                                  print(
                                      formattedDate); //formatted date output using intl package =>  2021-03-16
                                  endDateCtr.text =
                                      formattedDate; //set output date to TextField value.
                                  endDateState.value = pickedDate;
                                  endDateFocusNode.requestFocus();
                                } else {}
                              },
                            ),
                          )
                        ],
                      ),
                      SizedBox(
                        height:
                            Constant.getActualYPhone(context: context, y: 16),
                      ),
                      // Text(
                      //   ref
                      //       .watch(approvalFilterProvider)
                      //       .selectedApprovalType
                      //       .toString(),
                      //   style: Constant.titleH1_700_18(context: context),
                      // ),
                      Text(
                        "Approval",
                        style: Constant.titleH1_700_18(context: context)
                            .copyWith(fontWeight: FontWeight.w700),
                      ),
                      SizedBox(
                        height:
                            Constant.getActualYPhone(context: context, y: 16),
                      ),
                      ...approvalTypeList.map(
                        (e) {
                          return Row(
                            children: [
                              Checkbox(
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(4)),
                                value: selectedApprovalTypeState.value
                                    .contains(e.value),
                                onChanged: (val) {
                                  selectApprovalTypeFunction(e.value!);
                                },
                              ),
                              Text(
                                e.name ?? "",
                                style: Constant.titleH1_700_18(context: context)
                                    .copyWith(fontWeight: FontWeight.normal),
                              )
                            ],
                          );
                        },
                      )
                    ],
                  ),
                ),
              ),
              Container(
                height: MediaQuery.of(context).size.height * 0.1,
                child: Row(
                  children: [
                    Expanded(
                      child: CustomButtonWhite(
                          btnText: "Reset",
                          onPressed: () {
                            ref.read(approvalFilterProvider.notifier).state =
                                ApprovalFilterProvider(
                                    startDate: DateTime.now(),
                                    endDate: DateTime.now(),
                                    keyword: "",
                                    selectedApprovalType: []);
                            Navigator.pop(context);
                          }),
                    ),
                    SizedBox(
                      width: Constant.getActualXPhone(context: context, x: 24),
                    ),
                    Expanded(
                      child: CustomButtonOrange(
                          btnText: "Simpan",
                          onPressed: () {
                            ref.read(approvalFilterProvider.notifier).state =
                                ApprovalFilterProvider(
                                    endDate: endDateState.value,
                                    keyword: staffCtr.text,
                                    selectedApprovalType:
                                        selectedApprovalTypeState.value,
                                    startDate: startDateState.value);
                            Navigator.pop(context);
                          }),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
