import { zodResolver } from "@hookform/resolvers/zod";
import Button from "../../components/Button/Button";
import { Grid } from "../../components/Grid/Grid";
import { useForm, Controller } from "react-hook-form";
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 { useFetchProfile } from "../../hooks/useFetchProfile";

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

const schema = z.object({
  selectedAccessId: z
    .array(z.union([z.string(), z.number()]))
    .min(1, { message: "لطفاً یک دسترسی را انتخاب کنید." }),
});

export const EditAccess = ({ getData, item }: AddAccessProps) => {
  const showToast = useToast();
  const { closeModal } = useModalStore();
  const { getProfile } = useFetchProfile();
  const [selectedKeys, setSelectedKeys] = useState<(string | number)[]>([]);
  const [data, setData] = useState<any>([]);
  const [accessData, setAccessData] = useState<any>(null);

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      selectedAccessId: [],
    },
  });

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

  useEffect(() => {
    if (accessData?.results && item?.permissions) {
      const permissionPageAccesses = item.permissions.flatMap(
        (option: any) => option.page_access || []
      );

      const matchingPages = accessData.results.filter((page: any) =>
        permissionPageAccesses.includes(page.name)
      );

      const matchingIds = matchingPages.map((page: any) => page.id);

      if (matchingIds.length > 0) {
        setSelectedKeys(matchingIds);
        setValue("selectedAccessId", matchingIds);
      } else {
        setSelectedKeys([]);
        setValue("selectedAccessId", []);
      }
    }
  }, [accessData, item, setValue]);

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

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

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

  const getPages = async () => {
    const data = await mutationUserAccess.mutateAsync({
      page: 1,
      page_size: 10000,
    });
    setAccessData(data);
  };

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

  useEffect(() => {
    if (accessData?.results) {
      const sortedResults = [...accessData.results].sort((a, b) => {
        if (a.page < b.page) return -1;
        if (a.page > b.page) return 1;
        return 0;
      });

      const d = sortedResults.map((access: any) => ({
        key: access.id,
        value: `${getFaPermissions(access.page)} - ${access?.description} (${
          access?.name
        }) `,
      }));
      setData(d);
    }
  }, [accessData]);

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        user: item?.user?.id,
        permissions: data.selectedAccessId,
      });
      showToast("عملیات با موفقیت انجام شد", "success");
      closeModal();
      getData();
      getProfile();
    } catch (error: any) {
      if (error.status === 400) {
        showToast("مشکلی پیش آمده است!", "error");
      }
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Grid container column className="gap-2 overflow-hidden">
        <Controller
          name="selectedAccessId"
          control={control}
          render={({ field }) => (
            <AutoComplete
              multiselect
              data={data}
              selectedKeys={selectedKeys}
              onChange={(newSelectedKeys) => {
                handleChangeComplete(newSelectedKeys);
                field.onChange(newSelectedKeys);
              }}
              title="انتخاب دسترسی"
              error={!!errors.selectedAccessId}
              helperText={errors.selectedAccessId?.message}
            />
          )}
        />

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