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

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

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

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

  const [attributesData, setAttributesData] = useState<any>();
  const [brokersData, setBrokersData] = useState<any>();
  const [priceSelections, setPriceSelections] = useState<
    Array<{
      pricing_type: number;
      name: string;
      value?: number;
    }>
  >(item?.price_calculation_items || []);

  const { data: attributesResponse } = useApiRequest({
    api: `/product/web/api/v1/attribute/${
      formData?.product?.[0] || 1
    }/by_product/`,
    method: "get",
    params: { page: 1, page_size: 100 },
  });

  const { data: brokersResponse } = useApiRequest({
    api: `/product/web/api/v1/broker/`,
    method: "get",
    params: { page: 1, page_size: 100 },
  });

  const { data: priceTypesResponse } = useApiRequest({
    api: `/product/web/api/v1/quota_final_price_type/`,
    method: "get",
    params: { page: 1, page_size: 100 },
  });

  const getAttributesData = async () => {
    if (visible) {
      const getQuatity = (allocate: any) => {
        const result = item?.attribute_values?.find(
          (option: any) => option?.attribute === allocate?.id
        );
        if (result) {
          return result.value;
        } else {
          return 0;
        }
      };

      const d = attributesResponse?.results?.map((item: any) => {
        return {
          attribute: item?.id,
          value: getQuatity(item),
          fa: item?.name,
        };
      });

      if (d?.length) {
        setAttributesData(d);
      }
    }
  };

  const getBrokersData = async () => {
    if (visible) {
      const getQuatity = (allocate: any) => {
        const result = item?.brokers?.find(
          (option: any) => option?.broker === allocate?.id
        );
        if (result) {
          return result.value;
        } else {
          return 0;
        }
      };

      const d = brokersResponse?.results?.map((broker: any) => {
        const existingValue = getQuatity(broker);
        const value = item ? existingValue : broker?.fix_broker_price || 0;
        const active = broker?.fix_broker_price_state
          ? true
          : item
          ? existingValue > 0
          : value > 0;
        return {
          broker: broker?.id,
          value,
          fa: broker?.name,
          required: broker?.required,
          active,
          fix_broker_price_state: broker?.fix_broker_price_state,
        };
      });

      if (d?.length) {
        setBrokersData(d);
      }
    }
  };

  useEffect(() => {
    if (visible) {
      getAttributesData();
      getBrokersData();
    }
  }, [visible]);

  const getPriceList = () => {
    return [
      ...(brokersData || [])
        .filter((item: any) => item.active)
        .map((item: any) => ({
          value: item.fa,
          amount: item?.value,
          disabled: item?.fix_broker_price_state,
        })),
      ...(attributesData || []).map((item: any) => ({
        value: item.fa,
        amount: item?.value,
        disabled: false,
      })),
    ]?.map((item: any, i: number) => {
      return {
        key: i,
        ...item,
      };
    });
  };

  useEffect(() => {
    if (item) {
      return;
    }
    const fixedBrokers =
      brokersData?.filter((broker: any) => broker?.fix_broker_price_state) ||
      [];
    if (!fixedBrokers.length || !priceTypesResponse?.results?.length) {
      return;
    }
    setPriceSelections((prev) => {
      const next = [...prev];
      priceTypesResponse.results.forEach((pt: any) => {
        fixedBrokers.forEach((broker: any) => {
          const existingIndex = next.findIndex(
            (selection) =>
              selection.pricing_type === pt?.id && selection.name === broker.fa
          );
          if (existingIndex === -1) {
            next.push({
              pricing_type: pt?.id,
              name: broker.fa,
              value: broker.value || 0,
            });
          } else {
            next[existingIndex] = {
              ...next[existingIndex],
              value: broker.value || 0,
            };
          }
        });
      });
      return next;
    });
  }, [item, brokersData, priceTypesResponse]);

  const getPriceForType = (typeId: number) => {
    const selectedItems =
      priceSelections?.filter((item) => item.pricing_type === typeId) || [];
    return getPriceList()
      ?.filter((opt) => {
        const isSelected = selectedItems.some(
          (item) => item.name === opt.value
        );
        if (!isSelected) return false;
        const broker = brokersData?.find((b: any) => b.fa === opt.value);
        if (broker) {
          return broker.active;
        }
        return true;
      })
      ?.reduce((sum, item) => sum + (item.amount || 0), 0);
  };

  const handleSubmitForm = () => {
    const allTypesSelected = priceTypesResponse?.results?.every((pt: any) =>
      priceSelections?.some((item) => item.pricing_type === pt?.id)
    );

    if (
      allTypesSelected &&
      !brokersData?.filter((opt: any) => opt.required && opt.value === 0).length
    ) {
      const activeBrokersData = brokersData?.filter(
        (broker: any) => broker.active
      );
      const activeBrokerNames = activeBrokersData?.map((b: any) => b.fa) || [];
      const filteredPriceSelections = priceSelections?.filter((item) => {
        const isBroker = brokersData?.some((b: any) => b.fa === item.name);
        if (isBroker) {
          return activeBrokerNames.includes(item.name);
        }
        return true;
      });
      onSubmit({
        price_calculation_items: filteredPriceSelections,
        price_attributes_data: attributesData,
        broker_data: activeBrokersData,
      });
    }
  };

  const updateSelectionValue = (name: string, value: number) => {
    setPriceSelections((prev) =>
      prev.map((item) =>
        item.name === name
          ? {
              ...item,
              value,
            }
          : item
      )
    );
  };

  return (
    <form ref={internalRef} onSubmit={handleSubmitForm}>
      <Grid container column>
        <Typography className="mt-8" variant="body2">
          مولفه های قیمت گذاری
        </Typography>
        <Grid className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 mt-2 gap-4 items-start">
          {attributesData?.map((item: any, i: number) => (
            <Textfield
              key={i}
              start={item?.fa}
              end="ریال"
              formattedNumber
              value={item?.value}
              onChange={(e) => {
                const nextValue = parseInt(e.target.value) || 0;
                setAttributesData((prev: any) => {
                  if (!prev) {
                    return prev;
                  }
                  const newPlans = [...prev];
                  const target = newPlans[i];
                  if (!target) {
                    return prev;
                  }
                  const updated = {
                    ...target,
                    value: nextValue,
                  };
                  newPlans[i] = updated;
                  updateSelectionValue(updated.fa, nextValue);
                  return newPlans;
                });
              }}
            />
          ))}
        </Grid>
        <Typography className="mt-8" variant="body2">
          شرکا
        </Typography>
        <Grid className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 mt-2 gap-4 items-start">
          {brokersData?.map((item: any, i: number) => (
            <Grid
              className="grid gap-2 p-2 border-1 border-gray-200 rounded-xl"
              key={i}
            >
              <Grid className="flex justify-start select-none items-center gap-2">
                <Checkbox
                  checked={item?.fix_broker_price_state ? true : item?.active}
                  disabled={item?.fix_broker_price_state}
                  onChange={() => {
                    if (item?.fix_broker_price_state) {
                      return;
                    }
                    const newActiveState = !item.active;
                    setBrokersData((prev: any) => {
                      const newPlans = [...prev];
                      newPlans[i] = {
                        ...newPlans[i],
                        active: newActiveState,
                      };
                      return newPlans;
                    });
                    if (!newActiveState) {
                      setPriceSelections((prev) =>
                        prev.filter((selection) => selection.name !== item.fa)
                      );
                    }
                  }}
                />
                <Typography
                  color="text-gray-600 dark:text-dark-100"
                  variant="caption"
                >
                  تعرفه {item?.fa}
                </Typography>
              </Grid>

              {(item?.required || item?.active) && (
                <Textfield
                  start={`تعرفه ${item?.fa}`}
                  end="ریال"
                  formattedNumber
                  value={item?.value}
                  disabled={item?.fix_broker_price_state}
                  onChange={(e) => {
                    const nextValue = parseInt(e.target.value) || 0;
                    setBrokersData((prev: any) => {
                      if (!prev) {
                        return prev;
                      }
                      const newPlans = [...prev];
                      const target = newPlans[i];
                      if (!target) {
                        return prev;
                      }
                      const updated = {
                        ...target,
                        value: nextValue,
                      };
                      newPlans[i] = updated;
                      updateSelectionValue(updated.fa, nextValue);
                      return newPlans;
                    });
                  }}
                  error={item?.required && !item?.value ? true : false}
                  helperText={
                    item?.required && !item?.value
                      ? "تعرفه این کارگزار اجباری است!"
                      : ""
                  }
                />
              )}
            </Grid>
          ))}
        </Grid>

        <Typography className="mt-8" variant="body2">
          نحوه محاسبه قیمت
        </Typography>
        <Grid className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 mt-2 gap-4 items-start">
          {priceTypesResponse?.results?.map((pt: any) => (
            <AutoComplete
              key={pt?.id}
              multiselect
              selectField
              data={getPriceList()}
              title={pt?.name}
              onChange={(e: (string | number)[]) => {
                setPriceSelections((prev) => {
                  const filtered = prev.filter(
                    (item) => item.pricing_type !== pt?.id
                  );
                  const requiredBrokers = item
                    ? []
                    : brokersData?.filter(
                        (broker: any) => broker?.fix_broker_price_state
                      ) || [];
                  const newSelections = e.map((selectedKey) => {
                    const selectedItem = getPriceList().find(
                      (item) => item.key === selectedKey
                    );

                    return {
                      pricing_type: pt?.id,
                      name: selectedItem?.value || "",
                      value: selectedItem?.amount || 0,
                    };
                  });
                  const merged = [...filtered, ...newSelections];
                  requiredBrokers.forEach((broker: any) => {
                    const existingIndex = merged.findIndex(
                      (selection) =>
                        selection.pricing_type === pt?.id &&
                        selection.name === broker.fa
                    );
                    const brokerValue = broker.value || 0;
                    if (existingIndex === -1) {
                      merged.push({
                        pricing_type: pt?.id,
                        name: broker.fa,
                        value: brokerValue,
                      });
                    } else {
                      merged[existingIndex] = {
                        ...merged[existingIndex],
                        value: brokerValue,
                      };
                    }
                  });
                  return merged;
                });
              }}
              selectedKeys={(() => {
                const filtered =
                  priceSelections?.filter(
                    (item) => item.pricing_type === pt?.id
                  ) || [];
                const keys = filtered.map((item) => {
                  const priceItem = getPriceList().find(
                    (p) => p.value === item.name
                  );
                  return priceItem?.key;
                });
                return keys.filter((key) => key !== undefined);
              })()}
              error={
                !priceSelections?.some((item) => item.pricing_type === pt?.id)
              }
              helperText={
                priceSelections?.some((item) => item.pricing_type === pt?.id)
                  ? ""
                  : "لطفا یکی از موارد را انتخاب کنید!"
              }
            />
          ))}
        </Grid>

        <Grid className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 mt-8 gap-4 items-start">
          {priceTypesResponse?.results?.map((pt: any, idx: number) => (
            <Grid
              key={pt?.id}
              className={`flex gap-2 p-2 rounded-xl items-center ${
                idx % 2 === 0
                  ? "bg-primary-200/55 dark:bg-dark-400"
                  : "bg-gray2-200 dark:bg-dark-400"
              }`}
            >
              <Typography
                variant="body2"
                color={
                  idx % 2 === 0
                    ? "text-gray-500 dark:text-dark-100"
                    : "text-gray-600 dark:text-dark-100"
                }
              >
                {pt?.name}: {getPriceForType(pt?.id)?.toLocaleString()} ریال
              </Typography>
            </Grid>
          ))}
        </Grid>
      </Grid>
    </form>
  );
};
