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 { RadioGroup } from "../../components/RadioButton/RadioGroup";
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 distributionTypeOptions = [
  { label: "توزیع گروهی", value: "group" },
  { label: "توزیع تصادفی", value: "random" },
];

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

type FormValues = z.infer<typeof schema>;

type BatchItem = {
  batch_identity?: string | number;
  species_code?: number;
  count: number | "";
  label?: string;
};

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

  const isEdit = Boolean(item?.id);

  const [distributionType, setDistributionType] = useState<"group" | "random">(
    isEdit
      ? item?.distribution_type === "random"
        ? "random"
        : "group"
      : "group",
  );
  const [batches, setBatches] = useState<BatchItem[]>([]);

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

  const mutation = useApiMutation({
    api: isEdit
      ? `/tag/web/api/v1/tag_distribution/${item?.id}`
      : "/tag/web/api/v1/tag_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(() => {
    if (!item) return;

    setValue("organization", [item.assigned_org?.id]);
    trigger("organization");

    const mappedBatches = item.distributions.map((d: any) => ({
      ...(item.distribution_type === "batch" && {
        batch_identity: item.dist_batch_identity,
      }),
      species_code: d.species_code,
      count: d.distributed_number,
      label:
        item.distribution_type === "batch"
          ? `از ${d.serial_from ?? "-"} تا ${d.serial_to ?? "-"}`
          : undefined,
    }));

    setBatches(mappedBatches);
  }, [item]);

  const onSubmit = async (data: FormValues) => {
    const dists =
      distributionType === "random"
        ? batches.map((b) => ({
            species_code: b.species_code,
            count: b.count,
          }))
        : batches.map((b) => ({
            batch_identity: b.batch_identity,
            species_code: b.species_code,
            count: b.count,
          }));

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

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

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

  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");
              }}
            />
          )}
        />

        <RadioGroup
          direction="row"
          options={distributionTypeOptions}
          value={distributionType}
          onChange={(e) => {
            const val = e.target.value as "group" | "random";
            setDistributionType(val);
            setBatches([]);
          }}
        />

        {distributionType === "group" && (
          <FormApiBasedAutoComplete
            title="گروه پلاک"
            api="/tag/web/api/v1/tag_batch/"
            keyField="batch_identity"
            secondaryKey="species_code"
            valueTemplate="از v1 تا v2"
            valueField={["serial_from"]}
            valueField2={["serial_to"]}
            groupBy="species_code"
            defaultKey={
              item?.distributions?.map((d: any) => d.batch_identity) || []
            }
            groupFunction={(item) =>
              speciesOptions().find((s: any) => s.key === item)?.value ||
              "نامشخص"
            }
            valueTemplateProps={[{ v1: "string" }, { v2: "string" }]}
            multiple
            onChange={(items) => {
              setBatches(
                items?.map((r: any) => {
                  const existing = batches.find(
                    (b) =>
                      b.batch_identity === r.key1 && b.species_code === r.key2,
                  );
                  return {
                    batch_identity: r.key1,
                    species_code: r.key2,
                    count: existing?.count ?? "",
                  };
                }) || [],
              );
            }}
            onChangeValue={(labels) => {
              setBatches((prev) =>
                prev.map((item, index) => ({
                  ...item,
                  label: labels[index],
                })),
              );
            }}
          />
        )}

        {distributionType === "random" && speciesData?.results && (
          <AutoComplete
            data={speciesOptions()}
            multiselect
            selectedKeys={batches.map((b) => b.species_code)}
            onChange={(keys: (string | number)[]) => {
              setBatches(
                keys.map((k) => {
                  const prev = batches.find((b) => b.species_code === k);
                  return {
                    species_code: k as number,
                    count: prev?.count ?? "",
                  };
                }),
              );
            }}
            title="گونه"
          />
        )}

        {batches.map((batch, index) => (
          <Textfield
            key={index}
            fullWidth
            formattedNumber
            placeholder={
              distributionType === "group"
                ? `تعداد ${
                    speciesOptions().find(
                      (s: any) => s.key === batch.species_code,
                    )?.value
                  } (${batch.label}) `
                : `تعداد ${
                    speciesOptions().find(
                      (s: any) => s.key === batch.species_code,
                    )?.value
                  }`
            }
            value={batch.count}
            onChange={(e) => {
              const next = [...batches];
              next[index].count = Number(e.target.value);
              setBatches(next);
            }}
          />
        ))}

        <Button
          disabled={
            batches.length === 0 ||
            batches.some(
              (b) =>
                b.count === "" ||
                b.count === undefined ||
                b.count === null ||
                Number(b.count) <= 0,
            )
          }
          type="submit"
        >
          {isEdit ? "ویرایش" : "ثبت"}
        </Button>
      </Grid>
    </form>
  );
};
