import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '/models/pending_work_model.dart';
import '/models/work_list_model.dart';
import '/models/work_type_model.dart';
import '/widget/snackbar_widget.dart';
import '/widget/work_card.dart';
import '/screen/work_list_screen/work_list_provider.dart';
import '/screen/work_list_screen/work_status_provider.dart';
import '/screen/work_list_screen/work_supervisor_moder.dart';
import '/screen/work_list_screen/work_type_provider.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../../app/constant.dart';
import '../../models/work_status_model.dart';
import '../../models/work_supervisor_model.dart';
import '../../provider/current_user_provider.dart';
import '../../widget/header_widget.dart';

// ignore: camel_case_types
enum arrStatus { baru, pending, done }

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final selectedStatus = useState<String>("");
    final selectedTipe = useState<List<int>>(List.empty());
    final selectedSupervisor = useState<List<String>>(List.empty());
    final workTypeData = useState<List<WorkTypeModel>>([]);
    final workTypeLoading = useState(false);
    final workStatusData = useState<List<WorkStatusModel>>([]);
    final workStatusLoading = useState(false);
    final workSupervisorData = useState<List<WorkSupervisorModel>>([]);
    final workSupervisorLoading = useState(false);
    final workListData = useState<List<WorkListModel>>([]);
    final workListLoading = useState(false);
    final change = useState(1);

    final mCourirID =
        ref.watch(currentUserProvider)?.model.user?.mCourierID ?? "0";
    fetchData() {
      ref.read(WorkTypeProvider.notifier).getData();
      ref.read(WorkStatusProvider.notifier).getData();
      ref.read(WorkSupervisorProvider.notifier).getData();
      // ref
      //     .read(WorkListProvider.notifier)
      //     .getData(id: mCourirID, tipeId: "x", status: "N-p", supervisor: "N");
      ref.read(WorkListProvider.notifier).getData(
          id: mCourirID,
          tipeId: "1-2-3-4-5",
          status: "N'-'P'-'D",
          supervisor: "N'-'Y'-'X");
    }

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        fetchData();
      });
      return () {};
    }, []);

    filterData() {
      var status =
          selectedStatus.value.isNotEmpty ? selectedStatus.value : "N'-'P'-'D";
      var supervisor = selectedSupervisor.value.isNotEmpty
          ? selectedSupervisor.value.join("'-'")
          : "N'-'Y'-'X";
      var tipe = selectedTipe.value.isNotEmpty
          ? selectedTipe.value.join('-')
          : "1-2-3-4-5";
      // print("selected status value : ${status}");
      // print("selected supervisor value :" + supervisor);
      // print("selected tipe value :" + tipe);
      ref.read(WorkListProvider.notifier).getData(
          id: mCourirID, tipeId: tipe, status: status, supervisor: supervisor);
    }

    ref.listen(WorkTypeProvider, (previous, next) {
      if (next is WorkTypeStateLoading) {
        workTypeLoading.value = true;
      } else if (next is WorkTypeStateError) {
        workTypeLoading.value = false;
        // print(next.message);
        SanckbarWidget(context, next.message, snackbarType.error);
      } else if (next is WorkTypeStateDone) {
        workTypeLoading.value = false;
        workTypeData.value = next.model;
      }
    });
    ref.listen(WorkStatusProvider, (previous, next) {
      if (next is WorkStatusStateLoading) {
        workStatusLoading.value = true;
      } else if (next is WorkStatusStateError) {
        workStatusLoading.value = false;
        // print(next.message);
        SanckbarWidget(context, next.message, snackbarType.error);
      } else if (next is WorkStatusStateDone) {
        // print(jsonEncode(next.model));
        workStatusLoading.value = false;
        var newData = next.model;
        var newStatus = [];
        next.model.forEach((e) {
          newStatus.add(e.statusid);
        });
        newData.insert(
            0,
            WorkStatusModel(
                statusid: newStatus.join("'-'"), statusname: "Semua"));
        selectedStatus.value = newStatus.join("'-'");
        workStatusData.value = newData;
      }
    });
    ref.listen(WorkSupervisorProvider, (previous, next) {
      if (next is WorkSupervisorStateLoading) {
        workSupervisorLoading.value = true;
      } else if (next is WorkSupervisorStateError) {
        workSupervisorLoading.value = false;
        // print(next.message);
        SanckbarWidget(context, next.message, snackbarType.error);
      } else if (next is WorkSupervisorStateDone) {
        // print(jsonEncode(next.model));
        workSupervisorLoading.value = false;
        workSupervisorData.value = next.model;
      }
    });
    ref.listen(WorkListProvider, (previous, next) {
      if (next is WorkListStateLoading) {
        workListLoading.value = true;
      } else if (next is WorkListStateError) {
        workListLoading.value = false;
        // print(next.message);

        SanckbarWidget(context, next.message, snackbarType.error);
      } else if (next is WorkListStateDone) {
        // print(jsonEncode(next.model));
        workListLoading.value = false;
        workListData.value = next.model;
      }
    });
    selectedStatus.addListener(() {
      // print("change");
      change.value = change.value++;
    });
    return RefreshIndicator(
      onRefresh: () async {
        filterData();
      },
      child: Container(
        color: const Color(0XFFF4F6F8),
        child: Column(
          children: [
            Container(
              color: Colors.white,
              height: Constant.getActualY(context: context, y: 56),
            ),
            const HeaderWidget(
              teks: "List Pekerjaan",
            ),
            Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                SizedBox(
                    // color: Colors.red,
                    child: InkWell(
                        // splashColor: Colors.red,
                        onTap: () {
                          showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (context) {
                              return AlertDialog(
                                content: HookBuilder(builder: (context) {
                                  final a = useState(1);
                                  return SizedBox(
                                    width: Constant.getActualX(
                                        context: context, x: 280),
                                    height: Constant.getActualY(
                                        context: context, y: 692),
                                    child: Column(
                                      children: [
                                        SizedBox(
                                          height: Constant.getActualY(
                                              context: context, y: 36),
                                          width: Constant.getActualX(
                                              context: context, x: 280),
                                          // color: Colors.red,
                                          child: Row(
                                            // crossAxisAlignment:
                                            //     CrossAxisAlignment.end,
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Text(
                                                "Filter",
                                                style: Constant.body1(
                                                        context: context)
                                                    .copyWith(
                                                        fontWeight:
                                                            FontWeight.w600,
                                                        color: Constant
                                                            .textPrimary),
                                              ),
                                              IconButton(
                                                  iconSize: 20,
                                                  splashRadius: 20,
                                                  onPressed: () {
                                                    filterData();
                                                    Navigator.pop(context);
                                                  },
                                                  icon: const Icon(Icons.clear))
                                            ],
                                          ),
                                        ),
                                        const Divider(),
                                        SizedBox(
                                          height: Constant.getActualY(
                                              context: context, y: 24),
                                        ),
                                        Container(
                                          height: Constant.getActualY(
                                              context: context, y: 590),
                                          margin: EdgeInsets.only(
                                              left: Constant.getActualX(
                                                  context: context, x: 48)),
                                          // color: Colors.red,
                                          child: ListView(
                                            children: [
                                              Text(
                                                "Tipe",
                                                style: Constant.body1(
                                                        context: context)
                                                    .copyWith(
                                                        fontWeight:
                                                            FontWeight.w600,
                                                        color: Constant
                                                            .textPrimary),
                                              ),
                                              SizedBox(
                                                height: Constant.getActualY(
                                                    context: context, y: 8),
                                              ),
                                              workTypeLoading.value
                                                  ? LoadingAnimationWidget
                                                      .progressiveDots(
                                                          color: Constant
                                                              .primaryBlue,
                                                          size: 50)
                                                  : Column(
                                                      children:
                                                          workTypeData.value
                                                              .map(
                                                                (e) => SizedBox(
                                                                  child: Row(
                                                                    children: [
                                                                      Checkbox(
                                                                          shape: RoundedRectangleBorder(
                                                                              borderRadius: BorderRadius.circular(
                                                                                  5)),
                                                                          value: selectedTipe.value.contains(e
                                                                              .id),
                                                                          onChanged:
                                                                              (value) {
                                                                            var sp =
                                                                                selectedTipe.value.toSet().toList();
                                                                            if (value ==
                                                                                true) {
                                                                              sp.add(int.parse(e.id.toString()));
                                                                            } else {
                                                                              sp.remove(int.parse(e.id.toString()));
                                                                            }
                                                                            selectedTipe.value =
                                                                                sp;
                                                                            // print(value);
                                                                            // print(e.id);

                                                                            a.value =
                                                                                a.value++;
                                                                          }),
                                                                      SizedBox(
                                                                        height: Constant.getActualY(
                                                                            context:
                                                                                context,
                                                                            y: 8),
                                                                      ),
                                                                      Expanded(
                                                                        child:
                                                                            Text(
                                                                          e.name
                                                                              .toString(),
                                                                          maxLines:
                                                                              2,
                                                                          overflow:
                                                                              TextOverflow.ellipsis,
                                                                          style: Constant.body3(context: context).copyWith(
                                                                              fontWeight: FontWeight.w400,
                                                                              color: Constant.textPrimary),
                                                                        ),
                                                                      ),
                                                                    ],
                                                                  ),
                                                                ),
                                                              )
                                                              .toList(),
                                                    ),
                                              SizedBox(
                                                height: Constant.getActualY(
                                                    context: context, y: 24),
                                              ),
                                              Text(
                                                "Status",
                                                style: Constant.body1(
                                                        context: context)
                                                    .copyWith(
                                                        fontWeight:
                                                            FontWeight.w600,
                                                        color: Constant
                                                            .textPrimary),
                                              ),
                                              SizedBox(
                                                height: Constant.getActualY(
                                                    context: context, y: 8),
                                              ),
                                              workStatusLoading.value
                                                  ? LoadingAnimationWidget
                                                      .progressiveDots(
                                                          color: Constant
                                                              .primaryBlue,
                                                          size: 50)
                                                  : Column(
                                                      children: workStatusData
                                                          .value
                                                          .map((e) {
                                                        return SizedBox(
                                                          child: Row(
                                                            children: [
                                                              Radio(
                                                                  value: e
                                                                      .statusid,
                                                                  groupValue:
                                                                      selectedStatus
                                                                          .value,
                                                                  onChanged:
                                                                      (baru) {
                                                                    selectedStatus
                                                                            .value =
                                                                        baru!;

                                                                    a.value = a
                                                                        .value++;
                                                                  }),
                                                              SizedBox(
                                                                height: Constant
                                                                    .getActualY(
                                                                        context:
                                                                            context,
                                                                        y: 8),
                                                              ),
                                                              Text(
                                                                "${e.statusname}",
                                                                style: Constant.body3(
                                                                        context:
                                                                            context)
                                                                    .copyWith(
                                                                        fontWeight:
                                                                            FontWeight
                                                                                .w400,
                                                                        color: Constant
                                                                            .textPrimary),
                                                              ),
                                                            ],
                                                          ),
                                                        );
                                                      }).toList(),
                                                    ),
                                              SizedBox(
                                                height: Constant.getActualY(
                                                    context: context, y: 24),
                                              ),
                                              Text(
                                                "Supervisor",
                                                style: Constant.body1(
                                                        context: context)
                                                    .copyWith(
                                                        fontWeight:
                                                            FontWeight.w600,
                                                        color: Constant
                                                            .textPrimary),
                                              ),
                                              SizedBox(
                                                height: Constant.getActualY(
                                                    context: context, y: 8),
                                              ),
                                              workSupervisorLoading.value
                                                  ? LoadingAnimationWidget
                                                      .progressiveDots(
                                                          color: Constant
                                                              .primaryBlue,
                                                          size: 50)
                                                  : Column(
                                                      children:
                                                          workSupervisorData
                                                              .value
                                                              .map(
                                                                (e) => SizedBox(
                                                                  child: Row(
                                                                    children: [
                                                                      Checkbox(
                                                                          shape: RoundedRectangleBorder(
                                                                              borderRadius: BorderRadius.circular(
                                                                                  5)),
                                                                          value: selectedSupervisor.value.contains(e
                                                                              .supervisorid),
                                                                          onChanged:
                                                                              (value) {
                                                                            var sp =
                                                                                selectedSupervisor.value.toSet().toList();
                                                                            if (value ==
                                                                                true) {
                                                                              sp.add(e.supervisorid!);
                                                                            } else {
                                                                              sp.remove(e.supervisorid!);
                                                                            }
                                                                            selectedSupervisor.value =
                                                                                sp;
                                                                            // print(value);
                                                                            // print(e.supervisorid);

                                                                            a.value =
                                                                                a.value++;
                                                                          }),
                                                                      SizedBox(
                                                                        height: Constant.getActualY(
                                                                            context:
                                                                                context,
                                                                            y: 8),
                                                                      ),
                                                                      Flexible(
                                                                        child:
                                                                            Text(
                                                                          e.supervisorname
                                                                              .toString(),
                                                                          style: Constant.body3(context: context).copyWith(
                                                                              fontWeight: FontWeight.w400,
                                                                              color: Constant.textPrimary),
                                                                          maxLines:
                                                                              5,
                                                                          overflow:
                                                                              TextOverflow.ellipsis,
                                                                        ),
                                                                      ),
                                                                      SizedBox(
                                                                        height: Constant.getActualY(
                                                                            context:
                                                                                context,
                                                                            y: 8),
                                                                      ),
                                                                      if (e.supervisorid ==
                                                                          "Y")
                                                                        Icon(
                                                                          size:
                                                                              25,
                                                                          Icons
                                                                              .check_circle_outline_rounded,
                                                                          color:
                                                                              Constant.primaryGreen,
                                                                        ),
                                                                      if (e.supervisorid ==
                                                                          'N')
                                                                        Icon(
                                                                          size:
                                                                              25,
                                                                          Icons
                                                                              .help_outline_rounded,
                                                                          color:
                                                                              Constant.primaryYellow,
                                                                        ),
                                                                      if (e.supervisorid ==
                                                                          "X")
                                                                        Icon(
                                                                          size:
                                                                              25,
                                                                          Icons
                                                                              .cancel_outlined,
                                                                          color:
                                                                              Constant.primaryRed,
                                                                        )
                                                                    ],
                                                                  ),
                                                                ),
                                                              )
                                                              .toList(),
                                                    ),
                                            ],
                                          ),
                                        )
                                      ],
                                    ),
                                  );
                                }),
                              );
                            },
                          );
                        },
                        child: Row(
                          children: [
                            Text(
                              "Filters",
                              style: Constant.caption1(context: context)
                                  .copyWith(color: Constant.textPrimary),
                            ),
                            Icon(
                              size:
                                  Constant.getActualY(context: context, y: 20),
                              Icons.filter_alt_outlined,
                              color: Constant.textPrimary,
                            )
                          ],
                        ))),
              ],
            ),
            Container(
              height: Constant.getActualY(context: context, y: 641),
              // color: Colors.red,
              padding: EdgeInsets.symmetric(
                  horizontal: Constant.getActualX(context: context, x: 32),
                  vertical: 1),
              child: workListLoading.value
                  ? LoadingAnimationWidget.fourRotatingDots(
                      color: Constant.primaryBlue, size: 50)
                  : ListView.builder(
                      itemCount: workListData.value.length,
                      itemBuilder: (context, index) {
                        var data = workListData.value[index];
                        return WorkCardWidget(data: data);
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }
}
