import LoaderSun from "@/components/common/Loader/LoaderSun";
import Button from "@/components/Forms/Button";
import { salvarCustosDoServico } from "@/requests/CRM/PosvOrdensServico/salvarCustosDoServico";
import { addConclusaoPendencia } from "@/requests/CRUD/ConclusaoPendencia/conclusaoPendencia";
import { obterLoja } from "@/requests/CRUD/Lojas/obterLoja";
import { listarMotivosReagendamento } from "@/requests/CRUD/MotivosReagendamento/listarMotivosReagendamento";
import { listarUsuarios } from "@/requests/CRUD/Usuario/listarUsuarios";
import { GetForm } from "@/utils";
import { useEffect, useState } from "react";
import FieldsCustosServicoOSInstalador from "./FieldsCustosServicoOSInstalador";

const FormCustosOS = ({
  ordemServico,
  defaultValues,
  dadosCard,
  dadosCliente,
  usuario,
  setActiveStepAtual,
  setOpenModalCustosOrdemServico,
  atualizarOrdensServico,
  isDisabled,
  ...rest
}: {
  [x: string]: any;
}) => {
  const [motivosReagendamento, setMotivosReagendamento] = useState<any[]>([]);
  // const [anexos, setAnexos] = useState<File[]>(false || []);
  const [imageUrls, setImageUrls] = useState<string[]>([]);
  const [isLoadingAnexos, setIsLoadingAnexos] = useState(false);
  const [inputKey, setInputKey] = useState(1);
  // const [valorServico_execucao_servico, setValorServico_execucao_servico] =
  //   useState(ordemServico?.valorTerceiroAbertura_pvos);
  // const [qtdKm_execucao_servico, setQtdKm_execucao_servico] = useState<
  //   string | number
  // >(defaultValues?.qtdKm_execucao_servico || "0");
  // const [qtdHoras_execucao_servico, setQtdHoras_execucao_servico] = useState<
  //   string | number
  // >(defaultValues?.qtdHoras_execucao_servico || "0");

  const [isLoading, setIsLoading] = useState(false);
  const [isLoaded, setIsLoaded] = useState(false);
  const [loja, setLoja] = useState<any>();
  const [usuarios, setUsuarios] = useState<any[]>([]);
  const [valorKm_execucao_servico, setValorKm] = useState<any>(0);
  const [valorHora_execucao_servico, valorHora] = useState<any>(0);

  useEffect(() => {
    const instalador = usuarios?.find(
      (u) => u?.id_usuario == ordemServico?.codExecutor_pvos,
    );
    setValorKm(instalador?.valor_km_usuario || loja?.valor_km_loja || 0);
    valorHora(
      instalador?.valor_hora_adicional_usuario ||
        loja?.valor_hora_adicional_loja ||
        0,
    );
  }, [usuarios, loja]);

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

  // useEffect(() => {
  //   form?.setValue(
  //     "valor_execucao_servico",
  //     FormatFields.formatarNumero(
  //       Number(valorServico_execucao_servico) +
  //         Number(qtdKm_execucao_servico) * (Number(loja?.valor_km_loja) || 0) +
  //         Number(qtdHoras_execucao_servico) *
  //           (Number(loja?.valor_hora_adicional_loja) || 0)
  //     )
  //   );
  //   form?.setValue(
  //     "valorTotalKm_execucao_servico",
  //     String(
  //       Number(qtdKm_execucao_servico) * (Number(loja?.valor_km_loja) || 0)
  //     )
  //   );
  //   form?.setValue(
  //     "valorTotalHora_execucao_servico",
  //     String(
  //       Number(qtdHoras_execucao_servico) *
  //         (Number(loja?.valor_hora_adicional_loja) || 0)
  //     )
  //   );
  // }, [
  //   valorServico_execucao_servico,
  //   qtdKm_execucao_servico,
  //   qtdHoras_execucao_servico,
  // ]);

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

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

  //     //   return newItens;
  //     // });
  //   };

  //   loadImages();
  // }, [anexos]);

  useEffect(() => {
    Promise.all([
      listarMotivosReagendamento().then(setMotivosReagendamento),
      obterLoja({ id_loja: dadosCard?.id_loja_coleta }).then(setLoja),
      listarUsuarios().then(setUsuarios),
      // (async () => {
      //   if (defaultValues && defaultValues["anexos_data"]) {
      //     const anexos_data = defaultValues["anexos_data"];

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

  async function onSubmitFormCustosOS(data: any) {
    const newData = {
      ...data,
      userCustos_execucao_servico: usuario?.id_usuario,
      OsAtrasada_execucao_servico:
        new Date(ordemServico?.dataConclusao_execucao_servico) >
        new Date(ordemServico?.datafinal_servico_pvos)
          ? "1"
          : "0",
      statusCustos_execucao_servico: "1",
      valorKm_execucao_servico: valorKm_execucao_servico,
      valorHora_execucao_servico: valorHora_execucao_servico,
      // anexos,
      caminhos_anexos: data?.anexos?.map((anexo: File) => ({
        cod_os_pvos: ordemServico?.id_pvos,
        caminho_arq_pvos: `clientes/${dadosCliente?.pasta_cliente}/${dadosCard?.id_coleta_cliente}/OrdensServico/anexosCustosInstalador/${anexo.name}`,
        nome_arq_pvos: anexo.name,
        tipoAnexo_os_pvos: "2",
      })),
      id_execucao_servico: ordemServico?.id_execucao_servico,
      os_execucao_servico: ordemServico?.os_execucao_servico,
      coleta_execucao_servico: ordemServico?.coleta_execucao_servico,
      id_card: dadosCard?.id,
    };
    setIsLoading(true);
    return salvarCustosDoServico(newData)
      .then(() => {
        return Promise.all([
          atualizarOrdensServico(),
          addConclusaoPendencia({
            id_coleta: dadosCard.id_coleta_cliente,
            id_etapa: dadosCard.id_lista,
            id_pendencia: "30",
          }),
        ]).then(() => {
          setActiveStepAtual((prev: any) => prev + 1);
        });
      })
      .then(() => {
        setOpenModalCustosOrdemServico(false);
      })
      .finally(() => {
        setIsLoading(false);
      });
  }

  return isLoaded ? (
    <div className="flex flex-row flex-wrap gap-4">
      <FieldsCustosServicoOSInstalador
        form={form}
        defaultValues={defaultValues}
        isDisabled={isDisabled}
        ordemServico={ordemServico}
        loja={loja}
        motivosReagendamento={motivosReagendamento}
        instalador={usuarios?.find(
          (u) => u?.id_usuario == ordemServico?.codExecutor_pvos,
        )}
        valorKm={valorKm_execucao_servico}
        valorHora={valorHora_execucao_servico}
      />
      {/* {ordemServico?.codExecutor_pvos != "0" && (
        <>
          <Input
            name="valorServico_execucao_servico "
            label="Valor do Serviço"
            formulario={form}
            mascara="numero"
            prefix={"R$"}
            defaultValue={
              defaultValues?.valorServico_execucao_servico ||
              ordemServico?.valorTerceiroAbertura_pvos
            }
            width={"flex-1"}
            onChange={(e) =>
              setValorServico_execucao_servico(
                FormatFields?.desformatarNumeros(e?.target?.value)
              )
            }
            disabled={isDisabled}
          />
          <Input
            name="qtdKm_execucao_servico"
            label="Quilometragem (km)"
            formulario={form}
            mascara="numero"
            defaultValue={defaultValues?.qtdKm_execucao_servico || "0"}
            width={"flex-1"}
            onChange={(e) =>
              setQtdKm_execucao_servico(
                FormatFields?.desformatarNumeros(e?.target?.value)
              )
            }
            disabled={isDisabled}
          />
          <Input
            name="qtdHoras_execucao_servico"
            label="Horas Adicionais"
            formulario={form}
            mascara="numero"
            defaultValue={defaultValues?.qtdHoras_execucao_servico || "0"}
            width={"flex-1"}
            onChange={(e) =>
              setQtdHoras_execucao_servico(
                FormatFields?.desformatarNumeros(e?.target?.value)
              )
            }
            disabled={isDisabled}
          />
          <Input
            name="valor_execucao_servico"
            label="Valor Total"
            formulario={form}
            mascara="numero"
            prefix={"R$"}
            width={"flex-1"}
            disabled
            defaultValue={defaultValues?.valor_execucao_servico}
          />
        </>
      )}
      <Input
        name="obsCustos_execucao_servico"
        label="Observações"
        formulario={form}
        type="textarea"
        defaultValue={
          (defaultValues && defaultValues?.obsCustos_execucao_servico) ||
          (ordemServico?.codExecutor_pvos == "0"
            ? "Pendência Concluída Automaticamente pois o instalador é interno"
            : "")
        }
        disabled={isDisabled}
      />
      {new Date(ordemServico?.dataConclusao_execucao_servico) >
        new Date(ordemServico?.datafinal_servico_pvos) && (
        <div className="w-full border-2 border-orange-500 bg-orange-500/[0.04] rounded p-2 flex flex-col gap-2">
          <div className="font-medium">
            A data informada na baixa indicou um atraso, informe o motivo e
            descição
          </div>
          <div className="flex flex-row flex-wrap gap-4">
            <InputSelectComponent
              name="motivoAtraso_execucao_servico"
              label="Motivo do Reagendamento"
              options={motivosReagendamento
                ?.filter((motivo) => motivo?.status_motivo_reagendamento == "1")
                ?.map((motivo) => ({
                  value: motivo?.id_motivo_reagendamento,
                  label: motivo?.motivo_reagendamento,
                }))}
              formulario={form}
              width={"flex-1"}
              defaultValue={defaultValues?.motivoAtraso_execucao_servico}
              disabled={isDisabled}
            />
            <Input
              name="descricaoAtraso_execucao_servico"
              label="Descrição do atraso"
              formulario={form}
              width={"flex-1"}
              inputClassName="bg-[#fff]"
              defaultValue={defaultValues?.descricaoAtraso_execucao_servico}
              disabled={isDisabled}
            />
          </div>
        </div>
      )}
      <div className="w-full">
        <div>Anexos dos Custos do Serviço</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>
                    {!isDisabled && (
                      <button
                        type="button"
                        onClick={(e) => {
                          e.stopPropagation();
                          setAnexos((prev) => {
                            const newAnexos = [...prev];
                            newAnexos.splice(index, 1);
                            return newAnexos;
                          });
                        }}
                      >
                        <MdClose />
                      </button>
                    )}
                  </div>
                );
              })
            )}
          </div>
          {!isDisabled && (
            <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 Anexo
            </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> */}
      {!isDisabled && (
        <div className="w-full">
          <Button
            onClick={handleSubmit(onSubmitFormCustosOS)}
            loading={isLoading}
          >
            Salvar
          </Button>
        </div>
      )}
    </div>
  ) : (
    <div className="flex justify-center w-full">
      <LoaderSun />
    </div>
  );
};

export default FormCustosOS;
