import LoaderSun from "@/components/common/Loader/LoaderSun";
import FileRenderer from "@/components/FileRenderer";
import Button from "@/components/Forms/Button";
import Input from "@/components/Forms/Input";
import InputGroup from "@/components/Forms/InputGroup";
import InputSelectComponent from "@/components/Forms/InputSelect";
import { baixarAwsBase64 } from "@/requests/common/Aws/baixarAws";
import { buscaCep } from "@/services/buscaCep";
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";
import Swal from "sweetalert2";

const FormFinanciador = ({
  onSubmitFunction,
  children,
  defaultValues,
  financiadores = [],
  ...rest
}: any) => {
  const [cnpj, setCnpj] = useState(
    defaultValues && defaultValues["tipoPessoa_financiador"] == "J"
      ? true
      : false,
  );
  const [dadosBanco1, setDadosBanco1] = useState<any>(false);
  const [dadosBanco2, setDadosBanco2] = useState<any>(false);
  const [imageUrls, setImageUrls] = useState<string[]>([]);
  const [anexos, setAnexos] = useState<File[]>(false || []);
  const [inputKey, setInputKey] = useState(1);
  const [isLoadingAnexos, setIsLoadingAnexos] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const { valuesSession } = useAuth();
  const { session } = valuesSession();
  const { handleSubmit, ...form } = GetForm();

  const { openGallery, setGallery } = GetGallery();

  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_financiador"]).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_financiador"].split("/").pop();
            const file = new File([blob], fileName, { type: blob.type });
            return file;
          }),
        ),
      )
        .then((res) => {
          setAnexos(res);
        })
        .finally(() => setIsLoadingAnexos(false));
    }
  }, []);

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

  useEffect(() => {
    if (cnpj) {
      form.control.unregister(
        [
          "nome_financiador",
          "email_financiador",
          "cpfcnpj_financiador",
          "dataNascimento_financiador",
          "estadoCivil_financiador",
          "profissao_financiador",
          "telefone1_financiador",
          "telefone2_financiador",
          "flex",
          "cep_financiador",
          "rua_financiador",
          "nro_financiador",
          "bairro_financiador",
          "comp_financiador",
          "cidade_financiador",
          "estado_financiador",
        ] as never[],
        {
          keepDefaultValue: false,
          keepError: false,
        },
      );
    } else {
      form.control.unregister(
        [
          "nomeEmpresa_financiador",
          "nomeResponsavelFisico_financiador",
          "cpfResponsavel_financiador",
          "data_aberturaEmpresa_financiador",
          "cpfcnpj_financiador",
          "ie_financiador",
          "flex",
          "cepEmpresa_financiador",
          "logradouroEmpresa_financiador",
          "numeroEmpresa",
          "bairroEmpresa_financiador",
          "complementoEmpresa_financiador",
          "cidadeEmpresa_financiador",
          "ufEmpresa_financiador",
        ] as never[],
        {
          keepDefaultValue: false,
          keepError: false,
        },
      );
    }
    form.reload();
  }, [cnpj]);

  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 [cep, setCep] = useState<string>(
    defaultValues &&
      (defaultValues["cep_financiador"] ||
        defaultValues["cepEmpresa_financiador"]),
  );
  const [bairro, setBairro] = useState<string>(
    defaultValues &&
      (defaultValues["bairro_financiador"] ||
        defaultValues["bairroEmpresa_financiador"]),
  );
  const [logradouro, setLogradouro] = useState<string>(
    defaultValues &&
      (defaultValues["rua_financiador"] ||
        defaultValues["logradouroEmpresa_financiador"]),
  );
  const [estadoSelecionado, setEstadoSelecionado] = useState<string>(
    defaultValues &&
      (defaultValues["estado_financiador"] ||
        defaultValues["ufEmpresa_financiador"]),
  );
  const [cidadeSelecionada, setCidadeSelecionada] = useState<any>(
    defaultValues &&
      (defaultValues["cidade_financiador"] ||
        defaultValues["cidadeEmpresa_financiador"]),
  );
  const [loadingCep, setLoadingCep] = useState(false);

  const handleCEPChange = async (event: any) => {
    const cep = event;
    setCep(cep);

    if (cep && cep.length === 9) {
      setLoadingCep(true);

      const formataCep = cep.replace("-", "");
      const enderecoInfo = await buscaCep(formataCep);

      form.setValue("bairroEmpresa_financiador", enderecoInfo!.bairro);
      form.setValue("logradouroEmpresa_financiador", enderecoInfo!.rua);
      form.setValue("ufEmpresa_financiador", enderecoInfo!.estado);
      form.setValue("cidadeEmpresa_financiador", enderecoInfo!.cidade);

      form.setValue("bairro_financiador", enderecoInfo!.bairro);
      form.setValue("rua_financiador", enderecoInfo!.rua);
      form.setValue("estado_financiador", enderecoInfo!.estado);
      form.setValue("cidade_financiador", enderecoInfo!.cidade);
      setLoadingCep(false);

      setBairro(enderecoInfo!.bairro || "");
      setLogradouro(enderecoInfo!.rua || "");
      setCidadeSelecionada(enderecoInfo!.cidade);
      setEstadoSelecionado(enderecoInfo!.estado);
    }
  };

  async function onSubmitFormFinanciamento(data: any) {
    if (anexos.length < 1) {
      return Swal.fire({
        title: "Erro",
        icon: "error",
        text: "É obrigado informar documentos de identificação",
        confirmButtonText: "ok",
      });
    }
    if (data.tipoPessoa_financiador == "F") {
      const dateNasc = data.dataNascimento_financiador
        ? new Date(data.dataNascimento_financiador)
        : new Date();
      const dateAtual = new Date();

      let idade = dateAtual.getFullYear() - dateNasc.getFullYear();
      const mes = dateAtual.getMonth() - dateNasc.getMonth();

      if (mes < 0 || (mes === 0 && dateAtual.getDate() < dateNasc.getDate())) {
        idade--;
      }
      if (idade < 18) {
        return Swal.fire({
          title: "A idade deve não pode ser menor que 18 anos!",
          icon: "error",
          html: "Falha ao validar a idade",
        });
      }
    }
    setIsLoading(true);
    return onSubmitFunction({ ...data, anexos }).finally(() =>
      setIsLoading(false),
    );
  }

  return (
    <form
      onSubmit={handleSubmit(onSubmitFormFinanciamento)}
      key={form.key}
      {...rest}
      className="p-5 g-5"
    >
      <div
        className={`relative border-[1px]  m-3 border-stroke border-opacity-100 rounded-md p-8`}
      >
        <span
          className={`absolute top-0 left-0 transform translate-x-[20%] text-black -translate-y-1/2 px-1 bg-white dark:bg-boxdark text-2xl `}
        >
          <strong>Dados Gerais</strong>
        </span>
        <InputGroup className="flex justify-center items-center">
          <InputSelectComponent
            formulario={form}
            label="Tipo"
            width="xl:w-1/3"
            name="tipoPessoa_financiador"
            options={[
              { value: "F", label: "Física" },
              { value: "J", label: "Jurídica" },
            ]}
            skipEffect
            onChange={(e: any) => {
              const juridica = e.value == "J";

              const formData = { ...form?.control?._formValues };
              if (cnpj != juridica) {
                if (juridica) {
                  form.setValue(
                    "cepEmpresa_financiador",
                    formData["cep_financiador"],
                  );
                  form.setValue(
                    "logradouroEmpresa_financiador",
                    formData["rua_financiador"],
                  );
                  form.setValue("numeroEmpresa", formData["nro_financiador"]);
                  form.setValue(
                    "bairroEmpresa_financiador",
                    formData["bairro_financiador"],
                  );
                  form.setValue(
                    "complementoEmpresa_financiador",
                    formData["comp_financiador"],
                  );
                  form.setValue(
                    "cidadeEmpresa_financiador",
                    formData["cidade_financiador"],
                  );
                  form.setValue(
                    "ufEmpresa_financiador",
                    formData["estado_financiador"],
                  );

                  // form.control.unregister(
                  //   [
                  //     "nome_financiador",
                  //     "email_financiador",
                  //     "cpfcnpj_financiador",
                  //     "dataNascimento_financiador",
                  //     "estadoCivil_financiador",
                  //     "profissao_financiador",
                  //     "telefone1_financiador",
                  //     "telefone2_financiador",
                  //     "flex",
                  //     "cep_financiador",
                  //     "rua_financiador",
                  //     "nro_financiador",
                  //     "bairro_financiador",
                  //     "comp_financiador",
                  //     "cidade_financiador",
                  //     "estado_financiador",
                  //   ] as never[],
                  //   {
                  //     keepDefaultValue: false,
                  //     keepError: false,
                  //   },
                  // );

                  // form.setYupSchema((prev) => {
                  //   const fields: any = prev.fields;
                  //   [
                  //     "nome_financiador",
                  //     "email_financiador",
                  //     "cpfcnpj_financiador",
                  //     "dataNascimento_financiador",
                  //     "estadoCivil_financiador",
                  //     "profissao_financiador",
                  //     "telefone1_financiador",
                  //     "telefone2_financiador",
                  //     "flex",
                  //     "cep_financiador",
                  //     "rua_financiador",
                  //     "nro_financiador",
                  //     "bairro_financiador",
                  //     "comp_financiador",
                  //     "cidade_financiador",
                  //     "estado_financiador",
                  //   ].map((field) => {
                  //     delete fields[field];
                  //   });
                  //   prev.fields = fields;
                  //   return prev;
                  // });
                } else {
                  form.setValue(
                    "cep_financiador",
                    formData["cepEmpresa_financiador"],
                  );
                  form.setValue(
                    "rua_financiador",
                    formData["logradouroEmpresa_financiador"],
                  );
                  form.setValue("nro_financiador", formData["numeroEmpresa"]);
                  form.setValue(
                    "bairro_financiador",
                    formData["bairroEmpresa_financiador"],
                  );
                  form.setValue(
                    "comp_financiador",
                    formData["complementoEmpresa_financiador"],
                  );
                  form.setValue(
                    "cidade_financiador",
                    formData["cidadeEmpresa_financiador"],
                  );
                  form.setValue(
                    "estado_financiador",
                    formData["ufEmpresa_financiador"],
                  );

                  // form.control.unregister(
                  //   [
                  //     "nomeEmpresa_financiador",
                  //     "nomeResponsavelFisico_financiador",
                  //     "cpfResponsavel_financiador",
                  //     "data_aberturaEmpresa_financiador",
                  //     "cpfcnpj_financiador",
                  //     "ie_financiador",
                  //     "flex",
                  //     "cepEmpresa_financiador",
                  //     "logradouroEmpresa_financiador",
                  //     "numeroEmpresa",
                  //     "bairroEmpresa_financiador",
                  //     "complementoEmpresa_financiador",
                  //     "cidadeEmpresa_financiador",
                  //     "ufEmpresa_financiador",
                  //   ] as never[],
                  //   {
                  //     keepDefaultValue: false,
                  //     keepError: false,
                  //   },
                  // );

                  // form.setYupSchema((prev) => {
                  //   const fields: any = prev.fields;
                  //   [
                  //     "nomeEmpresa_financiador",
                  //     "nomeResponsavelFisico_financiador",
                  //     "cpfResponsavel_financiador",
                  //     "data_aberturaEmpresa_financiador",
                  //     "cpfcnpj_financiador",
                  //     "ie_financiador",
                  //     "flex",
                  //     "cepEmpresa_financiador",
                  //     "logradouroEmpresa_financiador",
                  //     "numeroEmpresa",
                  //     "bairroEmpresa_financiador",
                  //     "complementoEmpresa_financiador",
                  //     "cidadeEmpresa_financiador",
                  //     "ufEmpresa_financiador",
                  //   ].map((field) => {
                  //     delete fields[field];
                  //   });
                  //   prev.fields = fields;
                  //   return prev;
                  // });
                }

                form.setValue("cpfcnpj_financiador" as never, "" as never);
                setCnpj(juridica);
              }
            }}
            defaultValue={
              (defaultValues && defaultValues["tipoPessoa_financiador"]) || "F"
            }
          />
        </InputGroup>
        <div>
          <div>Documentos de identificaçã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>
                      <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>
        {cnpj && (
          <>
            <InputGroup>
              <Input
                formulario={form}
                label="Razão Social"
                name="nomeEmpresa_financiador"
                type="text"
                defaultValue={
                  defaultValues && defaultValues["nomeEmpresa_financiador"]
                }
                required
                error="Informe a Razão Social"
                dynamic
              />
              <Input
                formulario={form}
                label="Nome Responsável Legal"
                name="nomeResponsavelFisico_financiador"
                defaultValue={
                  defaultValues &&
                  defaultValues["nomeResponsavelFisico_financiador"]
                }
                required
                error="Informe o Nome do Responsável Legal"
                dynamic
              />
              <Input
                formulario={form}
                label="CPF Responsável Legal"
                name="cpfResponsavel_financiador"
                mascara="cpf"
                defaultValue={
                  defaultValues && defaultValues["cpfResponsavel_financiador"]
                }
                required
                error="Informe o CPF"
                dynamic
              />
              <Input
                formulario={form}
                label="Data Abertura"
                name="data_aberturaEmpresa_financiador"
                type="date"
                defaultValue={
                  defaultValues &&
                  defaultValues["data_aberturaEmpresa_financiador"]
                }
              />
              <Input
                formulario={form}
                label="CNPJ"
                name="cpfcnpj_financiador"
                mascara="cnpj"
                type="text"
                defaultValue={
                  defaultValues && defaultValues["cpfcnpj_financiador"]
                }
                required
                error="Informe o CNPJ"
                dynamic
              />
              <Input
                formulario={form}
                label="IE"
                name="ie_financiador"
                type="text"
                defaultValue={defaultValues && defaultValues["ie_financiador"]}
              />
            </InputGroup>
            <hr />
            <span className="flex w-full justify-center items-center p-2 text-black text-[22px]">
              <strong>Dados Endereço</strong>
            </span>
            <InputGroup>
              <div className="w-full">
                {loadingCep && (
                  <span className="text-xs text-gray-500 mt-1 block">
                    Buscando endereço...
                  </span>
                )}

                <Input
                  formulario={form}
                  label="CEP"
                  name="cepEmpresa_financiador"
                  onChange={(e) => handleCEPChange(e.target.value)}
                  mascara="cep"
                  disabled={loadingCep}
                  type="text"
                  defaultValue={
                    defaultValues && defaultValues["cepEmpresa_financiador"]
                  }
                  required
                  error="Informe o CEP"
                  // dynamic
                />
              </div>
              <Input
                formulario={form}
                label="Logradouro"
                name="logradouroEmpresa_financiador"
                type="text"
                defaultValue={
                  defaultValues &&
                  defaultValues["logradouroEmpresa_financiador"]
                }
                required
                error="Informe o Logradouro"
                disabled={cep != "" && cep != "0" && logradouro != ""}
                // dynamic
              />
              <Input
                formulario={form}
                label="Número"
                name="numeroEmpresa"
                type="text"
                defaultValue={defaultValues && defaultValues["numeroEmpresa"]}
                required
                error="Informe o Número do endereço"
                // dynamic
              />
            </InputGroup>
            <InputGroup>
              <Input
                formulario={form}
                label="Bairro"
                name="bairroEmpresa_financiador"
                type="text"
                defaultValue={
                  defaultValues && defaultValues["bairroEmpresa_financiador"]
                }
                required
                error="Informe o Bairro"
                disabled={cep != "" && cep != "0" && bairro != ""}
                // dynamic
              />
              <Input
                formulario={form}
                label="Complemento"
                name="complementoEmpresa_financiador"
                type="text"
                defaultValue={
                  defaultValues &&
                  defaultValues["complementoEmpresa_financiador"]
                }
              />
              <Input
                formulario={form}
                label="Cidade"
                name="cidadeEmpresa_financiador"
                type="text"
                defaultValue={
                  defaultValues && defaultValues["cidadeEmpresa_financiador"]
                }
                required
                error="Informe a Cidade"
                disabled={cep != "" && cep != "0" && cidadeSelecionada != ""}
                // dynamic
              />
              <Input
                formulario={form}
                label="UF"
                name="ufEmpresa_financiador"
                type="text"
                defaultValue={
                  defaultValues && defaultValues["ufEmpresa_financiador"]
                }
                disabled={cep != "" && cep != "0" && estadoSelecionado != ""}
                required
                error="Informe a UF"
                // dynamic
              />
            </InputGroup>
          </>
        )}

        {!cnpj && (
          <>
            <InputGroup>
              <Input
                formulario={form}
                label="Nome Financiador"
                name="nome_financiador"
                type="text"
                mascara="letras"
                required
                dynamic
                error={"Preencha o nome!"}
                defaultValue={
                  defaultValues && defaultValues["nome_financiador"]
                }
              />
              <Input
                formulario={form}
                label="E-mail"
                name="email_financiador"
                type="email"
                // required
                dynamic
                error={"Preencha o E-mail!"}
                autoComplete="off"
                defaultValue={
                  defaultValues && defaultValues["email_financiador"]
                }
              />
              <Input
                formulario={form}
                label="CPF"
                mascara="cpf"
                name="cpfcnpj_financiador"
                type="text"
                defaultValue={
                  defaultValues && defaultValues["cpfcnpj_financiador"]
                }
                required
                error="Informe o CPF"
                dynamic
              />
            </InputGroup>
            <InputGroup>
              <Input
                formulario={form}
                label="Data Nascimento"
                name="dataNascimento_financiador"
                type="date"
                defaultValue={
                  defaultValues && defaultValues["dataNascimento_financiador"]
                }
              />
              <InputSelectComponent
                formulario={form}
                label="Estado Civil"
                name="estadoCivil_financiador"
                options={[
                  { value: "Solteiro", label: "Solteiro" },
                  { value: "Casado", label: "Casado" },
                  { value: "Divorciado", label: "Divorciado" },
                  { value: "Viúvo", label: "Viúvo" },
                ]}
                defaultValue={
                  defaultValues && defaultValues["estadoCivil_financiador"]
                }
              />
              <Input
                formulario={form}
                label="Profissão"
                name="profissao_financiador"
                type="text"
                defaultValue={
                  defaultValues && defaultValues["profissao_financiador"]
                }
              />
            </InputGroup>
            <InputGroup>
              <Input
                formulario={form}
                label="Celular 1"
                mascara="telefone"
                name="telefone1_financiador"
                type="text"
                defaultValue={
                  defaultValues && defaultValues["telefone1_financiador"]
                }
              />
              <Input
                formulario={form}
                mascara="telefone"
                label="Celular 2"
                name="telefone2_financiador"
                type="text"
                defaultValue={
                  defaultValues && defaultValues["telefone2_financiador"]
                }
              />
            </InputGroup>
            <hr />
            <span className="flex w-full justify-center items-center p-2 text-black text-[22px]">
              <strong>Dados Endereço</strong>
            </span>
            <InputGroup>
              <div className="w-full">
                {loadingCep && (
                  <span className="text-xs text-gray-500 mt-1 block">
                    Buscando endereço...
                  </span>
                )}

                <Input
                  formulario={form}
                  label="CEP"
                  name="cep_financiador"
                  onChange={(e) => handleCEPChange(e.target.value)}
                  mascara="cep"
                  disabled={loadingCep}
                  type="text"
                  defaultValue={
                    defaultValues && defaultValues["cep_financiador"]
                  }
                  required
                  error="Informe o CEP"
                  // dynamic
                />
              </div>
              <Input
                formulario={form}
                label="Logradouro"
                name="rua_financiador"
                type="text"
                defaultValue={defaultValues && defaultValues["rua_financiador"]}
                required
                error="Informe o Logradouro"
                disabled={cep != "" && cep != "0" && logradouro != ""}
                // dynamic
              />
              <Input
                formulario={form}
                label="Número"
                name="nro_financiador"
                type="text"
                defaultValue={defaultValues && defaultValues["nro_financiador"]}
                required
                error="Informe o Número do endereço"
                // dynamic
              />
            </InputGroup>
            <InputGroup>
              <Input
                formulario={form}
                label="Bairro"
                name="bairro_financiador"
                type="text"
                defaultValue={
                  defaultValues && defaultValues["bairro_financiador"]
                }
                required
                error="Informe o Bairro"
                disabled={cep != "" && cep != "0" && bairro != ""}
                // dynamic
              />
              <Input
                formulario={form}
                label="Complemento"
                name="comp_financiador"
                type="text"
                defaultValue={
                  defaultValues && defaultValues["comp_financiador"]
                }
              />
              <Input
                formulario={form}
                label="Cidade"
                name="cidade_financiador"
                type="text"
                defaultValue={
                  defaultValues && defaultValues["cidade_financiador"]
                }
                required
                error="Informe a cidade"
                disabled={cep != "" && cep != "0" && cidadeSelecionada != ""}
                // dynamic
              />
              <Input
                formulario={form}
                label="UF"
                name="estado_financiador"
                type="text"
                defaultValue={
                  defaultValues && defaultValues["estado_financiador"]
                }
                required
                disabled={cep != "" && cep != "0" && estadoSelecionado != ""}
                error="Informe a UF"
                // dynamic
              />
            </InputGroup>
          </>
        )}
      </div>

      <div
        className={`relative border-[1px]  m-3 border-stroke border-opacity-100 rounded-md p-8 mt-6`}
      >
        <span
          className={`absolute top-0 left-0 transform translate-x-[20%] text-black -translate-y-1/2 px-1 bg-white dark:bg-boxdark text-2xl `}
        >
          <strong>Dados Financeiros</strong>
        </span>
        <div className="flex flex-row justify-center items-center -mx-3 mb-6 gap-5">
          <Input
            formulario={form}
            label="Valor do Patrimônio"
            width={"xl:w-1/3"}
            mascara="numero"
            name="patrimonio_financiador"
            type="text"
            defaultValue={
              defaultValues && defaultValues["patrimonio_financiador"]
            }
          />

          <Input
            formulario={form}
            width={"xl:w-1/3"}
            label="Renda Mensal"
            mascara="numero"
            name="renda_financiador"
            type="text"
            defaultValue={defaultValues && defaultValues["renda_financiador"]}
          />
        </div>

        <div className="text-center w-full text-lg font-bold mb-4 text-black-2">
          <h1>Instituição Financeira 1</h1>
        </div>
        <div className="flex flex-wrap -mx-3 mb-6">
          <div className="w-full md:w-1/3 px-3 mb-6 md:mb-0">
            <Input
              formulario={form}
              label="Nome da Instituição Financeira"
              name="nome_banco1_financiador"
              type="text"
              onChange={(e) =>
                e.target.value != ""
                  ? setDadosBanco1(true)
                  : setDadosBanco1(false)
              }
              defaultValue={
                defaultValues && defaultValues["nome_banco1_financiador"]
              }
              required={dadosBanco1}
              error="Preencha o Nome da Instituição Financeira!"
            />
          </div>
          <div className="w-full md:w-1/3 px-3 mb-6 md:mb-0">
            <Input
              formulario={form}
              label="Agência"
              name="agencia_banco1_financiador"
              type="text"
              defaultValue={
                defaultValues && defaultValues["agencia_banco1_financiador"]
              }
              required={dadosBanco1}
              error="Preencha a Agência!"
              disabled={!dadosBanco1}
            />
          </div>
          <div className="w-full md:w-1/3 px-3">
            <Input
              formulario={form}
              label="Conta"
              name="conta_banco1_financiador"
              type="text"
              defaultValue={
                defaultValues && defaultValues["conta_banco1_financiador"]
              }
              required={dadosBanco1}
              error="Preencha a Conta!"
              disabled={!dadosBanco1}
            />
          </div>
        </div>

        <div className="text-center w-full text-lg font-bold mb-4 text-black-2">
          <h1>Instituição Financeira 2</h1>
        </div>
        <div className="flex flex-wrap -mx-3 mb-6">
          <div className="w-full md:w-1/3 px-3 mb-6 md:mb-0">
            <Input
              formulario={form}
              label="Nome da Instituição Financeira"
              name="nome_banco2_financiador_financiador"
              onChange={(e) => setDadosBanco2(true)}
              type="text"
              defaultValue={
                defaultValues &&
                defaultValues["nome_banco2_financiador_financiador"]
              }
              required={dadosBanco2}
            />
          </div>
          <div className="w-full md:w-1/3 px-3 mb-6 md:mb-0">
            <Input
              formulario={form}
              label="Agência"
              name="agencia_banco2_financiador"
              type="text"
              defaultValue={
                defaultValues && defaultValues["agencia_banco2_financiador"]
              }
              required={dadosBanco2}
              disabled={!dadosBanco2}
            />
          </div>
          <div className="w-full md:w-1/3 px-3">
            <Input
              formulario={form}
              label="Conta"
              name="conta_banco2_financiador"
              type="text"
              defaultValue={
                defaultValues && defaultValues["conta_banco2_financiador"]
              }
              required={dadosBanco2}
              disabled={!dadosBanco2}
            />
          </div>
        </div>
      </div>
      {children ? (
        children
      ) : (
        <div className="flex w-full justify-end sticky left-[100%] bottom-0 p-2 bg-white dark:bg-black">
          <Button
            loading={isLoading}
            className=" bg-success rounded-md"
          >
            Salvar
          </Button>
        </div>
      )}
      {/* {financiadores?.length === 0 && (
        <div className="flex justify-center items-center">
          <p className="text-center text-lg font-bold text-black-2">
            Não há financiadores cadastrados.
          </p>
        </div>
      )} */}
    </form>
  );
};

export default FormFinanciador;
