import 'dart:async';
import 'dart:convert';

import 'package:dropdown_button2/dropdown_button2.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';
import '/models/history_model.dart';
import '/models/history_type_model.dart';
import '/provider/history_filter_provider.dart';
import '/screen/history_screen/history_list_card.dart';
import '/screen/history_screen/history_list_provider.dart';
import '/screen/history_screen/history_type_provider.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
// import 'package:eva_icons_flutter/eva_icons_flutter.dart';

import '../../app/constant.dart';
import '../../provider/current_user_provider.dart';
import '../../widget/header_widget.dart';
import '../../widget/snackbar_widget.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final historyListData = useState<List<HistoryModel>>([]);
    final historyListLoading = useState(false);
    final isMounted = useIsMounted();
    final mCourirID =
        ref.watch(currentUserProvider)?.model.user?.mCourierID ?? "0";
    final dateFilter =
        DateFormat('d MMM y').format(ref.watch(dateFilterProvider));
    final SelectedTypeFilter = ref.watch(selectedTypeProvider);

    fetchData() {
      ref.read(HistoryListProvider.notifier).getData(
          id: mCourirID,
          date: DateFormat('dd-MM-yyyy').format(ref.watch(dateFilterProvider)),
          type: SelectedTypeFilter.tipeid.toString());
    }

    final dateInput = useTextEditingController(
        text: DateFormat('yyyy-MM-dd').format(DateTime.now()));

    // ref.watch(dateFilterProvider);

    ref.listen<HistoryListState>(
      HistoryListProvider,
      (previous, next) {
        if (next is HistoryListStateLoading) {
          historyListLoading.value = true;
        } else if (next is HistoryListStateError) {
          print(next.message);
          historyListLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
        } else if (next is HistoryListStateDone) {
          print(next.model);
          historyListData.value = next.model;
          historyListLoading.value = false;
        }
      },
    );
    useEffect(() {
      // final cancellationSource = CancellationSource();
      if (isMounted.call()) {
        WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
          fetchData();
        });
      }
      return () {};
    }, []);
    return RefreshIndicator(
      onRefresh: () async {
        fetchData();
      },
      child: Container(
          // color: const Color(0XFFF4F6F8),
          child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            color: Colors.white,
            height: Constant.getActualY(context: context, y: 56),
          ),
          HeaderWidget(teks: "Riwayat"),
          SizedBox(
            height: Constant.getActualY(context: context, y: 24),
          ),
          Container(
            width: double.infinity,
            margin: EdgeInsets.only(
                left: Constant.getActualX(context: context, x: 31),
                right: Constant.getActualX(context: context, x: 31)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Text(
                      SelectedTypeFilter.tipename.toString(),
                      style: Constant.body1(context: context)
                          .copyWith(fontWeight: FontWeight.w600),
                    ),
                    SizedBox(
                      width: Constant.getActualX(context: context, x: 5),
                    ),
                    Icon(
                      Icons.fiber_manual_record_rounded,
                      size: 9,
                    ),
                    SizedBox(
                      width: Constant.getActualX(context: context, x: 5),
                    ),
                    Chip(
                      label: Text(
                        dateFilter,
                        style: Constant.body3(context: context).copyWith(
                            fontWeight: FontWeight.w700,
                            color: Colors.grey.shade600),
                      ),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(Radius.circular(6))),
                    )
                  ],
                ),
                InkWell(
                  onTap: () {
                    showModalBottomSheet<void>(
                      isScrollControlled: true,
                      context: context,
                      builder: (BuildContext context) {
                        return HookConsumer(
                            builder: (BuildContext context, WidgetRef ref, a) {
                          final typeLoading = useState(false);
                          final typeData =
                              useState<List<HistoryTypeModel>>(List.empty());
                          final dateCtr = useTextEditingController(
                              // d MMMM y'
                              text: DateFormat('yyyy-MM-dd')
                                  .format(ref.read(dateFilterProvider)));
                          final selectedType = useState<HistoryTypeModel>(
                              ref.watch(selectedTypeProvider));
                          getData() {
                            ref
                                .read(HistoryTypeListProvider.notifier)
                                .getHistoryType();
                          }

                          useEffect(() {
                            WidgetsBinding.instance
                                .addPostFrameCallback((timeStamp) async {
                              getData();
                            });

                            return () {};
                          }, []);
                          ref.listen(HistoryTypeListProvider, (previous, next) {
                            if (next is HistoryTypeListStateInit) {
                              typeLoading.value = true;
                            } else if (next is HistoryTypeListStateLoading) {
                              typeLoading.value = true;
                            } else if (next is HistoryTypeListStateError) {
                              typeLoading.value = false;
                            } else if (next is HistoryTypeListStateDone) {
                              print(jsonEncode(next.model));
                              typeData.value = next.model;
                              typeLoading.value = false;
                            }
                          });
                          return Container(
                            margin: EdgeInsets.symmetric(
                                horizontal: Constant.getActualX(
                                    context: context, x: 31)),
                            height:
                                Constant.getActualY(context: context, y: 370),
                            child: Column(
                              // mainAxisAlignment: MainAxisAlignment.center,
                              mainAxisSize: MainAxisSize.min,
                              children: <Widget>[
                                SizedBox(
                                  height: Constant.getActualY(
                                      context: context, y: 20),
                                ),
                                SizedBox(
                                    width: Constant.getActualX(
                                        context: context, x: 100),
                                    child: Divider(
                                      color: Colors.grey,
                                      height: 2,
                                      thickness: 2,
                                    )),
                                SizedBox(
                                  height: Constant.getActualY(
                                      context: context, y: 20),
                                ),
                                Text(
                                  "Filter",
                                  style: Constant.heading3(context: context)
                                      .copyWith(
                                          fontWeight: FontWeight.w600,
                                          color: Constant.primaryBlue),
                                ),
                                SizedBox(
                                  height: Constant.getActualY(
                                      context: context, y: 20),
                                ),
                                TextField(
                                  controller: dateCtr,
                                  decoration: InputDecoration(
                                      suffixIcon: Icon(Icons.today_rounded),
                                      border: OutlineInputBorder(
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(8))),
                                      labelText:
                                          "Tanggal (yyyy-mm-dd)" //label text of field
                                      ),
                                  readOnly: true,
                                  onTap: () async {
                                    DateTime? pickedDate = await showDatePicker(
                                        context: context,
                                        initialDate:
                                            DateTime.parse(dateCtr.text),
                                        // initialDate:
                                        //     DateTime.parse(dateCtr.text),
                                        firstDate: DateTime(1950),
                                        initialEntryMode:
                                            DatePickerEntryMode.calendarOnly,
                                        //DateTime.now() - not to allow to choose before today.
                                        lastDate: DateTime(2100));

                                    if (pickedDate != null) {
                                      print(
                                          pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                                      String formattedDate =
                                          DateFormat('yyyy-MM-dd')
                                              .format(pickedDate);
                                      print(
                                          formattedDate); //formatted date output using intl package =>  2021-03-16
                                      dateCtr.text =
                                          formattedDate; //set output date to TextField value.
                                      // ref
                                      //     .read(dateFilterProvider.notifier)
                                      //     .state = pickedDate;
                                    } else {}
                                  },
                                ),
                                SizedBox(
                                  height: Constant.getActualY(
                                      context: context, y: 20),
                                ),
                                Container(
                                  // width: Constant.getActualX(
                                  //     context: context, x: 320),
                                  // height: Constant.getActualY(
                                  //     context: context, y: 56),
                                  child: DropdownButtonHideUnderline(
                                    child: DropdownButton2<HistoryTypeModel>(
                                      isExpanded: true,
                                      hint: Row(
                                        children: [
                                          Expanded(
                                            child: Text(
                                              'Select Item',
                                              style: Constant.body1(
                                                      context: context)
                                                  .copyWith(
                                                      fontWeight:
                                                          FontWeight.w600,
                                                      color:
                                                          Constant.primaryDark),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                        ],
                                      ),
                                      items: typeData.value
                                          .map((HistoryTypeModel option) {
                                        return DropdownMenuItem<
                                            HistoryTypeModel>(
                                          value: option,
                                          child: Text(
                                            option.tipename.toString(),
                                            style: Constant.body1(
                                                    context: context)
                                                .copyWith(
                                                    color: Constant.textBlack,
                                                    fontWeight:
                                                        FontWeight.w600),
                                          ),
                                        );
                                      }).toList(),
                                      value: selectedType.value,
                                      onChanged: (HistoryTypeModel? newValue) {
                                        selectedType.value = newValue!;
                                        // if (newValue) {
                                        // ref
                                        //     .read(selectedTypeProvider.notifier)
                                        //     .state = newValue!;
                                        print(
                                            "Branch ID Selected : ${selectedType.value.tipename}");
                                        print(
                                            "Branch Code Selected : ${selectedType.value.tipename}");
                                        // }
                                      },
                                      buttonStyleData: ButtonStyleData(
                                        padding: EdgeInsets.only(
                                          left: Constant.getActualX(
                                              context: context, x: 10),
                                          right: Constant.getActualX(
                                              context: context, x: 10),
                                        ),

                                        decoration: BoxDecoration(
                                          // color: Colors.white,
                                          border: Border.all(
                                              color: Colors.grey.shade400),

                                          borderRadius:
                                              BorderRadius.circular(8),
                                        ),
                                        // elevation: 2,
                                      ),
                                      iconStyleData: IconStyleData(
                                        icon: typeLoading.value
                                            ? LoadingAnimationWidget
                                                .discreteCircle(
                                                    color: Constant.primaryBlue,
                                                    size: 20)
                                            : Icon(
                                                Icons
                                                    .keyboard_arrow_down_outlined,
                                              ),
                                        iconSize: 24,
                                        iconEnabledColor: Constant.textBlack,
                                        iconDisabledColor: Colors.grey,
                                      ),
                                      dropdownStyleData: DropdownStyleData(
                                        maxHeight: Constant.getActualY(
                                            context: context, y: 120),
                                        width: Constant.getActualX(
                                            context: context, x: 320),
                                        padding: EdgeInsets.only(
                                          top: Constant.getActualY(
                                              context: context, y: 10),
                                          left: Constant.getActualX(
                                              context: context, x: 10),
                                          right: Constant.getActualX(
                                              context: context, x: 10),
                                          bottom: Constant.getActualY(
                                              context: context, y: 10),
                                        ),
                                        decoration: BoxDecoration(
                                          // color: Constant.backgroundWhite,
                                          borderRadius:
                                              BorderRadius.circular(8),
                                        ),
                                        // elevation: 8,
                                        scrollbarTheme: ScrollbarThemeData(
                                          radius: const Radius.circular(40),
                                          thickness:
                                              MaterialStateProperty.all<double>(
                                                  6),
                                          thumbVisibility:
                                              MaterialStateProperty.all<bool>(
                                                  true),
                                        ),
                                      ),
                                      menuItemStyleData: MenuItemStyleData(
                                        height: Constant.getActualY(
                                            context: context, y: 56),
                                        padding: EdgeInsets.only(
                                          top: Constant.getActualY(
                                              context: context, y: 10),
                                          left: Constant.getActualX(
                                              context: context, x: 10),
                                          right: Constant.getActualX(
                                              context: context, x: 10),
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  height: Constant.getActualY(
                                      context: context, y: 40),
                                ),
                                Container(
                                  width: double.infinity,
                                  height: Constant.getActualY(
                                      context: context, y: 48),
                                  child: ElevatedButton(
                                    onPressed: () {
                                      ref
                                          .read(selectedTypeProvider.notifier)
                                          .state = selectedType.value;
                                      ref
                                          .read(dateFilterProvider.notifier)
                                          .state = DateTime.parse(dateCtr.text);
                                      ref
                                          .read(HistoryListProvider.notifier)
                                          .getData(
                                              id: mCourirID,
                                              date: DateFormat('dd-MM-yyyy')
                                                  .format(ref.watch(
                                                      dateFilterProvider)),
                                              type: ref
                                                  .watch(selectedTypeProvider)
                                                  .tipeid!);
                                      Navigator.pop(context);
                                    },
                                    child: Text(
                                      "Cari",
                                      style: Constant.heading3(context: context)
                                          .copyWith(
                                              fontWeight: FontWeight.w700),
                                    ),
                                    style: ButtonStyle(
                                      backgroundColor:
                                          MaterialStateColor.resolveWith(
                                              (st) => Constant.primaryBlue),
                                      shape: MaterialStateProperty.all<
                                          RoundedRectangleBorder>(
                                        RoundedRectangleBorder(
                                          borderRadius:
                                              BorderRadius.circular(8),
                                          // side: BorderSide(color: Colors.red),
                                        ),
                                      ),
                                      shadowColor: MaterialStateProperty.all(
                                          const Color(0xffff48423d)),
                                      elevation: MaterialStateProperty.all(4.0),
                                    ),
                                  ),
                                )
                              ],
                            ),
                          );
                        });
                      },
                    );
                  },
                  child: Icon(
                    Icons.filter_alt_outlined,
                    size: 25,
                  ),
                )
              ],
            ),
          ),
          Container(
            // color: Colors.red,
            height: Constant.getActualY(context: context, y: 588),
            child: historyListLoading.value
                ? Center(
                    child: LoadingAnimationWidget.fourRotatingDots(
                        color: Constant.primaryBlue, size: 50),
                  )
                : HistoryListCard(ListRiwayat: historyListData.value),
          ),
        ],
      )),
    );
  }
}
