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,
  zValidateStringOptional,
} from "../../../data/getFormTypeErrors";
import { z } from "zod";
import { useApiMutation } from "../../../utils/useApiRequest";
import { useToast } from "../../../hooks/useToast";
import { useModalStore } from "../../../context/zustand-store/appStore";
import { getToastResponse } from "../../../data/getToastResponse";
import { FormApiBasedAutoComplete } from "../../../components/FormItems/FormApiBasedAutoComplete";
import Typography from "../../../components/Typography/Typography";

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

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

  const cooperativeValue = isSubmit
    ? item?.quota?.brokers?.find(
        (broker: any) => broker?.broker_name === "تعاونی",
      )?.value
    : item?.quota_distribution?.quota?.brokers?.find(
        (broker: any) => broker?.broker_name === "تعاونی",
      )?.value;

  const schema = z.object({
    share_amount: zValidateNumber("سهم از تعرفه").max(
      cooperativeValue,
      `سهم از تعرفه نمی‌تواند بیشتر از ${cooperativeValue?.toLocaleString()} باشد!`,
    ),
    organization: zValidateNumber("سازمان"),
    assigned_organization: zValidateNumber("سازمان تخصیص دهنده"),
    weight: zValidateNumber("وزن"),
    description: zValidateStringOptional("(اختیاری) توضیحات"),
  });

  type FormValues = z.infer<typeof schema>;

  const {
    control,
    handleSubmit,
    setValue,
    trigger,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      share_amount: isSubmit ? "" : item?.share_amount || "",
      description: isSubmit ? "" : item?.quota_distribution?.description || "",
      weight: isSubmit ? "" : item?.quota_distribution?.weight || "",
    },
  });

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

  const onSubmit = async (data: FormValues) => {
    try {
      const payload = {
        distribution: {
          description: data.description || "",
          quota: isSubmit ? item?.id : item.quota_distribution?.quota?.id,
          weight: data.weight || 0,
          assigned_organization: data.assigned_organization,
        },
        stakeholders: data.organization,
        share_amount: data.share_amount || 0,
      };

      await mutation.mutateAsync(payload as any);
      showToast(
        getToastResponse(isSubmit ? false : true, "تخصیص به زیر مجموعه"),
        "success",
      );
      getData();
      closeModal();
    } catch (error: any) {
      if (error?.status === 400) {
        showToast(
          error?.response?.data?.detail || error?.response?.data?.message,
          "error",
        );
        closeModal();
      } else 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">
        <Grid container column className="justify-center w-full">
          <Typography
            variant="caption"
            sign="info"
            color="text-purple-400 dark:text-purple-200"
          >
            سهم تعاونی از فروش: {cooperativeValue?.toLocaleString()} ریال
          </Typography>
          <Typography
            variant="caption"
            sign="info"
            color="text-purple-400 dark:text-purple-200"
          >
            حداکثر وزن قابل تخصیص:{" "}
            {isSubmit
              ? item?.remaining_weight?.toLocaleString()
              : (
                  item?.quota_distribution?.weight +
                  item?.quota_distribution?.parent_distribution_remaining_weight
                )?.toLocaleString()}{" "}
            کیلوگرم
          </Typography>
        </Grid>
        <Controller
          name="organization"
          control={control}
          render={() => (
            <>
              <FormApiBasedAutoComplete
                defaultKey={item?.stakeholders?.id}
                title="انتخاب زیر مجموعه"
                api={`pos_device/web/v1/pos/stake_holders/list_by_organization`}
                keyField="id"
                valueTemplate="v1 (از دستگاه : v2)"
                valueTemplateProps={[{ v1: "string" }, { v2: "string" }]}
                secondaryKey={["organization", "id"]}
                valueField={["organization", "name"]}
                valueField2={["device"]}
                error={!!errors.organization}
                errorMessage={errors.organization?.message}
                onChange={(r) => {
                  setValue("organization", r.key1);
                  setValue("assigned_organization", r.key2);
                  trigger("organization");
                }}
              />
            </>
          )}
        />

        <Controller
          name="weight"
          control={control}
          render={({ field }) => (
            <Textfield
              formattedNumber
              fullWidth
              placeholder="وزن"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.weight}
              helperText={errors.weight?.message}
            />
          )}
        />

        <Controller
          name="share_amount"
          control={control}
          render={({ field }) => (
            <Textfield
              formattedNumber
              fullWidth
              placeholder="سهم از تعرفه"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.share_amount}
              helperText={errors.share_amount?.message}
            />
          )}
        />

        <Controller
          name="description"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="توضیحات"
              value={field.value as any}
              onChange={field.onChange}
              error={!!errors.description}
              helperText={errors.description?.message}
            />
          )}
        />

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