import Input from "@/components/Forms/Input";
import { Table, TableCell, TableRow } from "@/components/ui/table";
import { useCapaCard } from "@/src/contexts/CardContext";
import { Dispatch, SetStateAction, useEffect, useMemo, useState } from "react";

const ConfiguracoesRegrasEtapa = ({
  // Gerais
  locks,

  locksResponsaveis,
  setLocksResponsaveisId,
  lockResponsaveisId,
  locksRetrocesso,
  locksRetrocessoId,
  setLocksRetrocessoId,

  // Dados
  allPendencias,
  linhaPendencias,
  dadosFunil,
  categoriasAnexos,
  camposPersonalizados,
  documentosPersonalizados,
  categoriaslocksPermissoes,
  listOther,

  // Tipos (NOVOS estados por-tipo)
  locksId,
  setLocksId,
  locksPendencias,
  setLocksPendencias,
  locksAnexos,
  setLocksAnexos,
  locksDocsPersonalizados,
  setLocksDocsPersonalizados,
  locksCamposPersonalizados,
  setLocksCamposPersonalizados,
  moverParaQualquer,
  setMoverParaQualquer,
  listCanSendFor,
  setListCanSendFor,
  permissoesLocks,
  setPermissoesLocks,
}: {
  // Gerais
  locks: any[];

  locksResponsaveis: any[];
  setLocksResponsaveisId: Dispatch<SetStateAction<string[]>>;
  lockResponsaveisId: string[];
  locksRetrocesso: any[];

  // Dados
  allPendencias: any[];
  linhaPendencias: any[];
  dadosFunil: any;
  categoriasAnexos: any[];
  documentosPersonalizados: any[];
  camposPersonalizados: any[];
  categoriaslocksPermissoes: any[];
  listOther: any[];

  // Tipos (NOVOS estados por-tipo)
  locksId: string[];
  setLocksId: Dispatch<SetStateAction<Record<string, string[]>>>;
  locksRetrocessoId: string[];
  setLocksRetrocessoId: Dispatch<SetStateAction<Record<string, string[]>>>;
  locksPendencias: Record<string, string[]>;
  setLocksPendencias: Dispatch<SetStateAction<Record<string, string[]>>>;
  locksAnexos: Record<string, string[]>;
  setLocksAnexos: Dispatch<SetStateAction<Record<string, string[]>>>;
  locksDocsPersonalizados: Record<string, string[]>;
  setLocksDocsPersonalizados: Dispatch<
    SetStateAction<Record<string, string[]>>
  >;
  locksCamposPersonalizados: Record<string, string[]>;
  setLocksCamposPersonalizados: Dispatch<
    SetStateAction<Record<string, string[]>>
  >;
  moverParaQualquer: Record<string, boolean>;
  setMoverParaQualquer: Dispatch<SetStateAction<Record<string, boolean>>>;
  listCanSendFor: Record<string, string[]>;
  setListCanSendFor: Dispatch<SetStateAction<Record<string, string[]>>>;
  permissoesLocks: Record<string, string[]>;
  setPermissoesLocks: Dispatch<SetStateAction<Record<string, string[]>>>;

  [x: string]: any;
}) => {
  const { tiposNegocios } = useCapaCard();

  const [activeTab, setActiveTab] = useState<"gerais" | "tipos">("gerais");
  const [activeTipoId, setActiveTipoId] = useState<string | null>(null);

  const normalizeMap = (
    map: Record<string, any> | undefined | null,
  ): Record<string, string[]> => {
    const normalized: Record<string, string[]> = {};
    if (!map) return normalized;
    for (const key in map) {
      const value = map[key];
      if (Array.isArray(value)) normalized[key] = value.map(String);
      else if (value != null) normalized[key] = [String(value)];
      else normalized[key] = [];
    }
    return normalized;
  };
  useEffect(() => {
    if (activeTipoId) {
      const arr = getArr(listCanSendFor, activeTipoId);
      const jaDefinido = getBool(moverParaQualquer, activeTipoId);

      if (!jaDefinido && arr.length === 0) {
        setBooleanInMap(setMoverParaQualquer, activeTipoId, true);
      }
    }

    // só depende do idTipo (não de moverParaQualquer ou listCanSendFor)
  }, [activeTipoId]);

  // Helpers de toggle por-tipo
  const toggleInMap = (
    setMap: Dispatch<SetStateAction<Record<string, string[]>>>,
    tipoId: string,
    valueId: string,
    checked: boolean,
  ) => {
    setMap((prev) => {
      const safePrev = normalizeMap(prev);
      const current = safePrev[tipoId] || [];
      const next = checked
        ? Array.from(new Set([...current, valueId]))
        : current.filter((v) => v != valueId);

      return { ...safePrev, [tipoId]: next };
    });
  };

  const setBooleanInMap = (
    setMap: Dispatch<SetStateAction<Record<string, boolean>>>,
    tipoId: string,
    value: boolean,
  ) => setMap((prev) => ({ ...prev, [tipoId]: value }));

  const getArr = (
    map: Record<string, any> | undefined,
    tipoId: string,
  ): string[] => {
    const arr = map?.[tipoId];
    return Array.isArray(arr) ? arr.map(String) : [];
  };
  const getBool = (map: Record<string, boolean>, tipoId: string) =>
    !!map?.[tipoId];

  const renderMessage = (nome: any) => {
    switch (nome) {
      case "Geração da Proposta":
        return "Proposta Gerada";
      case "Aprovação da Proposta":
        return "Proposta Aprovada";
      case "Geração do Contrato":
        return "Contrato Gerado";
      case "Aprovação do Contrato":
        return "Contrato Aprovado";
      case "Aprovação de Crédito":
        return "Aprovado Pagamento Cliente";
      case "Finalização da Venda":
        return "Finalizado a Venda";
      case "Agendamento da Instalação":
        return "Agendado a Instalação";
      case "Conclusão da Instalação":
        return "Concluído a Instalação";
      default:
        return nome;
    }
  };

  // Tipos permitidos pelo funil
  const tiposPermitidosIds = useMemo(() => {
    const raw = String(dadosFunil?.tipo_negocio_funil ?? "*");
    const arr = raw
      .split(",")
      .map((s) => s.trim())
      .filter(Boolean);
    return arr.length ? arr : ["*"];
  }, [dadosFunil?.tipo_negocio_funil]);

  const tiposAtivosIntegrador = useMemo(() => {
    if (!tiposNegocios) return [];
    if (tiposPermitidosIds.includes("*")) return tiposNegocios;
    return tiposNegocios.filter((t: any) =>
      tiposPermitidosIds.includes(String(t.id_tipo_negocio)),
    );
  }, [tiposNegocios, tiposPermitidosIds]);

  useEffect(() => {
    if (activeTab === "tipos" && !activeTipoId && tiposAtivosIntegrador?.length)
      setActiveTipoId(String(tiposAtivosIntegrador[0].id_tipo_negocio));
  }, [activeTab, activeTipoId, tiposAtivosIntegrador]);

  const pendenciasComNomeFinal = allPendencias?.map((item: any) => ({
    ...item,
    nome_final: renderMessage(item.nome_pendencia),
  }));

  const pendenciasPorTiposNegocios = useMemo(() => {
    return pendenciasComNomeFinal
      ?.filter(
        (item: any) =>
          item.nome_final !== "Projeto Concluído" &&
          item.tipoNegocio_pendencia
            ?.split(",")
            ?.some(
              (tipoNegocio: any) =>
                tiposPermitidosIds.includes(String(tipoNegocio)) ||
                tiposPermitidosIds.includes("*"),
            ),
      )
      .reduce((acc: any, curr: any) => {
        curr?.tipoNegocio_pendencia
          ?.split(",")
          ?.filter(
            (tipo: string) =>
              tiposPermitidosIds.includes(tipo) ||
              tiposPermitidosIds.includes("*"),
          )
          ?.forEach((tipoNegocioPendencia: any) => {
            acc[tipoNegocioPendencia] = [
              ...(acc[tipoNegocioPendencia] || []),
              curr,
            ];
          });
        return acc;
      }, {});
  }, [pendenciasComNomeFinal, tiposPermitidosIds]);

  const getPendenciasOrdenadasDoTipo = (id_tipo_negocio: string) => {
    const pendenciasDoTipoNegocio =
      pendenciasPorTiposNegocios[String(id_tipo_negocio)] || [];
    const ordenadas = linhaPendencias?.reduce((acc: any[], curr: any) => {
      const pendencia = pendenciasDoTipoNegocio?.find(
        (p: any) =>
          p.id_pendencia == curr.codPendencia_sequenciamento_pendencia,
      );
      if (
        pendencia &&
        String(curr.codTipoNegocio_sequenciamento_pendencia) ==
          String(id_tipo_negocio)
      )
        acc.push(pendencia);
      return acc;
    }, []);
    const naoPresentes = pendenciasDoTipoNegocio
      ?.filter((p: any) =>
        ordenadas?.every((x: any) => x.id_pendencia != p.id_pendencia),
      )
      ?.sort((a: any, b: any) =>
        a.nome_pendencia.localeCompare(b.nome_pendencia, "pt-BR"),
      );
    return { ordenadas, naoPresentes };
  };

  const filtrarDocsPorTipo = (id_tipo_negocio: string) =>
    (documentosPersonalizados || []).filter((documento: any) => {
      const tipoDoc = String(
        documento?.tipo_negocio_documento_personalizado || "",
      ).trim();
      if (!tipoDoc) return true;
      if (tipoDoc === "*") return true;
      return tipoDoc
        .split(",")
        .map((s) => s.trim())
        .includes(id_tipo_negocio);
    });

  const filtrarCamposPorTipo = (id_tipo_negocio: string) =>
    (camposPersonalizados || []).filter((campo: any) => {
      const tipoCampo = String(
        campo?.tipo_negocio_campo_personalizado ||
          campo?.tipo_negocio_campo ||
          "",
      ).trim();
      if (!tipoCampo) return true;
      if (tipoCampo === "*") return true;
      return tipoCampo
        .split(",")
        .map((s) => s.trim())
        .includes(id_tipo_negocio);
    });

  const filtrarRetrocessoPorTipo = (id_tipo_negocio: string) =>
    (locksRetrocesso || []).filter((lock: any) => {
      const tipoCampo = String(lock.tipoNegocio_lock || "").trim();
      if (!tipoCampo) return true;
      if (tipoCampo === "*") return true;
      return tipoCampo
        .split(",")
        .map((s) => s.trim())
        .includes(id_tipo_negocio);
    });
  const contatosArr = [1, 2, 3, 21, 22, 34, 36];
  const AbaLocksGerais = () => {
    return (
      <Table className="min-w-full bg-white dark:bg-[#1d2a39] border border-gray-300 shadow-sm">
        <tbody>
          <TableRow>
            <TableCell className="py-2 text-center">
              <div className="mx-auto flex flex-row gap-2 text-error font-bold">
                Nesta Etapa Bloquear a entrada do Card se não houver:
              </div>
            </TableCell>
            <TableCell className="py-2 text-center">
              <div className="mx-auto flex text-center flex-row gap-2">
                Selecione as opções desejadas
              </div>
            </TableCell>
          </TableRow>

          <TableRow className="bg-[#f3f3f3] dark:bg-black-2/20">
            <TableCell className="py-2 text-center">
              <div className="mx-auto flex flex-row gap-2 px-10 font-bold">
                Informações do Contato:
              </div>
            </TableCell>
            <TableCell className="py-2 text-center" />
          </TableRow>

          {locks
            ?.filter((l) => contatosArr.includes(Number(l.id_lock)))
            .map((lock, index) => (
              <TableRow key={`lock-geral-${index}`}>
                <TableCell className="py-2 text-center">
                  {lock.nome_lock}
                </TableCell>
                <TableCell className="py-2 text-center">
                  <Input
                    name=""
                    checked={getArr(locksId, "*").some(
                      (id) => id == lock.id_lock,
                    )}
                    type="checkbox"
                    onChange={(e) =>
                      toggleInMap(
                        setLocksId,
                        "*",
                        String(lock.id_lock),
                        e.target.checked,
                      )
                    }
                  />
                </TableCell>
              </TableRow>
            ))}

          <TableRow className="bg-[#f3f3f3] dark:bg-black-2/20">
            <TableCell className="py-2 text-center">
              <div className="mx-auto flex flex-row gap-2 px-10 font-bold">
                Responsáveis:
              </div>
            </TableCell>
            <TableCell className="py-2 text-center" />
          </TableRow>

          {locksResponsaveis?.map((lock: any, index: any) => (
            <TableRow key={`lock-resp-${index}`}>
              <TableCell className="py-2 text-center">
                {lock.nome_lock}
              </TableCell>
              <TableCell className="py-2 text-center">
                <Input
                  name=""
                  checked={lockResponsaveisId.some(
                    (id: any) => id == lock.id_lock,
                  )}
                  type="checkbox"
                  onChange={(e) => {
                    if (e.target.checked) {
                      setLocksResponsaveisId((previous) => [
                        ...previous,
                        lock.id_lock,
                      ]);
                    } else {
                      setLocksResponsaveisId((previous) =>
                        previous.filter((id) => id != lock.id_lock),
                      );
                    }
                  }}
                />
              </TableCell>
            </TableRow>
          ))}
        </tbody>
      </Table>
    );
  };

  // Secção Mover/Gerar por-tipo
  const SecaoMoverEGerarPorTipo = (idTipo: string) => {
    return (
      <>
        <TableRow className="bg-[#f3f3f3] dark:bg-black-2/20">
          <TableCell className="py-2 text-center">
            <div className="mx-auto flex flex-row gap-2 font-bold text-success">
              Nesta Etapa Permite Movimentar o Card Para:
            </div>
          </TableCell>
          <TableCell className="py-2 text-center" />
        </TableRow>
        <TableRow>
          <TableCell className="py-2 text-center">
            Mover para qualquer etapa
          </TableCell>
          <TableCell className="py-2 text-center">
            <Input
              name=""
              checked={getBool(moverParaQualquer, idTipo)}
              type="checkbox"
              onChange={(e) => {
                const checked = e.target.checked;

                setBooleanInMap(setMoverParaQualquer, idTipo, checked);
                if (checked) {
                  setListCanSendFor((prev) => ({ ...prev, [idTipo]: [] }));
                }
              }}
            />
          </TableCell>
        </TableRow>
        {!getBool(moverParaQualquer, idTipo) &&
          listOther?.map((item: any) => (
            <TableRow key={`move-${idTipo}-${item.id}`}>
              <TableCell className="py-2 text-center">{item.title}</TableCell>
              <TableCell className="py-2 text-center">
                <Input
                  name=""
                  checked={getArr(listCanSendFor, idTipo)?.some(
                    (id) => id == item.id,
                  )}
                  type="checkbox"
                  onChange={(e) =>
                    toggleInMap(
                      setListCanSendFor,
                      idTipo,
                      String(item.id),
                      e.target.checked,
                    )
                  }
                />
              </TableCell>
            </TableRow>
          ))}
        <TableRow className="bg-[#f3f3f3] dark:bg-black-2/20">
          <TableCell className="py-2 text-center">
            <div className="mx-auto flex flex-row gap-2 font-bold text-success">
              Nesta Etapa Permite Gerar:
            </div>
          </TableCell>
          <TableCell className="py-2 text-center" />
        </TableRow>
        {categoriaslocksPermissoes?.map((perm: any) => (
          <TableRow key={`perm-${idTipo}-${perm.id_cfg_lockPermissao}`}>
            <TableCell className="py-2 text-center">
              {perm.nome_cfg_lockPermissao}
            </TableCell>
            <TableCell className="py-2 text-center">
              <Input
                name=""
                checked={getArr(permissoesLocks, idTipo)?.some(
                  (id) => id == perm.id_cfg_lockPermissao,
                )}
                type="checkbox"
                onChange={(e) =>
                  toggleInMap(
                    setPermissoesLocks,
                    idTipo,
                    String(perm.id_cfg_lockPermissao),
                    e.target.checked,
                  )
                }
              />
            </TableCell>
          </TableRow>
        ))}
      </>
    );
  };

  // Sub-abas por Tipo
  const AbaTiposNegocios = () => {
    const tipoSelecionado =
      tiposAtivosIntegrador?.find(
        (t: any) => String(t.id_tipo_negocio) === String(activeTipoId),
      ) || tiposAtivosIntegrador?.[0];

    const idTipoSel = String(tipoSelecionado?.id_tipo_negocio || "");

    const { ordenadas, naoPresentes } = idTipoSel
      ? getPendenciasOrdenadasDoTipo(idTipoSel)
      : { ordenadas: [], naoPresentes: [] };
    const docsDoTipo = idTipoSel ? filtrarDocsPorTipo(idTipoSel) : [];
    const camposDoTipo = idTipoSel ? filtrarCamposPorTipo(idTipoSel) : [];
    const retrocessos = idTipoSel ? filtrarRetrocessoPorTipo(idTipoSel) : [];

    return (
      <>
        <div className="flex gap-2 mb-3 border-b border-gray-300 dark:border-gray-700 overflow-auto">
          {tiposAtivosIntegrador?.map((tipo: any) => {
            const id = String(tipo.id_tipo_negocio);
            const isActive = String(activeTipoId || "") === id;
            return (
              <button
                key={id}
                onClick={() => setActiveTipoId(id)}
                className={`px-4 py-2 whitespace-nowrap ${
                  isActive
                    ? "border-b-2 border-primary font-semibold"
                    : "text-gray-500"
                }`}
              >
                {tipo.nome_tipo_negocio}
              </button>
            );
          })}
        </div>

        <Table className="min-w-full bg-white dark:bg-[#1d2a39] border border-gray-300 shadow-sm">
          <tbody>
            <TableRow>
              <TableCell className="py-2 text-center">
                <div className="mx-auto flex flex-row gap-2 text-error font-bold">
                  Nesta Etapa Bloquear a entrada do Card se não houver:
                </div>
              </TableCell>
              <TableCell className="py-2 text-center">
                <div className="mx-auto flex flex-row gap-2">
                  Selecione as opções desejadas para bloquear
                </div>
              </TableCell>
            </TableRow>
            <TableRow className="bg-[#f3f3f3] dark:bg-black-2/20">
              <TableCell className="py-2 text-center">
                <div className="mx-auto flex flex-row gap-2 px-10 font-bold">
                  Informado ou Gerado:
                </div>
              </TableCell>
              <TableCell className="py-2 text-center" />
            </TableRow>

            {locks
              ?.filter((l) => !contatosArr.includes(Number(l.id_lock)))
              .map((lock, index) => (
                <TableRow key={`lock-geral-${index}`}>
                  <TableCell className="py-2 text-center">
                    {lock.nome_lock}
                  </TableCell>
                  <TableCell className="py-2 text-center">
                    <Input
                      name=""
                      checked={getArr(locksId, idTipoSel).some(
                        (id) => id == lock.id_lock,
                      )}
                      type="checkbox"
                      onChange={(e) =>
                        toggleInMap(
                          setLocksId,
                          idTipoSel,
                          String(lock.id_lock),
                          e.target.checked,
                        )
                      }
                    />
                  </TableCell>
                </TableRow>
              ))}
            <TableRow className="bg-[#f3f3f3] dark:bg-black-2/20">
              <TableCell className="py-2 text-center">
                <div className="mx-auto flex flex-row gap-2 px-10 font-bold">
                  Pendências de {tipoSelecionado?.nome_tipo_negocio}
                </div>
              </TableCell>
              <TableCell className="py-2 text-center" />
            </TableRow>

            {ordenadas?.map((lock: any) => {
              const isPendChecked = getArr(locksPendencias, idTipoSel).includes(
                String(lock.id_pendencia),
              );
              return (
                <TableRow key={`pend-${idTipoSel}-${lock.id_pendencia}`}>
                  <TableCell className="py-2 text-center">
                    {lock.nome_pendencia}
                  </TableCell>
                  <TableCell className="py-2 text-center justify-center">
                    <Input
                      name=""
                      checked={isPendChecked}
                      type="checkbox"
                      onChange={(e) =>
                        toggleInMap(
                          setLocksPendencias,
                          idTipoSel,
                          String(lock.id_pendencia),
                          e.target.checked,
                        )
                      }
                    />
                  </TableCell>
                </TableRow>
              );
            })}

            {naoPresentes?.length > 0 && (
              <>
                <TableRow className="bg-[#f3f3f3] dark:bg-black-2/20">
                  <TableCell className="py-2 text-center">
                    <div className="mx-auto flex flex-row gap-2 px-10 font-bold">
                      Pendências de {tipoSelecionado?.nome_tipo_negocio}{" "}
                      <span className="text-error">Não Habilitadas</span>
                    </div>
                  </TableCell>
                  <TableCell className="py-2 text-center" />
                </TableRow>
                {naoPresentes?.map((lock: any) => (
                  <TableRow key={`pend-na-${idTipoSel}-${lock.id_pendencia}`}>
                    <TableCell className="py-2 text-center">
                      {lock.nome_pendencia}
                    </TableCell>
                    <TableCell className="py-2 text-center">
                      <Input
                        name=""
                        checked={getArr(locksPendencias, idTipoSel)?.some(
                          (id) => id == lock.id_pendencia,
                        )}
                        type="checkbox"
                        onChange={(e) =>
                          toggleInMap(
                            setLocksPendencias,
                            idTipoSel,
                            String(lock.id_pendencia),
                            e.target.checked,
                          )
                        }
                      />
                    </TableCell>
                  </TableRow>
                ))}
              </>
            )}
            <TableRow className="bg-[#f3f3f3] dark:bg-black-2/20">
              <TableCell className="py-2 text-center">
                <div className="mx-auto flex flex-row gap-2 px-10 font-bold text-success">
                  Nesta Etapa Bloquear o Retrocesso se já houver:
                </div>
              </TableCell>
              <TableCell className="py-2 text-center" />
            </TableRow>

            {retrocessos?.map((lock: any, index: any) => (
              <TableRow key={`lock-retro-${index}`}>
                <TableCell className="py-2 text-center">
                  {lock.nome_lock_retrocesso}
                </TableCell>
                <TableCell className="py-2 text-center">
                  <Input
                    name=""
                    checked={getArr(locksRetrocessoId, idTipoSel)?.some(
                      (id: any) => id == lock.id_lock_retrocesso,
                    )}
                    type="checkbox"
                    onChange={(e) =>
                      toggleInMap(
                        setLocksRetrocessoId,
                        idTipoSel,
                        String(lock.id_lock_retrocesso),
                        e.target.checked,
                      )
                    }
                  />
                </TableCell>
              </TableRow>
            ))}

            <TableRow className="bg-[#f3f3f3] dark:bg-black-2/20">
              <TableCell className="py-2 text-center">
                <div className="mx-auto flex flex-row gap-2 px-10 font-bold">
                  Anexos:
                </div>
              </TableCell>
              <TableCell className="py-2 text-center" />
            </TableRow>
            {categoriasAnexos?.map((anexo: any) => (
              <TableRow key={`anexo-${idTipoSel}-${anexo.id_anexo_crm}`}>
                <TableCell className="py-2 text-center">
                  {anexo.identificacao_cfg_anexo}
                </TableCell>
                <TableCell className="py-2 text-center">
                  <Input
                    name=""
                    checked={getArr(locksAnexos, idTipoSel)?.some(
                      (id) => id == anexo.id_anexo_crm,
                    )}
                    type="checkbox"
                    onChange={(e) =>
                      toggleInMap(
                        setLocksAnexos,
                        idTipoSel,
                        String(anexo.id_anexo_crm),
                        e.target.checked,
                      )
                    }
                  />
                </TableCell>
              </TableRow>
            ))}

            <TableRow className="bg-[#f3f3f3] dark:bg-black-2/20">
              <TableCell className="py-2 text-center">
                <div className="mx-auto flex flex-row gap-2 px-10 font-bold">
                  Documentos personalizados:
                </div>
              </TableCell>
              <TableCell className="py-2 text-center" />
            </TableRow>
            {docsDoTipo?.map((documento: any) => (
              <TableRow
                key={`doc-${idTipoSel}-${documento.id_documento_personalizado}`}
              >
                <TableCell className="py-2 text-center">
                  {documento.nome_documento_personalizado}
                </TableCell>
                <TableCell className="py-2 text-center">
                  <Input
                    name=""
                    checked={getArr(locksDocsPersonalizados, idTipoSel)?.some(
                      (id) => id == documento.id_documento_personalizado,
                    )}
                    type="checkbox"
                    onChange={(e) =>
                      toggleInMap(
                        setLocksDocsPersonalizados,
                        idTipoSel,
                        String(documento.id_documento_personalizado),
                        e.target.checked,
                      )
                    }
                  />
                </TableCell>
              </TableRow>
            ))}

            <TableRow className="bg-[#f3f3f3] dark:bg-black-2/20">
              <TableCell className="py-2 text-center">
                <div className="mx-auto flex flex-row gap-2 px-10 font-bold">
                  Campos personalizados:
                </div>
              </TableCell>
              <TableCell className="py-2 text-center" />
            </TableRow>
            {camposDoTipo?.map((campo: any) => (
              <TableRow
                key={`campo-${idTipoSel}-${campo.id_campo_personalizado}`}
              >
                <TableCell className="py-2 text-center">
                  {campo.nome_campo_personalizado}
                </TableCell>
                <TableCell className="py-2 text-center">
                  <Input
                    name=""
                    checked={getArr(locksCamposPersonalizados, idTipoSel)?.some(
                      (id) => id == campo.id_campo_personalizado,
                    )}
                    type="checkbox"
                    onChange={(e) =>
                      toggleInMap(
                        setLocksCamposPersonalizados,
                        idTipoSel,
                        String(campo.id_campo_personalizado),
                        e.target.checked,
                      )
                    }
                  />
                </TableCell>
              </TableRow>
            ))}

            {SecaoMoverEGerarPorTipo(idTipoSel)}
          </tbody>
        </Table>
      </>
    );
  };

  return (
    <>
      <div className="flex gap-2 mb-3 border-b border-gray-300 dark:border-gray-700">
        <button
          onClick={() => setActiveTab("gerais")}
          type="button"
          className={`px-4 py-2 ${
            activeTab === "gerais"
              ? "border-b-2 border-primary font-semibold"
              : "text-gray-500"
          }`}
        >
          Regras Comuns (P/Todos Tipos de Negócios)
        </button>
        <button
          type="button"
          onClick={() => setActiveTab("tipos")}
          className={`px-4 py-2 ${
            activeTab === "tipos"
              ? "border-b-2 border-primary font-semibold"
              : "text-gray-500"
          }`}
        >
          Regras por Tipo de Negócio
        </button>
      </div>

      {activeTab === "gerais" ? <AbaLocksGerais /> : <AbaTiposNegocios />}
    </>
  );
};

export default ConfiguracoesRegrasEtapa;
