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 {
  zValidateAutoComplete,
  zValidateNumber,
  zValidateNumberOptional,
  zValidateString,
  zValidateStringOptional,
} 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 { getToastResponse } from "../../data/getToastResponse";
import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete";
import { useFetchProfile } from "../../hooks/useFetchProfile";
import { getFaPermissions } from "../../utils/getFaPermissions";

const schema = z.object({
  name: zValidateString("نام سازمان"),
  description: zValidateStringOptional("توضیحات"),
  type: zValidateNumber("نوع نقش"),
  permissions: zValidateAutoComplete("دسترسی"),
  parent_role: zValidateNumberOptional("نقش والد"),
});

type AddPageProps = {
  getData: () => void;
  item?: any;
};

type FormValues = z.infer<typeof schema>;

export const AddRole = ({ getData, item }: AddPageProps) => {
  const showToast = useToast();
  const { closeModal } = useModalStore();
  const { getProfile } = useFetchProfile();

  const {
    control,
    handleSubmit,
    setValue,
    trigger,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      name: item?.role_name || "",
      description: item?.description || "",
      parent_role: item?.parent_role?.id || "",
      permissions: item?.permissions || [],
    },
  });

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

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        role_name: data.name,
        description: data.description,
        type: data.type,
        permissions: data.permissions,
        ...(data.parent_role ? { parent_role: data.parent_role } : {}),
      });
      showToast(getToastResponse(item, "نقش"), "success");
      getData();
      getProfile();
      closeModal();
    } catch (error: any) {
      if (error?.status === 403) {
        showToast("این نقش تکراری است!", "error");
      } else {
        showToast(
          error?.response?.data?.message || "خطا در ثبت اطلاعات!",
          "error"
        );
      }
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Grid container column className="gap-2">
        <Controller
          name="name"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="نام نقش"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.name}
              helperText={errors.name?.message}
            />
          )}
        />

        <Controller
          name="parent_role"
          control={control}
          render={() => (
            <FormApiBasedAutoComplete
              defaultKey={item?.parent_role?.id}
              title="نقش والد (اختیاری)"
              api={"auth/api/v1/role/"}
              keyField="id"
              valueField="role_name"
              onChange={(r) => {
                setValue("parent_role", r);
                trigger(["parent_role"]);
              }}
              error={!!errors.parent_role}
              errorMessage={errors.parent_role?.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="type"
          control={control}
          render={() => (
            <FormApiBasedAutoComplete
              defaultKey={item?.type?.id || null}
              title="نوع نقش"
              api={"auth/api/v1/organization-type/"}
              keyField="id"
              valueField="name"
              onChange={(r) => {
                setValue("type", r);
                trigger(["type"]);
              }}
              error={!!errors.type}
              errorMessage={errors.type?.message}
            />
          )}
        />

        <Controller
          name="type"
          control={control}
          render={() => (
            <FormApiBasedAutoComplete
              multiple
              groupBy="page"
              groupFunction={(item) => getFaPermissions(item)}
              defaultKey={item?.permissions}
              title="دسترسی ها"
              api={"auth/api/v1/permission/"}
              keyField="id"
              valueField="page"
              valueField2="description"
              valueField3="name"
              onChange={(r) => {
                setValue("permissions", r);
                trigger(["permissions"]);
              }}
              error={!!errors.permissions}
              errorMessage={errors.permissions?.message}
            />
          )}
        />

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