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

import FileRenderer from "@/components/FileRenderer";
import Button from "@/components/Forms/Button";
import Input from "@/components/Forms/Input";
import InputGroup from "@/components/Forms/InputGroup";
import { useAuth } from "@/src/contexts/authContext";
import { GetForm, GetGallery } from "@/utils";
import { useEffect, useState } from "react";
import { FaPaperclip } from "react-icons/fa";
import { MdClose } from "react-icons/md";

const PendenciaEntregaKit = ({ dadosCard, onSubmitFunction }: any) => {
  const [imageUrls, setImageUrls] = useState<string[]>([]);
  const [anexos, setAnexos] = useState<File[]>([]);
  const [inputKey, setInputKey] = useState(1);
  const [isLoading, setIsLoading] = useState(false);

  const { usuario } = useAuth();

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

  useEffect(() => {
    setInputKey(inputKey + 1);

    const loadImages = async () => {
      const newImageUrls = await Promise.all(
        anexos.map(async (anexo) => {
          const reader = new FileReader();
          return new Promise((resolve) => {
            reader.onload = () => resolve(reader.result as string);
            reader.readAsDataURL(anexo);
          });
        })
      );
      setImageUrls(newImageUrls as string[]);
      setGallery(
        newImageUrls.map((newImageUrl, index) => ({
          src: newImageUrl as string,
          name: anexos[index].name?.split("/").pop()!,
        }))
      );
      form.setValue(
        "caminhos_anexos",
        anexos.map((anexo: File) => ({
          caminho_anexo_pendencia_entrega_kit: `clientes/${dadosCard.cliente?.pasta_cliente}/${dadosCard.id_coleta_cliente}/EntregaKit/${anexo.name}`,
        }))
      );
    };

    loadImages();
  }, [anexos]);

  const handleDownload = (anexo: File) => {
    const url = URL.createObjectURL(anexo);
    const link = document.createElement("a");
    link.href = url;
    link.download = anexo.name;
    link.click();
    URL.revokeObjectURL(url);
  };

  const adicionarAnexo = (event: any) => {
    const inputElement = event.target as HTMLInputElement;

    if (inputElement.files && inputElement.files.length > 0) {
      let arquivo = inputElement.files[0];
      setAnexos((prev) => {
        // if (prev.some((anexo) => anexo.name == arquivo.name)) {
        let nomeArquivo = arquivo.name?.replaceAll("/", "_");
        let extensao = nomeArquivo.substring(nomeArquivo.lastIndexOf("."));
        let nomeBase = nomeArquivo.substring(0, nomeArquivo.lastIndexOf("."));

        let contador = 0;
        let novoNome = nomeArquivo;
        while (prev.some((anexo) => anexo.name === novoNome)) {
          novoNome = `${nomeBase} (${++contador})${extensao}`;
        }
        arquivo = new File([arquivo], novoNome, {
          type: arquivo.type,
          lastModified: arquivo.lastModified,
        });
        // }

        return [...prev, arquivo];
      });

      setInputKey(inputKey + 1);
    }
  };

  function onSubmitPendenciaEntregaKit(data: any) {
    setIsLoading(true);
    return onSubmitFunction({
      ...data,
      anexos,
      codColeta_pendencia_entrega_kit: dadosCard.id_coleta_cliente,
      usuario,
    }).finally(() => setIsLoading(false));
  }

  return (
    <div>
      <InputGroup>
        <Input name="data_pendencia_entrega_kit" label="Data do recebimento" formulario={form} type="date" />
        <Input name="nome_recebedor_pendencia_entrega_kit" label="Nome do Recebedor" formulario={form} />
      </InputGroup>
      <Input name="observacoes_pendencia_entrega_kit" label="Observações" formulario={form} type="textarea" />
      <div className="pt-1">
        <div className="flex flex-col gap-1 max-h-[200px] overflow-auto">
          {imageUrls.map((imageUrl, index) => {
            const anexo: File = anexos[index];
            return (
              <div
                key={index}
                className="flex flex-row justify-between px-2 cursor-pointer hover:bg-[rgb(0,0,0)]/[.1] border border-transparent hover:border-black/[0.4] rounded"
                onClick={() => handleDownload(anexo)}
              >
                <div className="w-[400px] overflow-hidden text-ellipsis p-1 flex flex-row items-center gap-1">
                  <figure
                    className="flex flex-col items-center overflow-hidden w-[20%] hover:w-[50%] transition-all"
                    onClick={(e) => {
                      e.stopPropagation();
                      openGallery(index);
                    }}
                  >
                    <FileRenderer
                      src={imageUrl}
                      name={anexo?.name?.split("/").pop()!}
                      className={
                        "h-full w-30 flex flex-col items-center justify-center bg-animate-pulse bg-white rounded overflow-hidden"
                      }
                      width={200}
                    />
                  </figure>
                  {anexo?.name}
                </div>
                <button
                  type="button"
                  onClick={(e) => {
                    e.stopPropagation();
                    setAnexos((prev) => {
                      const newAnexos = [...prev];
                      newAnexos.splice(index, 1);
                      return newAnexos;
                    });
                  }}
                >
                  <MdClose />
                </button>
              </div>
            );
          })}
        </div>
        <label
          htmlFor="add_anexo"
          // htmlFor={indexItem}
          className="justify-center dark:text-white whitespace-nowrap rounded-md font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 text-primary-foreground flex bg-success hover:brightness-90 hover:bg-success justify-self-end text-sm h-fit items-center w-fit m-1 mb-4 p-1 px-2 cursor-pointer"
        >
          <FaPaperclip /> Adicionar Anexo
        </label>
        <input
          id="add_anexo"
          // id={indexItem}
          type="file"
          // accept="image/png, image/gif, image/jpeg"
          accept="image/*"
          capture="environment"
          className="hidden"
          key={inputKey}
          onInput={(e) => adicionarAnexo(e)}
        />
      </div>
      <div className="w-full flex justify-end pt-3">
        <Button type="button" onClick={handleSubmit(onSubmitPendenciaEntregaKit)} loading={isLoading}>
          Salvar
        </Button>
      </div>
    </div>
  );
};

export default PendenciaEntregaKit;
