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 {
  zValidateAutoComplete,
  zValidateMobile,
  zValidateNationalCode,
  zValidateNumber,
  zValidateString,
  zValidateStringOptional,
} 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 { FormEnterLocations } from "../../components/FormItems/FormEnterLocation";
import { RadioGroup } from "../../components/RadioButton/RadioGroup";
import { useState } from "react";
import AutoComplete from "../../components/AutoComplete/AutoComplete";

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

export const LiveStockAddRancher = ({ getData, item }: AddPageProps) => {
  const activityTypes = [
    { label: "روستایی", value: "V" },
    { label: "صنعتی", value: "I" },
    { label: "عشایری", value: "N" },
  ];

  const rancherHerdTypes = [
    { label: "عادی", value: false },
    { label: "بدون دام", value: true },
  ];

  const rancherTypes = [
    { key: "N", value: "حقیقی", disabled: false },
    { key: "L", value: "حقوقی", disabled: false },
  ];

  const schema = z
    .object({
      ranching_farm: zValidateString("نام صفحه"),
      first_name: zValidateString("نام"),
      last_name: zValidateString("نام خانوادگی"),
      mobile: zValidateMobile("موبایل"),
      national_code: zValidateNationalCode("کد ملی"),
      address: zValidateString("آدرس"),
      province: zValidateNumber("استان"),
      city: zValidateNumber("شهر"),
      rancher_type: zValidateAutoComplete("مالکیت"),
      union_name: zValidateStringOptional("نام واحد حقوقی"),
      union_code: zValidateStringOptional("شناسه ملی واحد حقوقی"),
    })
    .refine(
      (data) => {
        if (data.rancher_type?.[0] === "L") {
          return !!data.union_name;
        }
        return true;
      },
      {
        message: "نام واحد حقوقی نمیتواند خالی باشد",
        path: ["union_name"],
      }
    )
    .refine(
      (data) => {
        if (data.rancher_type?.[0] === "L") {
          return !!data.union_code;
        }
        return true;
      },
      {
        message: "شناسه ملی واحد حقوقی نمیتواند خالی باشد",
        path: ["union_code"],
      }
    );

  type FormValues = z.infer<typeof schema>;

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

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

  const [rancherHerdType, setRancherHerdType] = useState(
    item ? item?.without_herd : false
  );

  const {
    control,
    handleSubmit,
    setValue,
    trigger,
    getValues,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      ranching_farm: item?.ranching_farm || "",
      first_name: item?.first_name || "",
      last_name: item?.last_name || "",
      mobile: item?.mobile || "",
      national_code: item?.national_code || "",
      address: item?.address || "",
      province: item?.user?.province || "",
      city: item?.user?.city || "",
      rancher_type: item ? [item?.rancher_type] : [],
      union_name: item?.union_name || "",
      union_code: item?.union_code || "",
    },
  });

  const mutation = useApiMutation({
    api: `/herd/web/api/v1/rancher/${item ? item?.id + "/" : ""}`,
    method: item ? "put" : "post",
  });
  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        ranching_farm: data?.ranching_farm,
        first_name: data?.first_name,
        last_name: data?.last_name,
        mobile: data?.mobile,
        national_code: data?.national_code,
        address: data?.address,
        province: data?.province,
        city: data?.city,
        without_herd: rancherHerdType,
        activity: activityType,
        rancher_type: data?.rancher_type?.[0],
        ...(data.rancher_type?.[0] === "L"
          ? { union_name: data.union_name }
          : { union_name: "" }),
        ...(data.rancher_type?.[0] === "L"
          ? { union_code: data.union_code }
          : { union_code: "" }),
      });
      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="rancher_type"
          control={control}
          render={({ field }) => (
            <AutoComplete
              data={rancherTypes}
              selectedKeys={field.value}
              onChange={(keys: (string | number)[]) => {
                setValue("rancher_type", keys);
                trigger(["rancher_type", "union_name", "union_code"]);
              }}
              error={!!errors.rancher_type}
              helperText={errors.rancher_type?.message}
              title="نوع دامدار"
            />
          )}
        />

        {!!getValues("rancher_type")?.length && (
          <Grid container column className="gap-2">
            <Controller
              name="ranching_farm"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="نام دامداری"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.ranching_farm}
                  helperText={errors.ranching_farm?.message}
                />
              )}
            />
            <Controller
              name="first_name"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="نام"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.first_name}
                  helperText={errors.first_name?.message}
                />
              )}
            />

            <Controller
              name="last_name"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="نام خانوادگی"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.last_name}
                  helperText={errors.last_name?.message}
                />
              )}
            />
            <Controller
              name="national_code"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="کد ملی"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.national_code}
                  helperText={errors.national_code?.message}
                />
              )}
            />

            <Controller
              name="mobile"
              control={control}
              render={({ field }) => (
                <Textfield
                  isNumber
                  fullWidth
                  placeholder="موبایل"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.mobile}
                  helperText={errors.mobile?.message}
                />
              )}
            />

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

            <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="address"
              control={control}
              render={({ field }) => (
                <Textfield
                  fullWidth
                  placeholder="آدرس"
                  value={field.value}
                  onChange={field.onChange}
                  error={!!errors.address}
                  helperText={errors.address?.message}
                />
              )}
            />

            <RadioGroup
              groupTitle="وضعیت دامدار"
              direction="row"
              options={rancherHerdTypes}
              name="وضعیت"
              value={rancherHerdType}
              onChange={(e) =>
                e.target.value === "true"
                  ? setRancherHerdType(true)
                  : setRancherHerdType(false)
              }
            />

            {getValues("rancher_type")?.[0] === "L" && (
              <>
                <Controller
                  name="union_name"
                  control={control}
                  render={({ field }) => (
                    <Textfield
                      fullWidth
                      placeholder="نام واحد حقوقی"
                      value={field.value}
                      onChange={field.onChange}
                      error={!!errors.union_name}
                      helperText={errors.union_name?.message}
                    />
                  )}
                />

                <Controller
                  name="union_code"
                  control={control}
                  render={({ field }) => (
                    <Textfield
                      fullWidth
                      placeholder="شناسه ملی واحد حقوقی"
                      isNumber
                      value={field.value}
                      onChange={field.onChange}
                      error={!!errors.union_code}
                      helperText={errors.union_code?.message}
                    />
                  )}
                />
              </>
            )}

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