import { z } from "zod";
import { zValidateAutoComplete } from "../../data/getFormTypeErrors";
import { useToast } from "../../hooks/useToast";
import { useModalStore } from "../../context/zustand-store/appStore";
import { zodResolver } from "@hookform/resolvers/zod";
import { Controller, useForm } from "react-hook-form";
import { useApiMutation } from "../../utils/useApiRequest";
import { getToastResponse } from "../../data/getToastResponse";
import { Grid } from "../../components/Grid/Grid";
import Button from "../../components/Button/Button";
import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete";

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

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

  const schema = z.object({
    organization: zValidateAutoComplete("تعاونی"),
  });

  type FormValues = z.infer<typeof schema>;

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

  const mutation = useApiMutation({
    api: `herd/web/api/v1/rancher_org_link/`,
    method: "post",
  });

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        rancher: item?.id,
        organization: data?.organization?.[0],
      });
      showToast(getToastResponse(null, "تخصیص با موفقیت انجام شد"), "success");
      getData();
      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 justify-center">
        <Controller
          name="organization"
          control={control}
          render={() => (
            <FormApiBasedAutoComplete
              title="انتخاب تعاونی"
              api={`herd/web/api/v1/rancher_org_link/org_linked_rancher_list/`}
              keyField="id"
              valueField="name"
              error={!!errors.organization}
              errorMessage={errors.organization?.message}
              onChange={(r) => {
                setValue("organization", [r]);
              }}
            />
          )}
        />
        <Button type="submit">ثبت</Button>
      </Grid>
    </form>
  );
};
