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 {
  zValidateNumber,
  zValidateNumberOptional,
  zValidateString,
} from "../../data/getFormTypeErrors";
import { z } from "zod";
import { useApiMutation } from "../../utils/useApiRequest";
import { useToast } from "../../hooks/useToast";
import { useDrawerStore } from "../../context/zustand-store/appStore";
import { getToastResponse } from "../../data/getToastResponse";
import { RadioGroup } from "../../components/RadioButton/RadioGroup";
import { useState } from "react";
import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete";
import DatePicker from "../../components/date-picker/DatePicker";

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

const genderTypes = [
  { label: "نر", value: 1 },
  { label: "ماده", value: 2 },
];

const weightTypes = [
  { label: "سبک", value: "L" },
  { label: "سنگین", value: "H" },
];

export const LiveStockAddLiveStock = ({
  getData,
  item,
  herdId,
}: AddPageProps) => {
  const schema = z.object({
    type: zValidateNumber("نوع دام "),
    species: zValidateNumberOptional("گونه"),
    use_type: zValidateNumberOptional("نوع دام "),
    birthdate: zValidateString("تاریخ تولد"),
  });

  type FormValues = z.infer<typeof schema>;

  const showToast = useToast();
  const { closeDrawer } = useDrawerStore();
  const [gender, setGender] = useState(item?.gender || 1);
  const [weightType, setWeightType] = useState(
    item?.weight_type === "H" ? "H" : "L"
  );

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

  const mutation = useApiMutation({
    api: `/livestock/web/api/v1/livestock/${item ? item?.id + "/" : ""}`,
    method: item ? "put" : "post",
  });
  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        herd: herdId,
        type: data?.type,
        ...(data.use_type && {
          use_type: data.use_type,
        }),
        ...(data.species && {
          species: data.species,
        }),
        birthdate: data?.birthdate,
        weight_type: weightType,
        gender: gender,
      });
      showToast(getToastResponse(item, ""), "success");
      getData();
      closeDrawer();
    } 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="type"
          control={control}
          render={() => (
            <FormApiBasedAutoComplete
              defaultKey={item?.type?.id}
              title="نوع دام"
              api={`livestock/web/api/v1/livestock_type`}
              keyField="id"
              valueField="name"
              error={!!errors.type}
              errorMessage={errors.type?.message}
              onChange={(r) => {
                setValue("type", r);
              }}
            />
          )}
        />

        <RadioGroup
          groupTitle="جنسیت"
          direction="row"
          options={genderTypes}
          name="جنسیت"
          value={gender}
          onChange={(e) => {
            setGender(parseInt(e.target.value));
          }}
        />

        <Controller
          name="species"
          control={control}
          render={() => (
            <FormApiBasedAutoComplete
              defaultKey={item?.species?.id}
              title="گونه (اختیاری)"
              api={`livestock/web/api/v1/livestock_species`}
              keyField="id"
              valueField="name"
              error={!!errors.species}
              errorMessage={errors.species?.message}
              onChange={(r) => {
                setValue("species", r);
              }}
            />
          )}
        />

        <Controller
          name="use_type"
          control={control}
          render={() => (
            <FormApiBasedAutoComplete
              defaultKey={item?.use_type?.id}
              title="نوع دام (اختیاری)"
              api={`livestock/web/api/v1/livestock_use_type`}
              keyField="id"
              valueField="name"
              error={!!errors.use_type}
              errorMessage={errors.use_type?.message}
              onChange={(r) => {
                setValue("use_type", r);
              }}
            />
          )}
        />

        <DatePicker
          value={item?.birthdate || ""}
          minYear={1300}
          label="تاریخ تولد"
          size="medium"
          onChange={(r) => {
            setValue("birthdate", r);
          }}
        />

        <RadioGroup
          groupTitle="نوع وزن"
          direction="row"
          options={weightTypes}
          name="نوع وزن"
          value={weightType}
          onChange={(e) => {
            setWeightType(e.target.value);
          }}
        />
        <Button type="submit">ثبت</Button>
      </Grid>
    </form>
  );
};
