import Button from "@/components/Forms/Button";
import { listarUsuario } from "@/requests/CRM/agenda";
import { cadastrarAtendimento } from "@/requests/CRUD/Atendimento/cadastrarAtendimento";
import {
  listarContatos,
  listarNegociosCliente,
} from "@/requests/CRUD/Cliente/listarClientes";
import { listarLojas } from "@/requests/CRUD/Lojas/listarLojas";
import { listarPrioridades } from "@/requests/CRUD/Prioridades/listarPrioridades";
import { listarDuvidas } from "@/requests/CRUD/TiposDuvida/listarDuvidas";
import { listarReclamacoes } from "@/requests/CRUD/TiposReclamacoes/listarReclamacoes";
import { useAuth } from "@/src/contexts/authContext";
import { useScreenContext } from "@/src/contexts/ScreenContext";
import { GetForm, GetGallery } from "@/utils";
import { useEffect, useState } from "react";
import { FieldValues } from "react-hook-form";
import { tipos_atendimentos } from "../CXESCAD066";
import FormAtendimento from "../CXESCAD066/FormAtendimento";

const FormNovoAtendimento = ({
  onSubmitFunction,
  defaultValues,
  disabledFields,
  children,
  setLoading,
  ...rest
}: any) => {
  const { valuesSession, usuario } = useAuth();
  const { session } = valuesSession();

  const [anexoBase64, setAnexoBase64] = useState<string>("");
  const [anexoFile, setAnexoFile] = useState<File | null | any>(null);
  const [usuariosOptions, setUsuariosOptions] = useState<any[]>([]);
  const [prioridadeOptions, setPrioridadeOptions] = useState<any[]>([]);
  const [tipoAtendimento, setTipoAtendimento] = useState<any>(
    defaultValues && defaultValues["tipo_atendimento"]
  );
  const [optionsCliente, setOptionsCliente] = useState<any[]>([]);
  const [negociosCliente, setNegociosCliente] = useState<any[]>([]);
  const [usuarioTipoAtendimento, setUsuarioTipoAtendimento] = useState("");
  const [clienteSelecionado, setClienteSelecionado] = useState(
    defaultValues && defaultValues["cliente_atendimento"]
  );
  const [prioridadeTipoAtendimento, setPrioridadeTipoAtendimento] =
    useState("");

  const [isLoading, setIsLoading] = useState(false);
  const [lojasOptions, setLojasOptions] = useState<any>([]);
  const [selectedLoja, setSelectedLoja] = useState<any>([]);

  const [tiposDuvida, setTiposDuvida] = useState<any[]>([]);
  const [tiposReclamacoes, setTiposReclamacoes] = useState<any[]>([]);

  // const [anexos, setAnexos] = useState<File[]>(false || []);
  const [imageUrls, setImageUrls] = useState<string[]>([]);
  const [isLoadingAnexos, setIsLoadingAnexos] = useState(false);
  const [inputKey, setInputKey] = useState(1);

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

  async function onSubmitAtendimento(data: FieldValues) {
    // data["id_usuario"] = session.id_usuario;
    data["autor_cham"] = usuario?.id_usuario;
    // data["anexos"] = anexos;

    setIsLoading(true);

    // const formData = new FormData();
    // Object.keys(data).forEach((key) => {
    //   formData.append(key, data[key]);
    // });

    // if (anexoFile) {
    //   formData.append("anexo_atendimento", anexoFile);
    // }

    return cadastrarAtendimento({ ...data })
      .then(() => {
        form.control._reset();
        setPrioridadeTipoAtendimento("");
        setUsuarioTipoAtendimento("");
        setClienteSelecionado("");
        // setAnexos([]);
        // setAnexoFile(null);
        // setAnexoBase64("");
        form.reload();
      })
      .finally(() => {
        setIsLoading(false);
      });
  }

  useEffect(() => {
    listarLojas(session.id_usuario).then((res) => {
      const idsLojaUsuario = session.id_loja_usuario
        .split(",")
        .map((id: any) => id.trim());

      const filtered = res.filter((loja: any) =>
        idsLojaUsuario.includes(loja.id_loja?.toString())
      );

      setLojasOptions(filtered);
    });
    if (clienteSelecionado) {
      listarNegociosCliente({
        cliente_coleta: clienteSelecionado,
      }).then((res) => setNegociosCliente(res));
    }
  }, [clienteSelecionado]);

  useEffect(() => {
    listarUsers();

    listarPrioridades().then((prioridades) => {
      const prioridadesComStatus1 = prioridades.filter(
        (prioridade: any) => prioridade.status_prioridade == 1
      );
      setPrioridadeOptions(prioridadesComStatus1);
    });
    listarContatos().then((e) => {
      const clienteStatus1 = e.filter(
        (filtro: any) => filtro.status_cliente == 1
      );
      setOptionsCliente(clienteStatus1);
    });
    setSelectedLoja([session.loja_padrao_usuario]);
    listarDuvidas().then((res) =>
      setTiposDuvida(res.filter((tipo: any) => tipo?.status_tipo_duvida == "1"))
    );
    listarReclamacoes().then((res) =>
      setTiposReclamacoes(
        res
          .filter((tipo: any) => tipo?.status_tipo_reclamacao == "1")
          .sort((a: any, b: any) =>
            a.nome_tipo_reclamacao.localeCompare(b.nome_tipo_reclamacao)
          )
      )
    );
  }, []);

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

  function listarUsers() {
    return listarUsuario().then((e) => setUsuariosOptions(e));
  }

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

  return (
    <FormAtendimento
      onSubmitFunction={onSubmitAtendimento}
      tipos_atendimentos={tipos_atendimentos}
      usuarios={usuariosOptions}
      prioridadeOptions={prioridadeOptions}
      optionsCliente={optionsCliente}
      tiposDuvida={tiposDuvida}
      tiposReclamacoes={tiposReclamacoes}
      lojasOptions={lojasOptions}
    >
      <div className="flex justify-end">
        <Button loading={isLoading}>Cadastrar</Button>
      </div>
    </FormAtendimento>
    // <form onSubmit={handleSubmit(onSubmitAtendimento)} key={form.key} {...rest}>
    //   <InputGroup>
    //     <InputSelectComponent
    //       label="Loja"
    //       name="loja_tarefa"
    //       formulario={form}
    //       options={lojasOptions.map((e: any) => ({
    //         label: `${e.nome_loja}`,
    //         value: `${e.id_loja}`,
    //       }))}
    //       onChange={(selectedOptions: any) => {
    //         setSelectedLoja([selectedOptions.value]);
    //       }}
    //       defaultValue={session.loja_padrao_usuario}
    //     />
    //     <InputSelectComponent
    //       name="cod_cliente_cham"
    //       label="Cliente"
    //       formulario={form}
    //       required
    //       error="Preencha o Cliente"
    //       options={optionsCliente
    //         .filter((cliente: any) =>
    //           selectedLoja?.some((loja: any) =>
    //             cliente.loja_cliente?.split(",").includes(loja)
    //           )
    //         )
    //         .map((e: any) => ({
    //           label: `${e.nome_cliente}`,
    //           value: `${e.id_cliente}`,
    //         }))}
    //       onChange={(e: any) => {
    //         setClienteSelecionado(e.value);
    //         form.setValue("cod_negocio_cham" as never, "" as never);
    //       }}
    //       skipEffect
    //     />
    //     <InputSelectComponent
    //       name="cod_negocio_cham"
    //       label="Negócio"
    //       formulario={form}
    //       options={[
    //         { value: "0", label: "Sem Negócio" },
    //         ...negociosCliente
    //           .filter((negocio) => negocio.tipoNegocio_coleta == "1")
    //           .map((e: any) => ({
    //             label: `${e.id_coleta} - ${e.nome_negocio_coleta}`,
    //             value: `${e.id_coleta}`,
    //           })),
    //       ]}
    //     />
    //   </InputGroup>
    //   <InputGroup>
    //     <InputSelectComponent
    //       name="tipo_cham"
    //       label="Tipo de Atendimento"
    //       formulario={form}
    //       required
    //       error="Informe o Tipo de Atendimento"
    //       options={[
    //         {
    //           label: `Dúvida`,
    //           value: `3`,
    //         },
    //         {
    //           label: `Reclamação`,
    //           value: `4`,
    //         },
    //       ]}
    //       defaultValue={defaultValues && defaultValues["tipo_cham"]}
    //       onChange={(e: any) => {
    //         setTipoAtendimento(e?.value);
    //         if (e?.value == "3") {
    //           form.control.unregister(["cod_tipo_reclamacao_cham"] as never[], {
    //             keepValue: false,
    //             keepError: false,
    //           });
    //         } else {
    //           form.control.unregister(["cod_tipo_duvida_cham"] as never[], {
    //             keepValue: false,
    //             keepError: false,
    //           });
    //         }

    //         form.reload();
    //       }}
    //     />
    //     {tipoAtendimento &&
    //       (tipoAtendimento == "3" ? (
    //         <InputSelectComponent
    //           name="cod_tipo_duvida_cham"
    //           label="Atendimento"
    //           formulario={form}
    //           options={tiposDuvida?.map((tipo) => ({
    //             ...tipo,
    //             label: tipo?.nome_tipo_duvida,
    //             value: tipo?.id_tipo_duvida,
    //           }))}
    //           required
    //           error={"Informe o Atendimento"}
    //           defaultValue={
    //             defaultValues && defaultValues["cod_tipo_duvida_cham"]
    //           }
    //           key={1}
    //           onChange={(e: any) => {
    //             form.setValue("titulo_tarefa", e?.label);

    //             const usuarioResponsavel = usuariosOptions?.find(
    //               (usuario) =>
    //                 usuario.id_usuario == e?.cod_responsavel_tipo_duvida
    //             );
    //             if (usuarioResponsavel) {
    //               form.setValue("responsavel_tarefa", {
    //                 label: usuarioResponsavel?.nome_usuario,
    //                 value: usuarioResponsavel?.id_usuario,
    //               });
    //             }
    //             const prioridade = prioridadeOptions?.find(
    //               (prioridade) =>
    //                 prioridade?.id_prioridade == e?.cod_prioridade_tipo_duvida
    //             );
    //             if (prioridade) {
    //               form.setValue("prioridade_cham", {
    //                 label: prioridade?.nome_prioridade,
    //                 value: prioridade?.id_prioridade,
    //               });
    //             }
    //           }}
    //         />
    //       ) : (
    //         <InputSelectComponent
    //           name="cod_tipo_reclamacao_cham"
    //           label="Atendimento"
    //           formulario={form}
    //           options={tiposReclamacoes?.map((tipo) => ({
    //             ...tipo,
    //             label: tipo?.nome_tipo_reclamacao,
    //             value: tipo?.id_tipo_reclamacao,
    //           }))}
    //           required
    //           error={"Informe o Atendimento"}
    //           defaultValue={
    //             defaultValues && defaultValues["cod_tipo_reclamacao_cham"]
    //           }
    //           key={2}
    //           onChange={(e: any) => {
    //             form.setValue("titulo_tarefa", e?.label);

    //             const usuarioResponsavel = usuariosOptions?.find(
    //               (usuario) =>
    //                 usuario.id_usuario == e?.cod_responsavel_reclamacao
    //             );
    //             if (usuarioResponsavel) {
    //               form.setValue("responsavel_tarefa", {
    //                 label: usuarioResponsavel?.nome_usuario,
    //                 value: usuarioResponsavel?.id_usuario,
    //               });
    //             }
    //             const prioridade = prioridadeOptions?.find(
    //               (prioridade) =>
    //                 prioridade?.id_prioridade == e?.cod_prioridade_reclamacao
    //             );
    //             if (prioridade) {
    //               form.setValue("prioridade_cham", {
    //                 label: prioridade?.nome_prioridade,
    //                 value: prioridade?.id_prioridade,
    //               });
    //             }
    //           }}
    //         />
    //       ))}
    //     <InputSelectComponent
    //       name="responsavel_tarefa"
    //       label="Responsável"
    //       formulario={form}
    //       required
    //       error="Preencha o Responsável"
    //       options={usuariosOptions
    //         .filter((usuario: any) =>
    //           selectedLoja?.some((loja: any) =>
    //             usuario.loja_usuario?.split(",").includes(loja)
    //           )
    //         )
    //         .map((e: any) => ({
    //           label: `${e.nome_usuario}`,
    //           value: `${e.id_usuario}`,
    //         }))}
    //       defaultValue={
    //         usuarioTipoAtendimento ||
    //         (defaultValues && defaultValues["responsavel_tarefa"])
    //       }
    //     />
    //     <InputSelectComponent
    //       name="prioridade_cham"
    //       label="Prioridade"
    //       formulario={form}
    //       required
    //       error="Preencha a Prioridade"
    //       options={prioridadeOptions.map((e: any) => ({
    //         label: `${e.nome_prioridade}`,
    //         value: `${e.id_prioridade}`,
    //       }))}
    //       defaultValue={
    //         prioridadeTipoAtendimento ||
    //         (defaultValues && defaultValues["prioridade_cham"])
    //       }
    //     />
    //   </InputGroup>
    //   <InputGroup>
    //     <Input
    //       required
    //       error="Preencha o Relato"
    //       name="obs_cham"
    //       label="Relato do Cliente"
    //       type="textarea"
    //       formulario={form}
    //       defaultValue={defaultValues && defaultValues["obs_cham"]}
    //       disabled={disabledFields?.some(
    //         (field: string) => field == "obs_cham"
    //       )}
    //     />
    //   </InputGroup>
    //   {/* <InputGroup>
    //     <Input
    //       label="Anexo"
    //       onRemoveFile={() => {
    //         setAnexoBase64(""), setAnexoFile(null);
    //       }}
    //       name="anexo_atendimento"
    //       type="file"
    //       accept="image/*"
    //       onInputProp={(event: any) => {
    //         const inputElement = event.target as HTMLInputElement;

    //         if (inputElement.files && inputElement.files.length > 0) {
    //           const file = inputElement.files[0];
    //           const reader = new FileReader();
    //           reader.onloadend = () => {
    //             const base64String = reader.result as string;

    //             setAnexoFile(file);
    //             setAnexoBase64(base64String);
    //           };

    //           reader.readAsDataURL(file);
    //         }
    //         return 1;
    //       }}
    //       defaultValue={anexoBase64}
    //     />
    //   </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>
    //   <div className="flex justify-end">
    //     <Button loading={isLoading}>Cadastrar</Button>
    //   </div>{" "}
    // </form>
  );
};

export default FormNovoAtendimento;
