import LoaderSun from "@/components/common/Loader/LoaderSun";
import FileRenderer from "@/components/FileRenderer";
import Button from "@/components/Forms/Button";
import { baixarAwsBase64 } from "@/requests/common/Aws/baixarAws";
import { editarAtendimento } from "@/requests/CRUD/Atendimento/editarAtendimento";
import { FormatFields, GetGallery, handleDownload } from "@/utils";
import { useEffect, useState } from "react";
import { FaPaperclip } from "react-icons/fa";

export default function CardDemanda({ dadosAtualCard, reListarDemandas }: any) {
  const [anexos, setAnexos] = useState<File[]>(false || []);
  const [imageUrls, setImageUrls] = useState<string[]>([]);
  const [isLoadingAnexos, setIsLoadingAnexos] = useState(false);
  const [inputKey, setInputKey] = useState(1);
  const [abaSelecionada, setAbaSelecionada] = useState("Dados Gerais");
  const [isLoading, setIsLoading] = useState(false);

  const { openGallery, setGallery } = GetGallery();

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

        setIsLoadingAnexos(true);
        Promise.all(
          anexos_data.map((data: any) =>
            baixarAwsBase64(data["caminho_chamado_anexo"]).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_chamado_anexo"].split("/").pop();
              const file = new File([blob], fileName, { type: blob.type });
              return file;
            })
          )
        )
          .then((res) => {
            setAnexos(res);
          })
          .finally(() => setIsLoadingAnexos(false));
      }
    }
  }, [dadosAtualCard]);

  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]);

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

  const dadosRenderizados: any = {
    ["Usuario Responsável"]: dadosAtualCard.nome_usuario,
    ["Cliente"]: dadosAtualCard.nome_cliente,
    ["Tipo de Atendimento"]: dadosAtualCard.tipo_cham_formatado,
    ["Núemro do Chamado"]: dadosAtualCard.id_cham,
    ["Loja"]: dadosAtualCard.nome_loja,
    ["Negócio"]:
      dadosAtualCard.nome_negocio_coleta == null
        ? "Sem Negócio"
        : dadosAtualCard.nome_negocio_coleta,
    ["Prioridade"]: dadosAtualCard.nome_prioridade,
    ["Relato do Cliente"]: dadosAtualCard.obs_cham,
    ...(dadosAtualCard.observacoes_atendimento
      ? {
          ["Observações"]: dadosAtualCard.observacoes_atendimento,
        }
      : {}),
    ...(dadosAtualCard.nome_problema_n_resolvido
      ? {
          ["Problema Não Resolvido"]: dadosAtualCard.nome_problema_n_resolvido,
        }
      : {}),
    ...(dadosAtualCard.coletaRef_cham
      ? {
          ["Nº do Negócio Gerado"]: dadosAtualCard.coletaRef_cham,
        }
      : {}),
    ...(dadosAtualCard?.componentesKit?.filter(
      (item: any) => item?.tipo_item == "9"
    )?.length > 0
      ? {
          ["Módulos"]: (
            <div className="flex flex-col gap-1">
              {dadosAtualCard?.componentesKit
                ?.filter((item: any) => item?.tipo_item == "9")
                ?.map((item: any, index_item: number) => (
                  <div
                    className="flex flex-row justify-between fieldset border p-1 rounded"
                    key={index_item}
                  >
                    <div>
                      <div className="font-bold">
                        Potência:{" "}
                        {FormatFields.formatarNumero(item?.potencia_item)}W
                      </div>
                      <div className="font-bold">Qtd: {item?.qtd}</div>
                    </div>
                  </div>
                ))}
            </div>
          ),
        }
      : {}),
    ...(dadosAtualCard?.componentesKit?.filter(
      (item: any) => item?.tipo_item == "8"
    )?.length > 0
      ? {
          ["Inversores"]: (
            <div className="flex flex-col gap-1">
              {dadosAtualCard?.componentesKit
                ?.filter((item: any) => item?.tipo_item == "8")
                ?.map((item: any, index_item: number) => (
                  <div
                    className="flex flex-col justify-between fieldset border p-1 rounded"
                    key={index_item}
                  >
                    <div className="font-bold">{item?.descricao}</div>
                    <div className="font-bold whitespace-nowrap">
                      Qtd: {item?.qtd}
                    </div>
                  </div>
                ))}
            </div>
          ),
        }
      : {}),
  };

  return (
    <div className="flex flex-col min-h-[400px] gap-4">
      <div className="flex flex-row-reverse">
        <div
          className={`px-3 py-1 text-white w-fit font-bold flex flex-col items-center justify-center rounded-lg`}
          style={{
            backgroundColor: `hsl(${0 + ((240 - 0) * (Math.min(Math.max(dadosAtualCard.dias_prioridade, 1), 14) - 1)) / (14 - 1)}, 100%, 50%)`,
            textShadow: "0px 0px 2px black",
          }}
        >
          Prioridade {dadosAtualCard.nome_prioridade}
        </div>
      </div>
      <div className="flex flex-col w-full gap-3">
        <div className="flex flex-row gap-3 text-xl font-semibold mx-auto pb-2">
          <button
            className={`${abaSelecionada == "Dados Gerais" ? "bg-primary text-white" : "text-body"} px-4 py-1 rounded-3xl`}
            onClick={() => {
              setAbaSelecionada("Dados Gerais");
            }}
          >
            Dados Gerais
          </button>
          <button
            className={`${abaSelecionada == "Anexos" ? "bg-primary text-white" : "text-body"} px-4 py-1 rounded-3xl`}
            onClick={() => {
              setAbaSelecionada("Anexos");
            }}
          >
            Anexos
          </button>
        </div>

        <div
          className={`mx-auto flex flex-col w-80 overflow-auto ${abaSelecionada != "Dados Gerais" && "hidden"}`}
        >
          {/* <div className="text-black-2 text-lg font-semibold">Informações</div> */}
          <div className="text-black font-medium flex flex-col gap-2 ">
            {Object.keys(dadosRenderizados).map((info, index) => (
              <div key={index} className="flex flex-row gap-2 justify-between">
                <div className="font-medium">{info}</div>
                <div className="text-right font-semibold">
                  {dadosRenderizados[info]}
                </div>
              </div>
            ))}
            {/* <div>
              <div>Usuario Responsável:</div>
              <div>{dadosAtualCard.nome_usuario}</div>
            </div>
            <div>
              <div>Cliente:</div>
              <div>{dadosAtualCard.nome_usuario}</div>
            </div>
            <div>
              <div>Tipo de Atendimento: </div>
              <div>{dadosAtualCard.tipo_cham_formatado}</div>
            </div>
            <div>
              <div></div>
              <div></div>
              Núemro do Chamado: {dadosAtualCard.id_cham}
            </div>
            <div>
              <div></div>
              <div></div>
              Loja: {dadosAtualCard.nome_loja}
            </div>
            <div>
              <div></div>
              <div></div>
              Negócio:{" "}
              {dadosAtualCard.nome_negocio_coleta == null
                ? "Sem Negócio"
                : dadosAtualCard.nome_negocio_coleta}
            </div>
            <div>
              <div>Prioridade:</div>
              <div>{dadosAtualCard.nome_prioridade}</div>
            </div>
            {dadosAtualCard.observacoes_atendimento && (
              <div>
                <div> Observações: </div>
                <div>{dadosAtualCard.observacoes_atendimento}</div>
              </div>
            )}
            {dadosAtualCard.nome_problema_n_resolvido && (
              <div>
                <div>Problema Não Resolvido :</div>
                <div>{dadosAtualCard.nome_problema_n_resolvido}</div>
              </div>
            )}
            {dadosAtualCard.coletaRef_cham && (
              <div>
                <div>Nº do Negócio Gerado:</div>
                <div>{dadosAtualCard.coletaRef_cham}</div>
              </div>
            )}
            <div>
              <div> Relato do Cliente: </div>
              <div>{dadosAtualCard.obs_cham}</div>
            </div> */}

            {/* <div>
            Loja:{" "}
            {dadosAtualCard.loja_demanda
              ? lojasOptions.find(
                  (e: any) => e.id_loja == dadosAtualCard.loja_demanda
                )?.nome_loja
              : "Sem Loja"}
          </div> */}
            {/* {dadosAtualCard.anexo_atendimento && (
            <>
              <div> Anexo Atendimento:</div>
              <img src={anexoAtendimento} alt="Imagem Atendimento" />
            </>
          )} */}
          </div>
        </div>

        <div
          className={`flex flex-col overflow-auto ${abaSelecionada != "Anexos" && "hidden"}`}
        >
          <div className="flex flex-col gap-1 max-h-[400px] overflow-auto">
            <div className="flex flex-row justify-between">
              <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-primary hover:brightness-90 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>
              <Button
                onClick={() => {
                  setIsLoading(true);
                  editarAtendimento({
                    id_cham: dadosAtualCard.id_cham,
                    cod_cliente_cham: dadosAtualCard.cod_cliente_cham,
                    anexos,
                  })
                    .then(() => reListarDemandas())
                    .finally(() => setIsLoading(false));
                }}
                loading={isLoading}
              >
                Salvar Anexos
              </Button>
            </div>
            {isLoadingAnexos ? (
              <div className="flex justify-center items-center">
                <LoaderSun height={100} />
              </div>
            ) : imageUrls.length > 0 ? (
              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 className="flex flex-col text-lg font-bold items-center justify-center h-[200px]">
                <div className="p-10 px-20 bg-black-2/5">Não há Anexos</div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
