"use client";

import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { useEffect, useState } from "react";
import { getUserLevelForAssignments } from "@/service/task";

const FormSchema = z.object({
  items: z.array(z.string()).refine((value) => value.some((item) => item), {
    message: "Required",
  }),
});

interface UnitType {
  id: number;
  name: string;
  subDestination: { id: number; name: string }[] | null;
}

export function UnitMapping(props: {
  unit: "Polda" | "Satker" | "Polres";
  sendDataToParent: (data: string[]) => void;
  isDetail: boolean;
  initData?: string[];
}) {
  const { unit, sendDataToParent, isDetail } = props;
  const [unitList, setUnitList] = useState<UnitType[]>([]);
  const [satkerList, setSatkerList] = useState<{ id: number; name: string }[]>(
    []
  );
  const [polresList, setPolresList] = useState<{ id: number; name: string }[]>(
    []
  );
  const [isOpen, setIsOpen] = useState(false);

  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      items: props.initData ? props.initData : [],
    },
  });

  useEffect(() => {
    async function initState() {
      const response = await getUserLevelForAssignments();
      setupUnit(response?.data?.data.list);
      console.log("list", response?.data?.data.list);
    }

    initState();
  }, []);

  const unitType = form.watch("items");

  const isAllUnitChecked = unitList.every((item) =>
    unitType?.includes(String(item.id))
  );
  const isAllSatkerChecked = satkerList.every((item) =>
    unitType?.includes(String(item.id))
  );
  const isAllPolresChecked = polresList.every((item) =>
    unitType?.includes(String(item.id))
  );

  const setupUnit = (data: UnitType[]) => {
    const temp = data.filter((a) => a.name.includes("POLDA"));
    const temp2 = data.filter((a) => a.name.includes("SATKER"));
    const temp3 = temp.flatMap((item) => item.subDestination || []);
    setUnitList(temp);
    setSatkerList(temp2[0]?.subDestination || []);
    setPolresList(temp3);
  };

  useEffect(() => {
    sendDataToParent(form.getValues("items"));
  }, [unitType]);

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        <a
          onClick={() => setIsOpen(true)}
          className="text-primary cursor-pointer text-xs mr-3"
        >
          Pilih {unit}
        </a>
      </DialogTrigger>
      <DialogContent size="md" className="h-[500px] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{unit}</DialogTitle>
        </DialogHeader>
        <Form {...form}>
          <form className="flex flex-col gap-2">
            <div className="flex items-center gap-3">
              <Checkbox
                id={`all-${unit}`}
                checked={
                  unit === "Polda"
                    ? isAllUnitChecked
                    : unit === "Satker"
                    ? isAllSatkerChecked
                    : isAllPolresChecked
                }
                onCheckedChange={(checked) => {
                  if (checked) {
                    form.setValue(
                      "items",
                      unit === "Polda"
                        ? unitList.map((item) => String(item.id))
                        : unit === "Satker"
                        ? satkerList.map((item) => String(item.id))
                        : polresList.map((item) => String(item.id))
                    );
                  } else {
                    form.setValue("items", []);
                  }
                }}
              />

              <label htmlFor="all" className="text-sm text-black uppercase">
                SEMUA {unit}
              </label>
            </div>
            <FormField
              control={form.control}
              name="items"
              render={() => (
                <FormItem
                  className={`grid grid-cols-${
                    unit === "Polda" ? "2" : unit === "Satker" ? "3" : "4"
                  }`}
                >
                  {(unit === "Polda"
                    ? unitList
                    : unit === "Satker"
                    ? satkerList
                    : polresList
                  )?.map((item: any) => (
                    <FormField
                      key={item.id}
                      control={form.control}
                      name="items"
                      render={({ field }) => {
                        return (
                          <FormItem
                            key={String(item.id)}
                            className="flex flex-row items-center space-x-3 space-y-0"
                          >
                            <FormControl>
                              <Checkbox
                                checked={field.value?.includes(String(item.id))}
                                onCheckedChange={(checked) => {
                                  return checked
                                    ? field.onChange([
                                        ...field.value,
                                        String(item.id),
                                      ])
                                    : field.onChange(
                                        field.value?.filter(
                                          (value) => value !== String(item.id)
                                        )
                                      );
                                }}
                              />
                            </FormControl>
                            <p className="text-sm text-black">{item.name}</p>
                          </FormItem>
                        );
                      }}
                    />
                  ))}
                  <FormMessage />
                </FormItem>
              )}
            />
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
