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,
  zValidateEnglishString,
} 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";

const schema = z.object({
  code: zValidateString("کد حوزه"),
  name: zValidateEnglishString("نام انگلیسی حوزه"),
  fa_name: zValidateString("نام حوزه"),
});

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

type FormValues = z.infer<typeof schema>;

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

  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      code: item?.code || "",
      name: item?.name || "",
      fa_name: item?.fa_name || "",
    },
  });

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

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        code: data.code,
        name: data.name,
        fa_name: data.fa_name,
      });
      showToast(getToastResponse(item, "حوزه"), "success");
      closeModal();
      getData();
    } catch (error: any) {
      if (error?.status === 403) {
        showToast(
          error?.response?.data?.message || "این مورد تکراری است!",
          "error",
        );
      } else {
        showToast(
          error?.response?.data?.message || "خطا در ثبت اطلاعات!",
          "error",
        );
      }
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Grid container column className="gap-2">
        <Controller
          name="code"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="کد حوزه"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.code}
              helperText={errors.code?.message}
            />
          )}
        />
        <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="fa_name"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="نام حوزه"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.fa_name}
              helperText={errors.fa_name?.message}
            />
          )}
        />
        <Button type="submit">ثبت</Button>
      </Grid>
    </form>
  );
};
