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 {
  zValidateNumber,
  zValidateNumberOptional,
} from "../../data/getFormTypeErrors";
import { z } from "zod";
import { useToast } from "../../hooks/useToast";
import { useModalStore } from "../../context/zustand-store/appStore";
import { getToastResponse } from "../../data/getToastResponse";
import { useApiMutation } from "../../utils/useApiRequest";
import AutoComplete from "../../components/AutoComplete/AutoComplete";
import Divider from "../../components/Divider/Divider";
import { useUserProfileStore } from "../../context/zustand-store/userStore";

const schema = z.object({
  country_code: zValidateNumber("شناسه کشوری"),
  static_code: zValidateNumberOptional("کد ثابت"),
  species_code: zValidateNumber("کد گونه"),
  serial_start: zValidateNumber("بازه سریال پلاک از"),
  serial_end: zValidateNumber("بازه سریال پلاک تا"),
});

type FormValues = z.infer<typeof schema>;

const speciesOptions = [
  { key: 1, value: "گاو" },
  { key: 2, value: "گاومیش" },
  { key: 3, value: "شتر" },
  { key: 4, value: "گوسفند" },
  { key: 5, value: "بز" },
];

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

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

  const { profile } = useUserProfileStore();

  const {
    control,
    handleSubmit,
    setValue,
    trigger,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      country_code: 364,
      static_code: 0,
      serial_start: item?.serial_from || "",
      serial_end: item?.serial_to || "",
      species_code: item?.species_code || 1,
    },
  });

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

  const onSubmit = async (data: FormValues) => {
    if (data.serial_start >= data.serial_end) {
      showToast("بازه سریال پلاک را به درستی وارد کنید!", "error");
    } else {
      try {
        const payload = {
          country_code: data.country_code,
          static_code: data.static_code,
          species_code: data.species_code,
          serial_range: [data.serial_start, data.serial_end],
        };
        await mutation.mutateAsync(payload);
        showToast(getToastResponse(null, "پلاک"), "success");
        getData();
        closeModal();
      } catch (error: any) {
        showToast(
          error?.response?.data?.message || "خطا در ثبت اطلاعات!",
          "error"
        );
      }
    }
  };

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

        <Controller
          name="static_code"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="کد ثابت"
              disabled
              value={field.value}
              onChange={field.onChange}
              error={!!errors.static_code}
              helperText={errors.static_code?.message}
            />
          )}
        />

        <Textfield
          fullWidth
          placeholder="کد مالکیت ثبتی"
          disabled
          value={profile?.organization?.ownership_code || 0}
          error={!!errors.static_code}
          helperText={errors.static_code?.message}
        />

        <Controller
          name="species_code"
          control={control}
          render={({ field }) => (
            <AutoComplete
              data={speciesOptions}
              selectedKeys={field.value ? [field.value] : []}
              onChange={(keys: (string | number)[]) => {
                setValue("species_code", keys[0] as number);
                trigger("species_code");
              }}
              error={!!errors.species_code}
              helperText={errors.species_code?.message}
              title="کد گونه"
            />
          )}
        />

        <Divider>بازه سریال پلاک</Divider>

        <Grid container className="gap-2">
          <Controller
            name="serial_start"
            control={control}
            render={({ field }) => (
              <Textfield
                fullWidth
                placeholder="از"
                value={field.value}
                onChange={field.onChange}
                error={!!errors.serial_start}
                helperText={errors.serial_start?.message}
              />
            )}
          />

          <Controller
            name="serial_end"
            control={control}
            render={({ field }) => (
              <Textfield
                fullWidth
                placeholder="تا"
                value={field.value}
                onChange={field.onChange}
                error={!!errors.serial_end}
                helperText={errors.serial_end?.message}
              />
            )}
          />
        </Grid>

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