import { Grid } from "../../components/Grid/Grid";
import { Stepper } from "../../components/Stepper/Stepper";
import { useEffect, useState } from "react";
import { QuotaLevel1 } from "./QuotaLevel1";
import Button from "../../components/Button/Button";
import { QuotaLevel2 } from "./QuotaLevel2";
import { QuotaLevel3 } from "./QuotaLevel3";
import { QuotaLevel4 } from "./QuotaLevel4";
import { useApiMutation } from "../../utils/useApiRequest";
import { useToast, useConfirmToast } from "../../hooks/useToast";
import { getToastResponse } from "../../data/getToastResponse";
import { useModalStore } from "../../context/zustand-store/appStore";

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

export const AddQuota = ({ item, getData }: Props) => {
  const [currentStep, setCurrentStep] = useState(1);
  const [formData, setFormData] = useState<any>({});
  const [formRef, setFormRef] = useState<HTMLFormElement | null>(null);
  const showToast = useToast();
  const showConfirmToast = useConfirmToast();
  const { closeModal } = useModalStore();

  const steps = [
    { key: 1, label: "محصول" },
    { key: 2, label: "طرح ها" },
    { key: 3, label: "محدودیت ها" },
    { key: 4, label: "قیمت گذاری" },
  ];

  const handleNext = () => {
    if (formRef) {
      const submitEvent = new Event("submit", {
        bubbles: true,
        cancelable: true,
      });
      formRef.dispatchEvent(submitEvent);
    }
  };

  const handleBack = () => {
    setCurrentStep((prevStep) => Math.max(prevStep - 1, 1));
  };

  const handleFormSubmit = (data: any) => {
    if (data) {
      setFormData({
        ...formData,
        ...data,
        sendApi: currentStep === 4,
      });
    }
    setCurrentStep((prevStep) => Math.min(prevStep + 1, steps.length));
  };

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

  useEffect(() => {
    if (formData?.sendApi) {
      handleSubmitForm();
    }
  }, [formData]);

  const handleSubmitForm = async () => {
    if (item && item?.quota_distributed > 0) {
      const confirmed = await showConfirmToast(
        "اطلاعات ویرایش شده بر روی تمام توزیع های زیر مجموعه اعمال میشود!",
      );
      if (!confirmed) {
        return;
      }
    }

    const submitData = {
      quota_weight: formData?.quota_weight,
      sale_unit: formData?.sale_unit,
      has_organization_limit: formData?.has_organization_limit,
      limit_by_organizations: formData?.limit_by_organizations,
      product: formData?.product,
      sale_type: formData?.sale_type,
      month_choices: formData?.month_choices,
      sale_license: formData?.sale_license,
      group: formData?.group,
      has_distribution_limit: formData?.hasDistributionLimit,
      limit_by_herd_size: formData?.limit_by_herd_size,
      distribution_mode: formData?.distribution_mode,
      price_calculation_items: formData?.price_calculation_items,
      incentive_plan_data: formData?.active_plans,
      price_attributes_data: formData?.price_attributes_data,
      broker_data: formData?.broker_data,
      pos_sale_type: formData?.pos_sale_type,
      livestock_allocation_data: formData?.livestockTypes?.filter(
        (opt: { quantity_kg: number }) => opt?.quantity_kg > 0,
      ),
      livestock_age_limitations: formData?.livestock_age_limitations,
      pre_sale: formData?.pre_sale,
      free_sale: formData?.free_sale,
      one_time_purchase_limit: formData?.one_time_purchase_limit,
    };

    let filterEmptyKeys = Object.fromEntries(
      Object.entries(submitData).filter(([, v]) => v != null),
    );

    try {
      await mutation.mutateAsync(filterEmptyKeys);
      showToast(getToastResponse(item, "سهمیه"), "success");
      getData();
      closeModal();
    } catch (error: any) {
      if (error?.response?.data?.message) {
        showToast(error?.response?.data?.message, "error");
      } else {
        showToast("خطا در ثبت اطلاعات!", "error");
      }
    }
  };

  return (
    <Grid column container className="gap-4">
      <Grid container column className="min-h-150">
        <Stepper steps={steps} activeStep={currentStep} />
        <div className={currentStep === 1 ? "block" : "hidden"}>
          <QuotaLevel1
            item={item}
            getData={getData}
            onSubmit={handleFormSubmit}
            setFormRef={setFormRef}
            visible={currentStep === 1}
          />
        </div>
        <div className={currentStep === 2 ? "block" : "hidden"}>
          <QuotaLevel2
            item={item}
            getData={getData}
            onSubmit={handleFormSubmit}
            setFormRef={setFormRef}
            visible={currentStep === 2}
          />
        </div>
        <div className={currentStep === 3 ? "block" : "hidden"}>
          <QuotaLevel3
            item={item}
            getData={getData}
            onSubmit={handleFormSubmit}
            setFormRef={setFormRef}
            visible={currentStep === 3}
          />
        </div>
        <div className={currentStep === 4 ? "block" : "hidden"}>
          <QuotaLevel4
            item={item}
            getData={getData}
            onSubmit={handleFormSubmit}
            setFormRef={setFormRef}
            formData={formData}
            visible={currentStep === 4}
          />
        </div>{" "}
      </Grid>

      <Grid container className="justify-center  bottom-0 flex">
        <Grid container className="w-80 gap-2">
          <Button
            size="medium"
            fullWidth
            className="bg-transparent  border-1 border-primary-600 text-primary-700 dark:border-primary-700 font-semibold"
            onClick={handleBack}
            disabled={currentStep === 1}
          >
            قبلی
          </Button>

          <Button size="medium" fullWidth onClick={handleNext}>
            {currentStep < steps.length ? "بعدی" : "ثبت"}
          </Button>
        </Grid>
      </Grid>
    </Grid>
  );
};
