import LoaderSun from "@/components/common/Loader/LoaderSun";
import FileRenderer from "@/components/FileRenderer";
import Input from "@/components/Forms/Input";
import InputSelectComponent from "@/components/Forms/InputSelect";
import { baixarAwsBase64 } from "@/requests/common/Aws/baixarAws";
import { GetForm, GetGallery, handleDownload } from "@/utils";
import { useEffect, useState } from "react";
import { FaPaperclip } from "react-icons/fa";
import { MdClose } from "react-icons/md";

export default function FormFollowUp({
  onSubmitFunction,
  defaultValues,
  children,
  usuarios,
  ...rest
}: any) {
  const [anexos, setAnexos] = useState<File[]>(false || []);
  const [imageUrls, setImageUrls] = useState<string[]>([]);
  const [isLoadingAnexos, setIsLoadingAnexos] = useState(false);
  const [inputKey, setInputKey] = useState(1);

  const 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);
          }).catch(() => {});
        }),
      );
      setImageUrls(newImageUrls as string[]);
      setGallery(
        newImageUrls.map((newImageUrl, index) => ({
          src: newImageUrl as string,
          name: anexos[index].name?.split("/").pop()!,
        })),
      );
    };

    loadImages();
  }, [anexos]);

  useEffect(() => {
    if (defaultValues && defaultValues["anexos_data"]) {
      const anexos_data = defaultValues["anexos_data"];

      setIsLoadingAnexos(true);
      Promise.all(
        anexos_data.map((data: any) =>
          baixarAwsBase64(data["caminho_anexo_follow_up"]).then((res) => {
            const resultObject =
              typeof res === "string" ? JSON.parse(res) : res;
            const base64Content = resultObject.base64;

            const byteCharacters = atob(base64Content);
            const byteNumbers = new Array(byteCharacters.length);
            for (let i = 0; i < byteCharacters.length; i++) {
              byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            const byteArray = new Uint8Array(byteNumbers);
            const blob = new Blob([byteArray], {
              type: "application/octet-stream",
            });

            const fileName = data["caminho_anexo_follow_up"].split("/").pop();
            const file = new File([blob], fileName, { type: blob.type });
            return file;
          }),
        ),
      )
        .then((res) => {
          setAnexos(res);
        })
        .finally(() => setIsLoadingAnexos(false));
    }
  }, []);

  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 onSubmitFormFollowUp(data: any) {
    data["anexos"] = anexos;
    return onSubmitFunction(data);
  }
  return (
    <form
      onSubmit={form.handleSubmit(onSubmitFormFollowUp)}
      className="flex flex-col gap-3"
    >
      <Input
        name="descricao_follow_up"
        label="Descrição"
        type="textarea"
        formulario={form}
        defaultValue={defaultValues && defaultValues?.descricao_follow_up}
      />
      <div className="flex flex-row gap-4">
        <InputSelectComponent
          name="status_follow_up"
          label="Status"
          options={[
            {
              value: "0",
              label: "Pendente",
            },
            {
              value: "1",
              label: "Concluído",
            },
          ]}
          formulario={form}
          defaultValue={
            (defaultValues && defaultValues?.status_follow_up) || "0"
          }
          width="w-fit"
        />
        <InputSelectComponent
          name="responsavel_follow_up"
          label="Responsável"
          options={[
            {
              value: "0",
              label: "Não é Necessário",
            },
            ...usuarios?.map((usuario: any) => ({
              ...usuario,
              value: usuario?.id_usuario,
              label: usuario?.nome_usuario,
            })),
          ]}
          formulario={form}
          defaultValue={
            (defaultValues && defaultValues?.responsavel_follow_up) || "0"
          }
          width="w-fit"
        />
      </div>
      <div>
        <div>Anexos</div>
        <div className="pt-1">
          <div className="flex flex-col gap-1 max-h-[200px] overflow-auto">
            {isLoadingAnexos ? (
              <div className="flex justify-center items-center">
                <LoaderSun height={100} />
              </div>
            ) : (
              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 text-sm h-fit items-center w-fit m-1 mb-4 p-1 px-2 cursor-pointer"
          >
            <FaPaperclip /> Adicionar Documento
          </label>
          <input
            id="add_anexo"
            // id={indexItem}
            type="file"
            // accept="image/png, image/gif, image/jpeg"
            className="hidden"
            key={inputKey}
            onInput={(e) => adicionarAnexo(e)}
          />
        </div>
      </div>
      <div>{children}</div>
    </form>
  );
}
