"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 }[];
}

export function UnitMapping(props: {
  unit: string;
  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 [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);
    }

    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 setupUnit = (data: UnitType[]) => {
    const temp = data.filter((a) => a.name.includes("POLDA"));
    const temp2 = data.filter((a) => a.name.includes("SATKER"));
    setUnitList(temp);
    setSatkerList(temp2[0].subDestination);
  };

  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">
        <DialogHeader>
          <DialogTitle>{unit}</DialogTitle>
        </DialogHeader>
        {unit === "Polda" ? (
          <Form {...form}>
            <form className="flex flex-col gap-2">
              <div className="flex items-center gap-3">
                <Checkbox
                  id={`all-${unit}`}
                  checked={isAllUnitChecked}
                  disabled={isDetail}
                  onCheckedChange={(checked) => {
                    if (checked) {
                      form.setValue(
                        "items",
                        unitList.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" : "3"}`}
                  >
                    {unitList?.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
                                  disabled={isDetail}
                                  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>
        ) : (
          <Form {...form}>
            <form className="flex flex-col gap-2">
              <div className="flex items-center gap-3">
                <Checkbox
                  id={`all-${unit}`}
                  checked={isAllSatkerChecked}
                  disabled={isDetail}
                  onCheckedChange={(checked) => {
                    if (checked) {
                      form.setValue(
                        "items",
                        satkerList.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" : "3"}`}
                  >
                    {satkerList?.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
                                  disabled={isDetail}
                                  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>
  );
}
