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

const ItemPendenciaFaturamento = ({
  itemCompra,
  indexItem,
  setItensCompra,
  setKeyListItens,
  setHandleSubmits,
  dadosCard,
  // form,
}: {
  [x: string]: any;
}) => {
  const [imageUrls, setImageUrls] = useState<string[]>([]);
  const [anexos, setAnexos] = useState<File[]>(itemCompra.anexos || []);
  const [inputKey, setInputKey] = useState(1);

  const { isMobile } = useScreenContext();
  const { usuario } = useAuth();

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

  useEffect(() => {
    form?.setValue(
      "cod_coleta_faturamento",
      itemCompra?.cod_coleta_faturamento,
    );
  }, []);

  useEffect(() => {
    setHandleSubmits((prev: any) => {
      const newHandleSubmits = [...prev];
      newHandleSubmits.splice(indexItem, 1, handleSubmit);
      return newHandleSubmits;
    });
  }, [handleSubmit, indexItem]);

  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()!,
        })),
      );
      setItensCompra((prev: any[]) => {
        const newItensCompra = [...prev];
        newItensCompra.splice(indexItem, 1, {
          ...itemCompra,
          anexos,
          caminhos_anexos: anexos.map((anexo: File) => ({
            caminho_anexo_faturamento: `clientes/${dadosCard.cliente?.pasta_cliente}/${dadosCard.id_coleta_cliente}/Faturamento/${anexo.name}`,
          })),
        });

        return newItensCompra;
      });
    };

    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 (anexos.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);
    }
  };

  return (
    <fieldset className="flex flex-col border-black/25 border rounded p-2 px-3 w-full">
      <div className="w-full flex justify-end">
        <Button
          type="button"
          className={"p-2 bg-error text-white"}
          onClick={() => {
            setItensCompra((prev: any[]) => {
              const newItensCompra = [...prev];
              newItensCompra.splice(indexItem, 1);

              return newItensCompra;
            });
            setHandleSubmits((prev: any) => {
              const newHandleSubmits = [...prev];
              newHandleSubmits.splice(indexItem, 1);
              return newHandleSubmits;
            });
            setKeyListItens((prev: number) => prev + 1);
          }}
        >
          <Trash />
        </Button>
      </div>
      <div className={`flex flex-${isMobile ? "col" : "row"} gap-2`}>
        <Input
          name={`data_faturamento`}
          label="Data"
          formulario={form}
          type="date"
          required
          error="Informe a Data do Pedido"
          onBlur={(e: any) =>
            setItensCompra((prev: any[]) => {
              const newItensCompra = [...prev];
              newItensCompra.splice(indexItem, 1, {
                ...itemCompra,
                data_faturamento: e.target.value,
              });

              return newItensCompra;
            })
          }
          defaultValue={itemCompra.data_faturamento}
        />
        <Input
          name={`numero_nota_fiscal_faturamento`}
          label="Nº da Nota Fiscal"
          formulario={form}
          mascara="numerico"
          onBlur={(e: any) =>
            setItensCompra((prev: any[]) => {
              const newItensCompra = [...prev];
              newItensCompra.splice(indexItem, 1, {
                ...itemCompra,
                numero_nota_fiscal_faturamento: e.target.value,
              });

              return newItensCompra;
            })
          }
          defaultValue={itemCompra.numero_nota_fiscal_faturamento}
        />
        {["2", "4"].includes(dadosCard?.tipoNegocio_coleta) && (
          <Input
            name={`valor_faturamento`}
            label="Valor Faturado"
            formulario={form}
            mascara="numero"
            prefix={"R$"}
            onBlur={(e: any) =>
              setItensCompra((prev: any[]) => {
                const newItensCompra = [...prev];
                newItensCompra.splice(indexItem, 1, {
                  ...itemCompra,
                  valor_faturamento: e.target.value,
                });

                return newItensCompra;
              })
            }
            defaultValue={itemCompra.valor_faturamento}
          />
        )}
      </div>
      <Input
        name={`observacao_faturamento`}
        label="Observação"
        formulario={form}
        type="textarea"
        error="Informe a Observação"
        onBlur={(e: any) =>
          setItensCompra((prev: any[]) => {
            const newItensCompra = [...prev];
            newItensCompra.splice(indexItem, 1, {
              ...itemCompra,
              observacao_faturamento: e.target.value,
            });

            return newItensCompra;
          })
        }
        defaultValue={itemCompra.observacao_faturamento}
        rows={3}
      />
      <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={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={indexItem}
          type="file"
          className="hidden"
          key={inputKey}
          onInput={(e) => adicionarAnexo(e)}
        />
      </div>
    </fieldset>
  );
};

export default ItemPendenciaFaturamento;
