import { useEffect, useRef, useState } from "react";
import { useApiRequest } from "../../utils/useApiRequest";
import { Grid } from "../../components/Grid/Grid";
import Checkbox from "../../components/CheckBox/CheckBox";
import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete";
import Textfield from "../../components/Textfeild/Textfeild";
import Typography from "../../components/Typography/Typography";

type Props = {
  item: any;
  getData: () => void;
  onSubmit: (data: any) => void;
  setFormRef: (ref: HTMLFormElement | null) => void;
  visible: boolean;
};

interface LimitationDataProps {
  has_organization_limit: boolean;
  has_age_limitations: boolean;
  limit_by_organizations: number[] | string[];
}

export const QuotaLevel3 = ({ item, onSubmit, setFormRef, visible }: Props) => {
  const internalRef = useRef<HTMLFormElement>(null);

  const [limitByHerdSize, setLimitByHerdSize] = useState(
    item?.limit_by_herd_size || false,
  );

  const [preSale, setPreSale] = useState(item?.pre_sale || false);

  const [freeSale, setFreeSale] = useState(item?.free_sale || false);

  const [oneTimePurchase, setOneTimePurchase] = useState(
    item?.one_time_purchase_limit || false,
  );

  useEffect(() => {
    if (visible) {
      setFormRef(internalRef.current);
    }
  }, [visible]);

  const [limitationData, setLimitationData] = useState<LimitationDataProps>({
    has_organization_limit: item?.has_organization_limit ? true : false,
    has_age_limitations: item?.livestock_limitations?.length ? true : false,
    limit_by_organizations: [],
  });

  const [livestockTypes, setLivestockTypes] = useState<
    | Array<{
        livestock_type: any;
        weight_type: any;
        age_month: number;
        fa: string;
      }>
    | undefined
  >();

  const { data } = useApiRequest({
    api: "/livestock/web/api/v1/livestock_type/",
    method: "get",
    params: { page: 1, page_size: 1000 },
    queryKey: ["livestock_type"],
  });

  const getData = async () => {
    const getQuatity = (allocate: any) => {
      const result = item?.livestock_limitations?.find(
        (option: any) =>
          option?.livestock_type?.weight_type === allocate?.weight_type &&
          option?.livestock_type?.id === allocate?.id &&
          option?.livestock_type?.name === allocate?.name,
      );
      if (result) {
        return result.age_month;
      } else {
        return 0;
      }
    };

    const d = data?.results?.map((item: any) => {
      return {
        livestock_type: item?.id,
        age_month: getQuatity(item),
        fa: item?.name,
        weight_type: item?.weight_type,
      };
    });

    if (d.length) {
      setLivestockTypes(d);
    }
  };

  useEffect(() => {
    getData();
  }, [data]);

  const handleSubmitForm = () => {
    const submitData = {
      limit_by_herd_size: limitByHerdSize,
      ...limitationData,
      ...(!limitationData.has_organization_limit && {
        limit_by_organizations: [],
      }),
      ...(limitationData.has_age_limitations && {
        livestock_age_limitations: livestockTypes,
      }),
      pre_sale: preSale,
      free_sale: freeSale,
      one_time_purchase_limit: oneTimePurchase,
    };

    if (
      limitationData.has_organization_limit &&
      !limitationData.limit_by_organizations.length
    ) {
      return;
    }

    onSubmit(submitData);
  };

  const handleLivestockTypeChange = (index: number, value: number) => {
    setLivestockTypes((prev) => {
      if (!prev) return prev;
      const newTypes = [...prev];
      newTypes[index] = {
        ...newTypes[index],
        age_month: value,
      };
      return newTypes;
    });
  };

  return (
    <form ref={internalRef} onSubmit={handleSubmitForm}>
      <Grid container column>
        <Grid className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 mt-8 gap-4 items-start">
          <Grid className="flex gap-2 p-2 border-1 border-gray-200 rounded-xl items-center">
            <Checkbox
              label="محدود بر اساس تعداد راس دام"
              checked={limitByHerdSize}
              onChange={() => {
                setLimitByHerdSize(!limitByHerdSize);
              }}
            />
          </Grid>
          <Grid className="flex gap-2 p-2 border-1 border-gray-200 rounded-xl items-center">
            <Checkbox
              checked={false}
              label="محدود به دام های پلاک شده"
              disabled
            />
          </Grid>
          <Grid className="flex gap-2 p-2 border-1 border-gray-200 rounded-xl items-center">
            <Checkbox
              checked={false}
              label="محدود به دام های بیمه شده"
              disabled
            />
          </Grid>

          <Grid className="grid gap-4 p-2 border-1 border-gray-200 rounded-xl items-center">
            <Checkbox
              checked={limitationData.has_organization_limit}
              label="محدودیت بر اساس شهرستان و تعاونی"
              onChange={() => {
                setLimitationData((prev: any) => ({
                  ...prev,
                  has_organization_limit: !prev.has_organization_limit,
                }));
              }}
            />

            {limitationData.has_organization_limit && (
              <FormApiBasedAutoComplete
                defaultKey={item?.limit_by_organizations}
                title="محدودیت بر اساس شهرستان و تعاونی"
                api={"auth/api/v1/organization/child_organizations/"}
                keyField="id"
                valueField="name"
                multiple
                onChange={(r) => {
                  setLimitationData((prev: any) => ({
                    ...prev,
                    limit_by_organizations: r,
                  }));
                }}
                error={
                  limitationData.has_organization_limit &&
                  !limitationData?.limit_by_organizations.length
                }
                errorMessage={
                  limitationData.has_organization_limit &&
                  !limitationData?.limit_by_organizations.length
                    ? "یک یا چند مورد را انتخاب کنید!"
                    : ""
                }
              />
            )}
          </Grid>

          <Grid className="grid gap-2 p-2 border-1 border-gray-200 rounded-xl">
            <Checkbox
              checked={limitationData.has_age_limitations}
              label="محدودیت بر اساس بازه سنی دام"
              onChange={() => {
                setLimitationData((prev: any) => ({
                  ...prev,
                  has_age_limitations: !prev.has_age_limitations,
                }));
              }}
            />
            {limitationData.has_age_limitations && (
              <>
                <Grid className="grid gap-2 p-2 border-1 border-gray-200 rounded-xl">
                  <Grid className="flex justify-start select-none items-center gap-2">
                    <Typography
                      color="text-gray-600 dark:text-dark-100"
                      variant="caption"
                    >
                      سبک
                    </Typography>
                  </Grid>
                  <Grid className="grid grid-cols-2 sm:grid-cols-1 md:grid-cols-2 gap-2 rounded-xl items-center">
                    {livestockTypes
                      ?.filter((opt) => opt?.weight_type === "L")
                      .map((item, i) => (
                        <Textfield
                          key={i}
                          start={item?.fa}
                          end="ماه"
                          formattedNumber
                          value={item?.age_month}
                          onChange={(e) => {
                            const value = parseInt(e.target.value) || 0;
                            const originalIndex = livestockTypes.findIndex(
                              (type) =>
                                type.livestock_type === item.livestock_type &&
                                type.weight_type === item.weight_type,
                            );
                            if (originalIndex !== -1) {
                              handleLivestockTypeChange(originalIndex, value);
                            }
                          }}
                        />
                      ))}
                  </Grid>
                </Grid>
                <Grid className="grid gap-2 p-2 border-1 border-gray-200 rounded-xl">
                  <Grid className="flex justify-start select-none items-center gap-2">
                    <Typography
                      color="text-gray-600 dark:text-dark-100"
                      variant="caption"
                    >
                      سنگین
                    </Typography>
                  </Grid>
                  <Grid className="grid grid-cols-2 sm:grid-cols-1 md:grid-cols-2 gap-2 rounded-xl items-center">
                    {livestockTypes
                      ?.filter((opt) => opt?.weight_type === "H")
                      .map((item, i) => (
                        <Textfield
                          key={i}
                          start={item?.fa}
                          end="ماه"
                          formattedNumber
                          value={item?.age_month}
                          onChange={(e) => {
                            const value = parseInt(e.target.value) || 0;
                            const originalIndex = livestockTypes.findIndex(
                              (type) =>
                                type.livestock_type === item.livestock_type &&
                                type.weight_type === item.weight_type,
                            );
                            if (originalIndex !== -1) {
                              handleLivestockTypeChange(originalIndex, value);
                            }
                          }}
                        />
                      ))}
                  </Grid>
                </Grid>
              </>
            )}
          </Grid>

          <Grid className="flex gap-2 p-2 border-1 border-gray-200 rounded-xl items-center">
            <Checkbox
              label="فروش مازاد به توزیع سهمیه"
              checked={freeSale}
              onChange={() => {
                setFreeSale(!freeSale);
              }}
            />
          </Grid>

          <Grid className="flex gap-2 p-2 border-1 border-gray-200 rounded-xl items-center">
            <Checkbox
              label="پیش فروش به توزیع سهمیه"
              checked={preSale}
              onChange={() => {
                setPreSale(!preSale);
              }}
            />
          </Grid>

          <Grid className="flex gap-2 p-2 border-1 border-gray-200 rounded-xl items-center">
            <Checkbox
              label="محدودیت یکبار خرید از سهیمه"
              checked={oneTimePurchase}
              onChange={() => {
                setOneTimePurchase(!oneTimePurchase);
              }}
            />
          </Grid>
        </Grid>
      </Grid>
    </form>
  );
};
