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,
  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 { FormEnterLocations } from "../../components/FormItems/FormEnterLocation";
import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete";
import { useUserProfileStore } from "../../context/zustand-store/userStore";

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

const activityTypes = [
  { label: "روستایی", value: "V" },
  { label: "صنعتی", value: "I" },
  { label: "عشایری", value: "N" },
];

const activityStateTypes = [
  { label: "فعال", value: true },
  { label: "غیر فعال", value: false },
];

const operatingLicenseStateTypes = [
  { label: "دارای مجوز", value: true },
  { label: "بدون مجوز", value: false },
];

export const LiveStockAddHerd = ({ getData, item, rancher }: AddPageProps) => {
  const { profile } = useUserProfileStore();

  const schema = z.object({
    name: zValidateString("نام گله"),
    unit_unique_id: zValidateNumber("شناسه یکتا"),
    capacity: zValidateNumberOptional("ظرفیت"),
    code: zValidateNumber("کد گله"),
    heavy_livestock_number: zValidateNumberOptional("حجم دام سنگین"),
    light_livestock_number: zValidateNumberOptional("حجم دام سبک"),
    postal: zValidateNumberOptional("کد پستی"),
    institution: zValidateNumberOptional("کد موسسه"),
    epidemiologic: zValidateNumberOptional("کد اپیدمیولوژیک"),
    province: zValidateNumber("استان"),
    city: zValidateNumber("شهر"),
    cooperative:
      profile?.role?.type?.key === "J"
        ? zValidateNumber("تعاونی")
        : zValidateNumberOptional("تعاونی"),
    contractor: zValidateNumberOptional("شرکت پیمانکار"),
  });

  type FormValues = z.infer<typeof schema>;

  const showToast = useToast();
  const { closeDrawer } = useDrawerStore();

  const [activityType, setActivityType] = useState(item?.activity || "V");

  const [activityState, setActivityState] = useState(
    item ? item?.activity_state : true
  );
  const [operatingLicenseState, setOperatingLicenseState] = useState(
    item ? item?.operating_license_state : true
  );

  const {
    control,
    handleSubmit,
    setValue,
    trigger,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      name: item?.name || "",
      capacity: item?.capacity || "",
      code: item?.code || "",
      unit_unique_id: item?.unit_unique_id || "",
      heavy_livestock_number: item?.heavy_livestock_number || "",
      light_livestock_number: item?.light_livestock_number || "",
      postal: item?.postal || "",
      institution: item?.institution || "",
      epidemiologic: item?.epidemiologic || "",
      province: item?.user?.province || "",
      city: item?.user?.city || "",
    },
  });

  const mutation = useApiMutation({
    api: `/herd/web/api/v1/herd/${item ? item?.id + "/" : ""}`,
    method: item ? "put" : "post",
  });
  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        name: data?.name,
        capacity: data?.capacity,
        code: data?.code,
        unit_unique_id: data?.unit_unique_id,
        heavy_livestock_number: data?.heavy_livestock_number,
        light_livestock_number: data?.light_livestock_number,
        postal: data?.postal ?? "",
        institution: data?.institution ?? "",
        epidemiologic: data?.epidemiologic ?? "",
        province: data?.province,
        city: data?.city,

        rancher: parseInt(rancher) ?? parseInt(rancher),
        operating_license_state: operatingLicenseState,
        activity: activityType,
        activity_state: activityState,
        ...(data.contractor !== undefined && {
          contractor: data.contractor,
        }),
        ...(data.cooperative !== undefined && {
          cooperative: data.cooperative,
        }),
      });
      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="name"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="نام گله"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.name}
              helperText={errors.name?.message}
            />
          )}
        />
        <Controller
          name="unit_unique_id"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="شناسه یکتا"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.unit_unique_id}
              helperText={errors.unit_unique_id?.message}
            />
          )}
        />

        {profile?.role?.type?.key === "J" && (
          <Controller
            name="cooperative"
            control={control}
            render={() => (
              <FormApiBasedAutoComplete
                defaultKey={item?.cooperative?.id}
                title="تعاونی "
                api={`auth/api/v1/organization/child_organizations?search=تعاونی`}
                keyField="id"
                valueField="name"
                error={!!errors.cooperative}
                errorMessage={errors.cooperative?.message}
                onChange={(r) => {
                  setValue("cooperative", r);
                }}
              />
            )}
          />
        )}

        <Controller
          name="contractor"
          control={control}
          render={() => (
            <FormApiBasedAutoComplete
              defaultKey={item?.contractor?.id}
              title="شرکت پیمانکار (اختیاری)"
              api={`auth/api/v1/organization/child_organizations?search=شرکت`}
              keyField="id"
              valueField="name"
              error={!!errors.contractor}
              errorMessage={errors.contractor?.message}
              onChange={(r) => {
                setValue("contractor", r);
              }}
            />
          )}
        />

        <Controller
          name="province"
          control={control}
          render={() => (
            <FormEnterLocations
              cityValue={item?.city?.id}
              provinceValue={item?.province?.id}
              cityError={!!errors.city}
              provincError={!!errors.province}
              cityErrorMessage={errors.city?.message}
              provinceErrMessage={errors.province?.message}
              roleControlled
              onChange={async (locations) => {
                setValue("province", locations.province);
                setValue("city", locations.city);
                if (locations.province || locations.city)
                  await trigger(["province", "city"]);
              }}
            />
          )}
        />

        <Controller
          name="capacity"
          control={control}
          render={({ field }) => (
            <Textfield
              formattedNumber
              fullWidth
              placeholder="ظرفیت"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.capacity}
              helperText={errors.capacity?.message}
            />
          )}
        />

        <Controller
          name="code"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="کد گله"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.code}
              helperText={errors.code?.message}
            />
          )}
        />

        <RadioGroup
          groupTitle="نوع فعالیت"
          direction="column"
          options={activityTypes}
          name="نوع فعالیت"
          value={activityType}
          onChange={(e) => setActivityType(e.target.value)}
        />

        <Controller
          name="heavy_livestock_number"
          control={control}
          render={({ field }) => (
            <Textfield
              formattedNumber
              fullWidth
              placeholder="حجم دام سنگین"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.heavy_livestock_number}
              helperText={errors.heavy_livestock_number?.message}
            />
          )}
        />
        <Controller
          name="light_livestock_number"
          control={control}
          render={({ field }) => (
            <Textfield
              formattedNumber
              fullWidth
              placeholder="حجم دام سبک"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.light_livestock_number}
              helperText={errors.light_livestock_number?.message}
            />
          )}
        />
        <Controller
          name="postal"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="کد پستی"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.postal}
              helperText={errors.postal?.message}
            />
          )}
        />
        <Controller
          name="institution"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="کد موسسه"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.institution}
              helperText={errors.institution?.message}
            />
          )}
        />
        <Controller
          name="epidemiologic"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="کد اپیدمیولوژیک"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.epidemiologic}
              helperText={errors.epidemiologic?.message}
            />
          )}
        />

        <RadioGroup
          groupTitle="وضعیت فعالیت"
          direction="row"
          options={activityStateTypes}
          name="وضعیت فعالیت"
          value={activityState}
          onChange={(e) =>
            e.target.value === "true"
              ? setActivityState(true)
              : setActivityState(false)
          }
        />

        <RadioGroup
          groupTitle="وضعیت مجوز"
          direction="row"
          options={operatingLicenseStateTypes}
          name="وضعیت مجوز"
          value={operatingLicenseState}
          onChange={(e) =>
            e.target.value === "true"
              ? setOperatingLicenseState(true)
              : setOperatingLicenseState(false)
          }
        />

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