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

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

type PlansProps = {
  name: string;
  id: number;
  incentive_plan: number;
};

export const QuotaLevel2 = ({ item, onSubmit, setFormRef, visible }: Props) => {
  const [activePlans, setActivePlans] = useState<any>();

  const internalRef = useRef<HTMLFormElement>(null);

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

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

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

  const getData = async () => {
    if (livestockData) {
      const d = data?.results?.map((option: PlansProps) => {
        const founded = item?.incentive_plan?.find(
          (itm: PlansProps) => itm?.incentive_plan === option.id
        );
        return {
          name: option?.name,
          incentive_plan: option?.id,
          active: founded ? true : false,
          live_stocks: livestockData.results.flatMap((item: any) => {
            const foundedLiveStock = founded?.live_stocks?.find(
              (option: any) => option?.id === item.id
            );

            return [
              {
                incentive_plan: option?.id,
                livestock_type: item.id,
                quantity_kg: foundedLiveStock?.quantity || 0,
                fa: item.name,
              },
            ];
          }),
        };
      });
      setActivePlans(d);
    }
  };

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

  const handleSubmitForm = () => {
    onSubmit({
      active_plans: activePlans
        ?.filter((option: any) => option?.active)
        ?.flatMap((option: any) => {
          return option?.live_stocks;
        })
        .filter((opt: { quantity_kg: number }) => opt.quantity_kg > 0),
    });
  };

  return (
    <form ref={internalRef} onSubmit={handleSubmitForm}>
      <Grid container column className="mt-4 gap-2">
        <Grid className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-4 items-start">
          {activePlans?.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?.active}
                  onChange={() => {
                    setActivePlans((prev: any) => {
                      const newPlans = [...prev];
                      newPlans[i] = {
                        ...newPlans[i],
                        active: !newPlans[i].active,
                      };
                      return newPlans;
                    });
                  }}
                />
                <Typography
                  color="text-gray-600 dark:text-dark-100"
                  variant="caption"
                >
                  طرح {item?.name}
                </Typography>
              </Grid>

              {item?.active && (
                <>
                  <Grid className="grid gap-4 items-start">
                    <Grid className="grid gap-2 p-2 border-gray-200 rounded-xl">
                      {item?.live_stocks.map((item: any, idx: number) => {
                        return (
                          <Textfield
                            value={item.quantity_kg}
                            key={idx}
                            start={item.fa}
                            end="کیلوگرم"
                            formattedNumber
                            onChange={(e) => {
                              setActivePlans((prev: any) => {
                                const newPlans = [...prev];
                                if (
                                  newPlans[i] &&
                                  newPlans[i].live_stocks &&
                                  newPlans[i].live_stocks[idx]
                                ) {
                                  newPlans[i].live_stocks[idx].quantity_kg =
                                    parseInt(e.target.value);
                                }

                                return newPlans;
                              });
                            }}
                          />
                        );
                      })}
                    </Grid>
                  </Grid>
                </>
              )}
            </Grid>
          ))}
        </Grid>
      </Grid>
    </form>
  );
};
