import Button from "@/components/Forms/Button";
// import { listarFabricantes } from "@/requests/CRUD/Fabricante/listarFabricantes";

import { GetForm } from "@/utils";
import { useEffect, useState } from "react";
import ItemPendenciaFaturamento from "./ItemPendenciaFaturamento";

const PendenciaFaturamento = ({ dadosCard, onSubmitFunction }: any) => {
  const itemVazio = {
    cod_coleta_faturamento: dadosCard.id_coleta_cliente,
    data_faturamento: "",
    numero_nota_fiscal_faturamento: "",
    observacao_faturamento: "",
    anexos: [],
    ...(["2", "4"].includes(dadosCard?.tipoNegocio_coleta)
      ? { valor_faturamento: "" }
      : {}),
  };
  const [itensCompra, setItensCompra] = useState<any[]>([{ ...itemVazio }]);
  const [keyListItens, setKeyListItens] = useState(0);
  const [isLoading, setIsLoading] = useState(false);

  const [handleSubmits, setHandleSubmits] = useState<any[]>([]);

  // const validateNewHandleSubmits = getValidateNewHandleSubmits(
  //   handleSubmits,
  //   setHandleSubmits,
  // );
  // const validateNewHandleSubmits = (
  //   value: any[] | ((prev: any[]) => any[]),
  // ) => {
  //   // 1. Resolve o valor (se for função, executa; se não, usa o valor direto)
  //   const nextValue =
  //     typeof value === "function" ? value(handleSubmits) : value;

  //   // 2. Executa a sua lógica de validação
  //   const isValid = nextValue?.length != handleSubmits?.length;
  //   // &&
  //   // !equal(nextValue, handleSubmits);
  //   if (isValid) {
  //     setHandleSubmits(nextValue);
  //   }
  // };

  const { handleSubmit, ...form } = GetForm();

  useEffect(() => {
    const itensForm = form.control._formValues?.itensCompra;
    if (
      !itensForm ||
      JSON.stringify(itensCompra) != JSON.stringify(itensForm)
    ) {
      form.setValue("itensCompra", itensCompra);
    }
  }, [itensCompra]);

  const onSubmitFaturamento = async (e: any) => {
    setIsLoading(true);
    return Promise.all(
      handleSubmits.map(
        (handleSubmitItem) =>
          new Promise((resolve, reject) => {
            handleSubmitItem((d: any) => resolve(d))(e).finally(() =>
              reject(false),
            );
          }),
      ),
    )
      .then((res) => {
        return onSubmitFunction(res).finally(() => setIsLoading(false));
      })
      .catch((err) => {
        setIsLoading(false);
      });
  };

  return (
    <div key={keyListItens}>
      <div className="w-full flex justify-end pb-3">
        <Button
          type="button"
          className="bg-primary"
          onClick={() => {
            setItensCompra((prev) => [{ ...itemVazio }, ...prev]);
            // setItensCompra((prev) => [...prev, { ...itemVazio }]);
            setKeyListItens((prev) => prev + 1);
          }}
        >
          Novo Item
        </Button>
      </div>
      <div className="flex flex-col gap-2 max-h-[65vh] overflow-auto">
        {itensCompra.map((itemCompra, indexItem) => (
          <ItemPendenciaFaturamento
            key={indexItem}
            itemCompra={itemCompra}
            indexItem={indexItem}
            setItensCompra={setItensCompra}
            setKeyListItens={setKeyListItens}
            setHandleSubmits={setHandleSubmits}
            dadosCard={dadosCard}
          />
        ))}
      </div>
      <div className="w-full flex justify-end pt-3">
        <Button type="button" onClick={onSubmitFaturamento} loading={isLoading}>
          Concluir Faturamento
        </Button>
      </div>
    </div>
  );
};

export default PendenciaFaturamento;
