import Input from "@/components/Forms/Input";
import InputGroup from "@/components/Forms/InputGroup";
import InputSelectComponent from "@/components/Forms/InputSelect";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { listarFluxosPresentes } from "@/requests/CRM/kanban";
import { listarClientesConsulta } from "@/requests/CRUD/Cliente/listarClientes";
import { listarEtapasFunis } from "@/requests/CRUD/ColetaDados/cadastroColetaDados";
import { listarItensKitsPorTipo } from "@/requests/CRUD/ColetaDados/listarItenskitsDiversos";
import { listarLojas } from "@/requests/CRUD/Lojas/listarLojas";
import { listarUsuarios } from "@/requests/CRUD/Usuario/listarUsuarios";
import { useAuth } from "@/src/contexts/authContext";
import { IValueLabel } from "@/types/formInterfaces";
import { GetForm } from "@/utils";
import { Settings } from "lucide-react";
import { ReactNode, useEffect, useState } from "react";
const FormularioPropostas = ({
  origin,
  setLoading,
  setFilterValues,
  cidades,
  origens,
  orientacoes,
  tipoNegocio,
  classificacoes,
  setError,
  error,
  usuarios,
  onSubtmitFilter,
  children,
  pendencias,
  indicadores,
  setIndicadores,
}: {
  origin: string;
  filterValues?: any;
  cidades: any;
  origens: any;
  setLoading?: any;
  tipoNegocio?: any;
  classificacoes?: any;
  orientacoes: any;
  pendencias: any;
  usuarios: any;
  error: any;
  setError?: any;
  setFilterValues?: (values: any) => void;
  onSubtmitFilter?: any;
  children?: ReactNode;
  indicadores: any;
  setIndicadores: any;
}) => {
  const { handleSubmit, ...form } = GetForm();

  const { valuesSession, perfil, usuario } = useAuth();
  const { session } = valuesSession();
  const [dataInicio, setDataInicio] = useState<any>("");
  const [dataFim, setDataFim] = useState<any>("");
  const [lojas, setLojas] = useState<any[]>([]);
  const [selectedLoja, setSelectedLoja] = useState<any>([]);
  const [vendedores, setVendedores] = useState<any[]>([]);
  const [potenciaInversores, setPotenciaInversores] = useState<any[]>([]);
  const [potenciaModulos, setPotenciaModulos] = useState<any[]>([]);
  const [clientes, setClientes] = useState<any[]>([]);
  const [naoInformado, setNaoInformado] = useState(false);
  const [etapas, setEtapas] = useState<any>([]);
  const [fluxos, setFluxos] = useState<any>([]);
  const tipoProposta = [
    { label: "Geradas", value: "0" },
    { label: "Aprovadas", value: "1" },
    { label: "Reprovadas", value: "2" },
    { label: "Canceladas", value: "3" },
  ];

  const formatDate = (date: Date) => date.toISOString().split("T")[0];

  useEffect(() => {
    const now = new Date();
    const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
    const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);

    const dataInicial = new Date(2000, 0, 1);
    const dataFinal = new Date(2100, 11, 31);

    form.setValue("data_inicio", formatDate(dataInicial));
    form.setValue("data_fim", formatDate(dataFinal));
  }, []);
  const handleDataInicioChange = (e: any) => {
    setDataInicio(e.target.value);
    if (dataFim && e.target.value > dataFim) {
      setError("A data de início não pode ser maior que a data de fim.");
    } else {
      setError("");
    }
  };

  const handleDataFimChange = (e: any) => {
    setDataFim(e.target.value);
    if (dataInicio && e.target.value < dataInicio) {
      setError("A data de fim não pode ser menor que a data de início.");
    } else {
      setError("");
    }
  };
  const tipoPessoaOptions = [
    { value: "F", label: "Física" },
    { value: "J", label: "Jurídica" },
  ];
  useEffect(() => {
    setLoading(true);
    if (!perfil) return;
    const idsLojaUsuario = usuario?.loja_usuario
      .split(",")
      .map((id: any) => id.trim());

    Promise.all([
      listarLojas(),
      listarItensKitsPorTipo("8,9", { status_item: "*" }),
      listarUsuarios(session.id_loja_usuario),
      listarClientesConsulta(),
      listarEtapasFunis(),
      listarFluxosPresentes(),
    ]).then(([lojasRes, itensKit, usuariosRes, clientesRes, etapas, fluxos]) => {
      setEtapas(etapas)
      setFluxos(fluxos)
      setLojas(
        lojasRes.filter((loja: any) => idsLojaUsuario?.includes(loja.id_loja)),
      );

      ////
      const removeDuplicatas = (array: any[], key: string) => {
        const seen = new Set();
        return array.filter((item) => {
          const val = item[key];
          if (seen.has(val)) return false;
          seen.add(val);
          return true;
        });
      };

      const inversores = itensKit.filter((item: any) => item.tipo_item === "8");
      const modulos = itensKit.filter((item: any) => item.tipo_item === "9");

      setPotenciaInversores(removeDuplicatas(inversores, "potencia_item")); // ou 'id'
      setPotenciaModulos(removeDuplicatas(modulos, "potencia_item"));
      ///
      setVendedores(
        usuariosRes.filter((res: any) => res.comissionado_usuario == "1"),
      );

      ////
      clientesRes.filter(
        (client: any) => client.responsavel_cliente == session.id_usuario,
      );
      ///
      setLoading(false);
    });
  }, [perfil]);
  const fluxosSelecionados =
    (form.watch("fluxos_filtro" as any) || []).map(
      (e: any) => String(e.value)
    );

  const etapasFiltradas = etapas.filter((etapa: any) => {
    if (
      fluxosSelecionados.length === 0 ||
      fluxosSelecionados.includes("*")
    ) {
      return true;
    }

    return fluxosSelecionados.includes(
      String(etapa.grupo_etapa_funil)
    );
  });
  return (
    <form onSubmit={handleSubmit(onSubtmitFilter)}>
      {error && (
        <div className="w-full flex flex-col items-center justify-center p-2">
          <span className="text-danger p-2 text-xl bg-stroke bg-opacity-70 rounded-md">
            {error}
          </span>
        </div>
      )}
      <InputGroup className="w-80 mb-5">
        <InputSelectComponent
          name="status_proposta"
          label="Tipo Proposta"
          formulario={form}
          options={[
            {
              value: "*",
              label: "Todas",
            },
            ...tipoProposta,
          ]}
          required
          defaultValue={"*"}
          error="Preencha esse campo"
        />
      </InputGroup>
      <hr className="mb-4" />
      <InputGroup>
        <InputSelectComponent
          name="orientacoes_proposta"
          label="Orientação"
          formulario={form}
          isMulti
          options={[
            { value: String("*"), label: "Todos" },
            ...orientacoes.map((orientacao: any) => ({
              label: orientacao.nome_orientacao,
              value: orientacao.id_orientacao,
            })),
          ]}
          onChange={(selectedOptions: any) => {
            const hasAllSelected = selectedOptions.some(
              (option: any) => option.value === "*",
            );

            if (hasAllSelected) {
              form.setValue(
                "orientacoes_proposta" as never,
                [{ label: "Todos", value: "*" }] as never,
              );
            } else {
              form.setValue(
                "orientacoes_proposta" as never,
                selectedOptions as never,
              );
            }
          }}
          defaultValue={"*"}
        />
        <InputSelectComponent
          name="potencia_modulo"
          label="Potencia Módulo"
          formulario={form}
          isMulti
          options={[
            { value: String("*"), label: "Todos" },

            ...potenciaModulos
              .sort((a, b) => a.potencia_item - b.potencia_item)
              .map((potencia) => ({
                label: potencia.potencia_item,
                value: potencia.potencia_item,
              })),
          ]}
          onChange={(selectedOptions: any) => {
            const hasAllSelected = selectedOptions.some(
              (option: any) => option.value === "*",
            );

            if (hasAllSelected) {
              form.setValue(
                "potencia_modulo" as never,
                [{ label: "Todos", value: "*" }] as never,
              );
            } else {
              form.setValue(
                "potencia_modulo" as never,
                selectedOptions as never,
              );
            }
          }}
          defaultValue={"*"}
        />
        <InputSelectComponent
          name="potencia_inversor"
          label="Potencia Inversor"
          formulario={form}
          isMulti
          options={[
            { value: String("*"), label: "Todos" },

            ...potenciaInversores
              .sort((a, b) => a.potencia_item - b.potencia_item)
              .map((potencia) => ({
                label: potencia.potencia_item,
                value: potencia.potencia_item,
              })),
          ]}
          onChange={(selectedOptions: any) => {
            const hasAllSelected = selectedOptions.some(
              (option: any) => option.value === "*",
            );

            if (hasAllSelected) {
              form.setValue(
                "potencia_inversor" as never,
                [{ label: "Todos", value: "*" }] as never,
              );
            } else {
              form.setValue(
                "potencia_inversor" as never,
                selectedOptions as never,
              );
            }
          }}
          defaultValue={"*"}
        />
        <Input name="qtd_modulos" formulario={form} label="Qtde. Módulos" />

      </InputGroup>
      <InputGroup>
        <Input
          name="qtd_inversores"
          formulario={form}
          label="Qtde. Inversores"
        />
        <InputSelectComponent
          name="fluxos_filtro"
          label="Fluxos"
          textSize="text-sm"
          labelSize="text-md"
          width="w-[100%]"
          removeDocumentBody={
            origin !== "relatorio" && origin !== "relatorio-negocios"
          }
          skipEffect
          isMulti
          defaultValue={
            (["relatorio", "relatorio-negocios"].includes(origin) &&
              "*")
          }
          formulario={form}
          options={[
            { value: String("*"), label: "Todos" },
            ...fluxos.map((e: any) => ({
              value: e.id_funil,
              label: e.titulo_funil,
            })),
          ]}
        />
        <InputSelectComponent
          name="etapas_fluxo_filtro"
          label="Etapas"
          textSize="text-sm"
          labelSize="text-md"
          width="w-[100%]"
          removeDocumentBody={
            origin !== "relatorio" && origin !== "relatorio-negocios"
          }
          skipEffect
          isMulti
          defaultValue={
            (["relatorio", "relatorio-negocios"].includes(origin) &&
              "*")
          }
          formulario={form}
          options={[
            { value: String("*"), label: "Todos" },
            ...etapasFiltradas.map((e: any) => ({
              value: e.id_etapa_funil,
              label: e.titulo_etapa_funil,
            })),
          ]}
        />
      </InputGroup>
      <div className="text-sm py-2">
        <strong>Filtros de Datas do Período:</strong>
      </div>
      <InputGroup>
        <div className="p-4 my-2 mb-4 w-full relative border border-black/30 rounded-md">
          <InputGroup>
            <Input
              label="Data Geração da Proposta De"
              name="data_inicio_geracao_proposta"
              formulario={form}
              type="date"
              onChange={handleDataInicioChange}
            />
            <Input
              label="Até"
              name="data_fim_geracao_proposta"
              formulario={form}
              type="date"
              onChange={handleDataFimChange}
            />
            <Input
              label="Data Aprovação da Proposta De"
              name="data_inicio_aprovacao_proposta"
              formulario={form}
              type="date"
            />
            <Input
              label="Até"
              name="data_fim_aprovacao_proposta"
              formulario={form}
              type="date"
            />
            <Input
              label="Data Cancelamento da Proposta De"
              name="data_inicio_cancelamento_proposta"
              formulario={form}
              type="date"
            />
            <Input
              label="Até"
              name="data_fim_cancelamento_proposta"
              formulario={form}
              type="date"
            />
          </InputGroup>
        </div>
      </InputGroup>
      <Accordion type="single" className="mb-8" collapsible>
        <AccordionItem value="filtros">
          <AccordionTrigger className="text-sm pl-4 justify-center hover:text-black">
            <span className="flex items-center gap-2">
              <Settings size={17} /> Filtros Cliente
            </span>
          </AccordionTrigger>
          <AccordionContent forceMount className="data-[state=closed]:hidden">
            <InputGroup>
              <InputSelectComponent
                formulario={form}
                textSize="text-sm"
                labelSize="text-md"
                // width="w-[100%]"
                // skipEffect
                removeDocumentBody={
                  origin !== "relatorio" && origin !== "relatorio-negocios"
                }
                isMulti
                name="loja_cliente"
                defaultValue={
                  lojas.length > 1 ? "*" : session.loja_padrao_usuario
                }
                disabled={
                  lojas.length == session.loja_usuario?.split(",").length
                }
                options={[
                  { value: String("*"), label: "Todos" },
                  ...lojas?.map((loja: any) => ({
                    label: loja.nome_loja,
                    value: loja.id_loja,
                  })),
                ]}
                label="Loja Cliente"
              />
              {usuarios && usuarios.length > 0 && (
                <InputSelectComponent
                  formulario={form}
                  name="responsavel_cliente"
                  label="Responsável Cliente"
                  dynamic
                  isMulti
                  options={[
                    { value: "*", label: "Todos" },
                    ...usuarios
                      ?.filter(
                        (vendedor: any) => vendedor.comissionado_usuario == "1",
                      )
                      .map((e: any) => ({
                        value: e.id_usuario,
                        label: e.nome_usuario,
                      })),
                  ]}
                  defaultValue={"*"}
                />
              )}
              <InputSelectComponent
                formulario={form}
                name="cidade_cliente"
                label="Cidade do Cliente"
                isMulti
                options={[
                  { value: "*", label: "Todas" },
                  ...cidades!.map((e: any) => ({
                    value: `${e.nome_cidade}`,
                    label: `${e.nome_cidade} - ${e.estado_cidade}`,
                  })),
                ]}
                defaultValue={"*"}
              />
              <InputSelectComponent
                formulario={form}
                name="origem_cliente"
                label="Origem Cliente"
                isMulti
                options={[
                  { value: "*", label: "Todos" },
                  ...origens.map((e: any) => {
                    return {
                      value: e.id_origem_cliente,
                      label: e.nome_origem_cliente,
                    };
                  }),
                ]}
                defaultValue={"*"}
              />
              <InputSelectComponent
                formulario={form}
                name="tipoPessoa_cliente"
                label="Tipo Pessoa Cliente"
                isMulti
                options={[
                  { value: "*", label: "Todos" },
                  ...tipoPessoaOptions.map((e: any) => {
                    return {
                      value: e.value,
                      label: e.label,
                    };
                  }),
                ]}
                defaultValue={"*"}
              />
              <InputSelectComponent
                name="status_cliente"
                label="Status Cliente"
                textSize="text-sm"
                labelSize="text-md"
                width="w-[100%]"
                skipEffect
                isMulti
                formulario={form}
                defaultValue={"*"}
                options={[
                  { value: String("*"), label: "Todos" },
                  { value: "1", label: "Ativo" },
                  { value: "0", label: "Inativo" },
                ]}
              />
            </InputGroup>
          </AccordionContent>
        </AccordionItem>
      </Accordion>
      <Accordion type="single" className="mb-8" collapsible>
        <AccordionItem value="filtros">
          <AccordionTrigger className="text-sm pl-4 justify-center hover:text-black">
            <span className="flex items-center gap-2">
              <Settings size={17} /> Filtros Avançados
            </span>
          </AccordionTrigger>
          <AccordionContent forceMount className="data-[state=closed]:hidden">
            <InputGroup>
              <Input
                name="numNegocio_filtro"
                label="Nº do Negócio"
                textSize="text-sm"
                labelSize="text-md"
                formulario={form}
                mascara="numerico"
              />
              <InputSelectComponent
                name="status_filtro"
                label="Status"
                textSize="text-sm"
                labelSize="text-md"
                width="w-[100%]"
                skipEffect
                isMulti
                formulario={form}
                defaultValue={"*"}
                options={[
                  { value: String("*"), label: "Todos" },
                  { value: "0", label: "Em aberto" },
                  { value: "2", label: "Concluído" },
                  { value: "100", label: "Cancelado" },
                ]}
              />

              <InputSelectComponent
                name="cliente_filtro"
                label="Cliente"
                textSize="text-sm"
                labelSize="text-md"
                width="w-[100%]"
                removeDocumentBody={
                  origin !== "relatorio" && origin !== "relatorio-negocios"
                }
                skipEffect
                isMulti
                formulario={form}
                defaultValue={"*"}
                options={[
                  { value: String("*"), label: "Todos" },
                  ...clientes?.map<IValueLabel>((cliente: any) => ({
                    label: cliente.nome_cliente,
                    value: cliente.id_cliente,
                  })),
                ]}
              />
              <InputSelectComponent
                name="tipo_negocio_filtro"
                label="Tipo de Negócio"
                textSize="text-sm"
                labelSize="text-md"
                width="w-[100%]"
                removeDocumentBody={
                  origin !== "relatorio" && origin !== "relatorio-negocios"
                }
                skipEffect
                isMulti
                defaultValue={"*"}
                formulario={form}
                options={[
                  { value: String("*"), label: "Todos" },
                  ...tipoNegocio.map((e: any) => ({
                    value: e.id_tipo_negocio,
                    label: e.nome_tipo_negocio,
                  })),
                ]}
              />
              <InputSelectComponent
                name="classificacao_filtro"
                label="Classificação do Negócio"
                textSize="text-sm"
                labelSize="text-md"
                width="w-[100%]"
                removeDocumentBody={
                  origin !== "relatorio" && origin !== "relatorio-negocios"
                }
                skipEffect
                isMulti
                defaultValue={"*"}
                formulario={form}
                options={[
                  { value: String("*"), label: "Todos" },
                  ...(classificacoes || [])
                    .filter((e: any) => e.status_classificacao == 1)
                    .map((e: any) => ({
                      value: e.id_classificacao,
                      label: e.nome_classificacao,
                    })),
                  { value: "0", label: "Não Informado" },
                ]}
              />
              {/* </InputGroup>
            <InputGroup> */}
              <InputSelectComponent
                formulario={form}
                textSize="text-sm"
                labelSize="text-md"
                width="w-[100%]"
                // skipEffect
                removeDocumentBody={
                  origin !== "relatorio" && origin !== "relatorio-negocios"
                }
                isMulti
                name="loja_filtro"
                defaultValue={
                  lojas?.length > 1 ? "*" : session.loja_padrao_usuario
                }
                disabled={
                  lojas.length == session.loja_usuario?.split(",").length
                }
                options={[
                  { value: String("*"), label: "Todos" },
                  ...lojas?.map((loja: any) => ({
                    label: loja.nome_loja,
                    value: loja.id_loja,
                  })),
                ]}
                label="Loja"
              />
            </InputGroup>
            <InputGroup>
              <InputSelectComponent
                formulario={form}
                name="cidade_filtro"
                label="Cidade da Instalação"
                isMulti
                options={[
                  { value: "*", label: "Todas" },
                  ...cidades!.map((e: any) => ({
                    value: `${e.nome_cidade}`,
                    label: `${e.nome_cidade} - ${e.estado_cidade}`,
                  })),
                ]}
                defaultValue={"*"}
              />
              <InputSelectComponent
                formulario={form}
                name="pendencia_filtro"
                label="Status Linha da Pendência"
                isMulti
                options={[
                  { value: "*", label: "Todas" },
                  ...pendencias?.map((e: any) => ({
                    value: `${e.id_pendencia}`,
                    label: `${e.nome_pendencia}`,
                  })),
                ]}
                defaultValue={"*"}
              />
              <div className="border w-full border-black/30 p-2 rounded-md">
                <div className="flex justify-center mb-2">
                  <label className="flex items-center gap-2 cursor-pointer select-none">
                    <input
                      type="checkbox"
                      checked={naoInformado}
                      onChange={(e) => {
                        setNaoInformado(e.target.checked);
                        form.setValue("nao_informado_filtro", e.target.checked);
                      }}
                      className="w-4 h-4 accent-black"
                    />
                    <span className="font-medium text-sm">Não informado</span>
                  </label>
                </div>

                <div className="flex gap-3">
                  <Input
                    label="De consumo"
                    name="de_consumo_negocio_filtro"
                    formulario={form}
                    required
                    mascara="numero"
                    defaultValue={"0"}
                    width="w-[100%]"
                    disabled={naoInformado}
                  />
                  <Input
                    label="Até consumo"
                    name="ate_consumo_negocio_filtro"
                    formulario={form}
                    required
                    mascara="numero"
                    width="w-[100%]"
                    defaultValue={"99.999.999,99"}
                    disabled={naoInformado}
                  />
                </div>
              </div>
              <Input
                label="De"
                name="data_inicio"
                width={"xl:w-1/2"}
                formulario={form}
                type="date"
                onChange={handleDataInicioChange}
                error={"Preencha esse campo!"}
              />
              <Input
                label="Até"
                name="data_fim"
                width={"xl:w-1/2"}
                formulario={form}
                type="date"
                onChange={handleDataFimChange}
                error={"Preencha esse campo!"}
              />
            </InputGroup>
            {usuarios && usuarios.length > 0 && (
              <div className="p-9   my-2 mb-4 relative border border-black/30 rounded-md">
                <span className="absolute -top-3 font-semibold text-black bg-white px-3 left-9">
                  Responsáveis
                </span>
                <InputGroup>
                  <InputSelectComponent
                    formulario={form}
                    textSize="text-sm"
                    labelSize="text-md"
                    width="w-[100%]"
                    skipEffect
                    isMulti
                    removeDocumentBody={
                      origin !== "relatorio" && origin !== "relatorio-negocios"
                    }
                    name="responsavel_filtro"
                    options={[
                      { value: "", label: "Não Informado" },
                      { value: String("*"), label: "Todos" },
                      ...usuarios?.map((user: any) => ({
                        label: user.nome_usuario,
                        value: user.id_usuario,
                      })),
                    ]}
                    label="Quem gerou"
                    menuPositionFixed
                    defaultValue={"*"}
                  />
                  <InputSelectComponent
                    formulario={form}
                    textSize="text-sm"
                    labelSize="text-md"
                    width="w-[100%]"
                    skipEffect
                    isMulti
                    removeDocumentBody={
                      origin !== "relatorio" && origin !== "relatorio-negocios"
                    }
                    name="administrativo_filtro"
                    defaultValue={"*"}
                    options={[
                      { value: "", label: "Não Informado" },
                      { value: String("*"), label: "Todos" },
                      ...usuarios
                        ?.filter(
                          (user: any) =>
                            user.cargo_perfil == "1" ||
                            user.cargo_perfil == "4" ||
                            user.cargo_perfil == "-1",
                        )
                        ?.map((user: any) => ({
                          label: user.nome_usuario,
                          value: user.id_usuario,
                        })),
                    ]}
                    label="Administrador"
                    menuPositionFixed
                  />

                  {/* </InputGroup>
                  <InputGroup> */}
                  <InputSelectComponent
                    formulario={form}
                    textSize="text-sm"
                    labelSize="text-md"
                    width="w-[100%]"
                    isMulti
                    defaultValue={
                      perfil?.cargo_perfil == 2 ? usuario.id_usuario : "*"
                    }
                    disabled={perfil?.visualiza_todos_contatos_perfil != "1"}
                    removeDocumentBody={
                      origin !== "relatorio" && origin !== "relatorio-negocios"
                    }
                    name="vendedor_filtro"
                    options={[
                      { value: "", label: "Não Informado" },

                      { value: String("*"), label: "Todos" },
                      ...usuarios
                        ?.filter(
                          (user: any) => user.comissionado_usuario == "1",
                        )
                        ?.map((user: any) => ({
                          label: user.nome_usuario,
                          value: user.id_usuario,
                        })),
                    ]}
                    label="Vendedor"
                    menuPositionFixed
                    onChange={(selectedOptions: any) => {
                      const hasAllSelected = selectedOptions.some(
                        (option: any) => option.value === "*",
                      );

                      if (hasAllSelected) {
                        form.setValue(
                          "vendedor_filtro" as never,
                          [{ label: "Todos", value: "*" }] as never,
                        );
                      } else {
                        form.setValue(
                          "vendedor_filtro" as never,
                          selectedOptions as never,
                        );
                      }
                    }}
                  />
                  <InputSelectComponent
                    formulario={form}
                    textSize="text-sm"
                    labelSize="text-md"
                    width="w-[100%]"
                    isMulti
                    removeDocumentBody={
                      origin !== "relatorio" && origin !== "relatorio-negocios"
                    }
                    defaultValue={
                      perfil?.cargo_perfil == 3 ? usuario.id_usuario : "*"
                    }
                    disabled={perfil?.visualiza_todos_contatos_perfil != "1"}
                    name="preVendedor_filtro"
                    options={[
                      { value: "", label: "Não Informado" },

                      { value: String("*"), label: "Todos" },
                      ...usuarios
                        ?.filter((user: any) => user.cargo_perfil == "3")
                        ?.map((user: any) => ({
                          label: user.nome_usuario,
                          value: user.id_usuario,
                        })),
                    ]}
                    label="Pré-Vendedor"
                    menuPositionFixed
                    onChange={(selectedOptions: any) => {
                      const hasAllSelected = selectedOptions.some(
                        (option: any) => option.value === "*",
                      );

                      if (hasAllSelected) {
                        form.setValue(
                          "preVendedor_filtro" as never,
                          [{ label: "Todos", value: "*" }] as never,
                        );
                      } else {
                        form.setValue(
                          "preVendedor_filtro" as never,
                          selectedOptions as never,
                        );
                      }
                    }}
                  />
                </InputGroup>
                <InputGroup>
                  <InputSelectComponent
                    formulario={form}
                    isMulti
                    textSize="text-sm"
                    labelSize="text-md"
                    width="w-[100%]"
                    defaultValue={
                      perfil?.cargo_perfil == 5 ? usuario.id_usuario : "*"
                    }
                    disabled={perfil?.visualiza_todos_contatos_perfil != "1"}
                    removeDocumentBody={
                      origin !== "relatorio" && origin !== "relatorio-negocios"
                    }
                    name="tecnico_filtro"
                    options={[
                      { value: "", label: "Não Informado" },

                      { value: String("*"), label: "Todos" },
                      ...usuarios
                        ?.filter((user: any) => user.cargo_perfil == "5")
                        ?.map((user: any) => ({
                          label: user.nome_usuario,
                          value: user.id_usuario,
                        })),
                    ]}
                    label="Técnico"
                    menuPositionFixed
                    onChange={(selectedOptions: any) => {
                      const hasAllSelected = selectedOptions.some(
                        (option: any) => option.value === "*",
                      );

                      if (hasAllSelected) {
                        form.setValue(
                          "tecnico_filtro" as never,
                          [{ label: "Todos", value: "*" }] as never,
                        );
                      } else {
                        form.setValue(
                          "tecnico_filtro" as never,
                          selectedOptions as never,
                        );
                      }
                    }}
                  />
                  <InputSelectComponent
                    formulario={form}
                    isMulti
                    textSize="text-sm"
                    labelSize="text-md"
                    width="w-[100%]"
                    defaultValue={
                      perfil?.cargo_perfil == 6 ? usuario.id_usuario : "*"
                    }
                    disabled={perfil?.visualiza_todos_contatos_perfil != "1"}
                    removeDocumentBody={
                      origin !== "relatorio" && origin !== "relatorio-negocios"
                    }
                    name="instalador_filtro"
                    options={[
                      { value: "", label: "Não Informado" },

                      { value: String("*"), label: "Todos" },
                      ...usuarios
                        ?.filter((user: any) => user.cargo_perfil == "6")
                        ?.map((user: any) => ({
                          label: user.nome_usuario,
                          value: user.id_usuario,
                        })),
                    ]}
                    label="Instalador"
                    menuPositionFixed
                    onChange={(selectedOptions: any) => {
                      const hasAllSelected = selectedOptions.some(
                        (option: any) => option.value === "*",
                      );

                      if (hasAllSelected) {
                        form.setValue(
                          "instalador_filtro" as never,
                          [{ label: "Todos", value: "*" }] as never,
                        );
                      } else {
                        form.setValue(
                          "instalador_filtro" as never,
                          selectedOptions as never,
                        );
                      }
                    }}
                  />
                  <InputSelectComponent
                    formulario={form}
                    textSize="text-sm"
                    labelSize="text-md"
                    width="w-[100%]"
                    isMulti
                    removeDocumentBody={
                      origin !== "relatorio" && origin !== "relatorio-negocios"
                    }
                    defaultValue={
                      perfil?.cargo_perfil == 4 ? usuario.id_usuario : "*"
                    }
                    disabled={perfil?.visualiza_todos_contatos_perfil != "1"}
                    name="gerente_filtro"
                    options={[
                      { value: "", label: "Não Informado" },

                      { value: String("*"), label: "Todos" },
                      ...usuarios
                        ?.filter(
                          (user: any) =>
                            user.cargo_perfil == "1" ||
                            user.cargo_perfil == "4",
                        )
                        ?.map((user: any) => ({
                          label: user.nome_usuario,
                          value: user.id_usuario,
                        })),
                    ]}
                    label="Gerente"
                    menuPositionFixed
                    onChange={(selectedOptions: any) => {
                      const hasAllSelected = selectedOptions.some(
                        (option: any) => option.value === "*",
                      );

                      if (hasAllSelected) {
                        form.setValue(
                          "gerente_filtro" as never,
                          [{ label: "Todos", value: "*" }] as never,
                        );
                      } else {
                        form.setValue(
                          "gerente_filtro" as never,
                          selectedOptions as never,
                        );
                      }
                    }}
                  />
                  <InputSelectComponent
                    formulario={form}
                    textSize="text-sm"
                    labelSize="text-md"
                    width="w-[100%]"
                    isMulti
                    removeDocumentBody={
                      origin !== "relatorio" && origin !== "relatorio-negocios"
                    }
                    defaultValue={
                      perfil?.cargo_perfil == 7 ? usuario.id_usuario : "*"
                    }
                    disabled={perfil?.visualiza_todos_contatos_perfil != "1"}
                    name="supervisor_filtro"
                    options={[
                      { value: "", label: "Não Informado" },

                      { value: String("*"), label: "Todos" },
                      ...usuarios
                        ?.filter((user: any) => user.cargo_perfil == "7")
                        ?.map((user: any) => ({
                          label: user.nome_usuario,
                          value: user.id_usuario,
                        })),
                    ]}
                    label="Supervisor"
                    menuPositionFixed
                    onChange={(selectedOptions: any) => {
                      const hasAllSelected = selectedOptions.some(
                        (option: any) => option.value === "*",
                      );

                      if (hasAllSelected) {
                        form.setValue(
                          "supervisor_filtro" as never,
                          [{ label: "Todos", value: "*" }] as never,
                        );
                      } else {
                        form.setValue(
                          "supervisor_filtro" as never,
                          selectedOptions as never,
                        );
                      }
                    }}
                  />
                </InputGroup>
              </div>
            )}
          </AccordionContent>
        </AccordionItem>
      </Accordion>
      {children}
    </form>
  );
};

export default FormularioPropostas;
