import { zodResolver } from "@hookform/resolvers/zod";
import Button from "../../components/Button/Button";
import { Grid } from "../../components/Grid/Grid";
import Textfield from "../../components/Textfeild/Textfeild";
import { useForm, Controller } from "react-hook-form";
import { zValidateString } from "../../data/getFormTypeErrors";
import { z } from "zod";
import { useApiMutation } from "../../utils/useApiRequest";
import { useToast } from "../../hooks/useToast";
import { useModalStore } from "../../context/zustand-store/appStore";
import AutoComplete from "../../components/AutoComplete/AutoComplete";
import { useEffect, useState } from "react";
import { getFaPermissions } from "../../utils/getFaPermissions";
import Checkbox from "../../components/CheckBox/CheckBox";

type FormValues = z.infer<typeof schema>;
type AddAccessProps = {
  getData: () => void;
  item?: any;
};

const schema = z.object({
  access: zValidateString("نام صفحه"),
  description: zValidateString("توضیحات"),
  selectedPageId: z
    .array(z.union([z.string(), z.number()]))
    .min(1, { message: "لطفاً یک صفحه انتخاب کنید." }),
  modify_state: z.boolean(),
});

export const AddAccess = ({ getData, item }: AddAccessProps) => {
  const showToast = useToast();
  const { closeModal } = useModalStore();

  const [selectedKeys, setSelectedKeys] = useState<(string | number)[]>([]);
  const [data, setData] = useState<any>([]);
  const [pagesData, setPagesData] = useState<any>(null);

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      access: item?.name || "",
      description: item?.description || "",
      selectedPageId: [],
      modify_state: item?.modify_state || false,
    },
  });

  useEffect(() => {
    if (selectedKeys.length > 0) {
      setValue("selectedPageId", selectedKeys);
    }
  }, [selectedKeys, setValue]);

  useEffect(() => {
    if (pagesData?.results && item?.page) {
      const matchingPage = pagesData.results.find(
        (page: any) => page.name === item.page
      );
      if (matchingPage) {
        const keys = [matchingPage.id];
        setSelectedKeys(keys);
        setValue("selectedPageId", keys);
      }
    }
  }, [pagesData, item, setValue]);

  const handleChangeComplete = (newSelectedKeys: (number | string)[]) => {
    setSelectedKeys(newSelectedKeys);
  };

  const mutationPages = useApiMutation({
    api: "/auth/api/v1/page/",
    method: "get",
  });

  const mutation = useApiMutation({
    api: `/auth/api/v1/permission/${item ? item?.id + "/" : ""}`,
    method: item ? "put" : "post",
  });

  const getPages = async () => {
    const data = await mutationPages.mutateAsync({
      page: 1,
      page_size: 1000,
    });
    setPagesData(data);
  };

  useEffect(() => {
    getPages();
  }, []);

  useEffect(() => {
    if (pagesData?.results) {
      const d = pagesData.results.map((page: any) => ({
        key: page.id,
        value: `${getFaPermissions(page.name)} (${page.name})`,
      }));
      setData(d);
    }
  }, [pagesData]);

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        name: data.access,
        description: data.description,
        category: "api",
        meta: {},
        page: selectedKeys[0],
        modify_state: data?.modify_state,
      });
      showToast("عملیات با موفقیت انجام شد", "success");
      closeModal();
      getData();
    } catch (error: any) {
      if (error.status === 400) {
        showToast("این دسترسی تکراری است!", "error");
      }
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Grid container column className="gap-2">
        <Controller
          name="selectedPageId"
          control={control}
          render={({ field }) => (
            <AutoComplete
              data={data}
              selectedKeys={selectedKeys}
              onChange={(newSelectedKeys) => {
                handleChangeComplete(newSelectedKeys);
                field.onChange(newSelectedKeys);
              }}
              title="انتخاب صفحه"
              error={!!errors.selectedPageId}
              helperText={errors.selectedPageId?.message}
            />
          )}
        />

        <Controller
          name="access"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="نام دسترسی"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.access}
              helperText={errors.access?.message}
            />
          )}
        />

        <Controller
          name="description"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="توضیحات"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.description}
              helperText={errors.description?.message}
            />
          )}
        />

        <Controller
          name="modify_state"
          control={control}
          render={({ field }) => (
            <Checkbox
              checked={field.value}
              onChange={field.onChange}
              label="دسترسی داخلی"
            />
          )}
        />

        <Button type="submit">ثبت</Button>
      </Grid>
    </form>
  );
};
