import { z } from "zod";
import { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Grid } from "../../components/Grid/Grid";
import Button from "../../components/Button/Button";
import Textfield from "../../components/Textfeild/Textfeild";
import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete";
import AutoComplete from "../../components/AutoComplete/AutoComplete";
import { zValidateAutoComplete } from "../../data/getFormTypeErrors";
import { useApiMutation, useApiRequest } from "../../utils/useApiRequest";
import { useToast } from "../../hooks/useToast";
import { useModalStore } from "../../context/zustand-store/appStore";

const schema = z.object({
  organization: zValidateAutoComplete("سازمان"),
});

type FormValues = z.infer<typeof schema>;

type ParentDistItem = {
  id: number;
  dist_identity?: number;
  batch_identity: string | number | null;
  species_code: number;
  maxCount: number;
  label?: string;
};

export const DistributeFromDistribution = ({
  item,
  getData,
  isEdit,
  parentDistributions,
}: any) => {
  const showToast = useToast();
  const { closeModal } = useModalStore();

  const [dists, setDists] = useState<ParentDistItem[]>([]);
  const [selectedSpeciesKeys, setSelectedSpeciesKeys] = useState<
    (string | number)[]
  >([]);
  const [counts, setCounts] = useState<Record<number, number | "">>({});

  const {
    control,
    handleSubmit,
    setValue,
    trigger,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      organization: [],
    },
  });

  const { data: batchDetail } = useApiRequest({
    api: `/tag/web/api/v1/tag_distribution_batch/${item?.id}/`,
    method: "get",
    queryKey: ["tagDistributionBatchDetail", item?.id],
    enabled: !!item?.id && !isEdit,
  });

  const mutation = useApiMutation({
    api: `/tag/web/api/v1/tag_distribution/${item?.id}/${isEdit ? "edit_" : ""}distribute_distribution/`,
    method: isEdit ? "put" : "post",
  });

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

  useEffect(() => {
    const sourceDistributions = isEdit
      ? parentDistributions
      : item?.distributions?.length
        ? item.distributions
        : batchDetail?.distributions;

    if (!sourceDistributions?.length) {
      setDists([]);
      setCounts({});
      return;
    }

    const parentDists: ParentDistItem[] = sourceDistributions.map((d: any) => {
      const maxCount = d?.remaining_number || 0;
      return {
        id: d?.id ?? d?.dist_identity,
        dist_identity: d?.dist_identity,
        batch_identity: d?.batch_identity ?? null,
        species_code: d?.species_code,
        maxCount: Number(maxCount) || 0,
        label:
          d?.serial_from != null && d?.serial_to != null
            ? `از ${d.serial_from} تا ${d.serial_to}`
            : undefined,
      };
    });

    setDists(parentDists);

    if (isEdit && item?.distributions?.length) {
      const defaultCounts: Record<number, number | ""> = {};
      const defaultSpeciesKeys: (string | number)[] = [];

      parentDists.forEach((pd) => {
        const childDist = item.distributions.find(
          (cd: any) =>
            cd.parent_tag_distribution === pd.id ||
            cd.species_code === pd.species_code,
        );
        if (childDist) {
          defaultCounts[pd.id] = childDist.total_tag_count || 0;
          if (!defaultSpeciesKeys.includes(pd.species_code)) {
            defaultSpeciesKeys.push(pd.species_code);
          }
        }
      });

      setCounts(defaultCounts);
      setSelectedSpeciesKeys(defaultSpeciesKeys);
    } else {
      setCounts({});
      setSelectedSpeciesKeys([]);
    }
  }, [item?.distributions, batchDetail?.distributions, parentDistributions]);

  const speciesOptions = () =>
    speciesData?.results?.map((opt: any) => ({
      key: opt?.value,
      value: opt?.name,
    })) ?? [];

  const getSpeciesName = (speciesCode: number) =>
    speciesOptions().find((s: any) => s.key === speciesCode)?.value ?? "نامشخص";

  const visibleDists = dists.filter((d) =>
    selectedSpeciesKeys.includes(d.species_code),
  );

  const onSubmit = async (data: FormValues) => {
    const distsPayload = visibleDists
      .filter((d) => {
        const c = counts[d.id];
        return c !== "" && c !== undefined && c !== null && Number(c) > 0;
      })
      .map((d) => {
        const fromItem = item?.distributions?.find(
          (x: any) => x.id === d.id || x.dist_identity === d.id,
        );
        const batch_identity =
          fromItem != null ? fromItem.batch_identity : d.batch_identity;
        return {
          parent_tag_distribution: d.id,
          batch_identity: batch_identity != null ? batch_identity : null,
          species_code: d.species_code,
          count: Number(counts[d.id] ?? 0),
        };
      });

    if (distsPayload.length === 0) {
      showToast("حداقل یک گونه با تعداد معتبر وارد کنید", "error");
      return;
    }

    try {
      await mutation.mutateAsync({
        assigned_org: data.organization[0],
        parent_distribution_batch: item.id,
        dists: distsPayload,
      });

      showToast(
        isEdit
          ? "ویرایش توزیع با موفقیت انجام شد"
          : "توزیع از توزیع با موفقیت انجام شد",
        "success",
      );
      getData();
      closeModal();
    } catch (error: any) {
      showToast(
        error?.response?.data?.message || "خطا در ثبت اطلاعات!",
        "error",
      );
    }
  };

  const handleCountChange = (distId: number, value: number | "") => {
    setCounts((prev) => ({ ...prev, [distId]: value }));
  };

  const isValidCount = (dist: ParentDistItem) => {
    const c = counts[dist.id];
    if (c === "" || c === undefined || c === null) return false;
    const num = Number(c);
    return num > 0 && num <= dist.maxCount;
  };

  const speciesOptionsFromParent = () => {
    const uniqueSpecies = Array.from(
      new Map(dists.map((d) => [d.species_code, d])).values(),
    );
    return uniqueSpecies.map((d) => ({
      key: d.species_code,
      value: getSpeciesName(d.species_code),
    }));
  };

  const hasValidDists =
    visibleDists.length > 0 && visibleDists.every((d) => isValidCount(d));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Grid container column className="gap-3">
        <Controller
          name="organization"
          control={control}
          render={() => (
            <FormApiBasedAutoComplete
              defaultKey={item?.assigned_org?.id}
              title="انتخاب سازمان (دریافت‌کننده)"
              api={`auth/api/v1/organization/organizations_by_province?exclude=PSP&province=${item?.assigner_org?.province}`}
              keyField="id"
              valueField="name"
              error={!!errors.organization}
              errorMessage={errors.organization?.message}
              onChange={(r) => {
                setValue("organization", [r]);
                trigger("organization");
              }}
            />
          )}
        />

        {dists.length > 0 && speciesData?.results && (
          <>
            <AutoComplete
              data={speciesOptionsFromParent()}
              multiselect
              selectedKeys={selectedSpeciesKeys}
              onChange={(keys: (string | number)[]) => {
                setSelectedSpeciesKeys(keys);
              }}
              title="گونه"
            />
            {visibleDists.map((dist) => {
              const countVal = counts[dist.id];
              const numCount =
                countVal !== "" && countVal !== undefined && countVal !== null
                  ? Number(countVal)
                  : null;
              const isOverMax = numCount !== null && numCount > dist.maxCount;
              const isEmpty = countVal === "" || countVal === undefined;
              const helperText = isOverMax
                ? `تعداد نباید بیشتر از ${dist.maxCount.toLocaleString()} باشد`
                : isEmpty
                  ? "لطفا تعداد را وارد کنید"
                  : undefined;

              return (
                <Textfield
                  key={dist.id}
                  fullWidth
                  formattedNumber
                  placeholder={`تعداد ${getSpeciesName(dist.species_code)}${dist.label ? ` (${dist.label})` : ""} — حداکثر: ${dist.maxCount.toLocaleString()}`}
                  value={counts[dist.id] ?? ""}
                  onChange={(e) =>
                    handleCountChange(dist.id, Number(e.target.value))
                  }
                  error={isOverMax}
                  helperText={helperText}
                />
              );
            })}
          </>
        )}

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