"use client";

import { useState, useEffect, useRef } from "react";
import {
  Alert,
  Button,
  Card,
  Checkbox,
  Collapse,
  Empty,
  Form,
  Input,
  Modal,
  Select,
  Space,
  Spin,
  Tabs,
  Tooltip,
  Typography,
  message,
} from "antd";
import {
  GlobalOutlined,
  MenuOutlined,
  HomeOutlined,
  BulbOutlined,
  InfoCircleOutlined,
  PhoneOutlined,
  LayoutOutlined,
  AppstoreOutlined,
  CustomerServiceOutlined,
  DeleteOutlined,
  FileOutlined,
  PlusOutlined,
  ReloadOutlined,
  SaveOutlined,
} from "@ant-design/icons";
import AdminSidebar from "../components/AdminSidebar";
import AdminHeader from "../components/AdminHeader";
import GlobalConfig from "./sections/GlobalConfig";
import HeaderConfig from "./sections/HeaderConfig";
import FooterConfig from "./sections/FooterConfig";
import {
  STRAPI_URL,
  LEGACY_SITE_CONFIG_DOCUMENT_IDS,
  SITE_CONFIG_RESOURCES,
  createConfigDocument,
  createSiteConfigSet,
  fetchConfigDocument,
  listConfigDocuments,
  loadSiteConfigSets,
  saveSiteConfigSet,
  updateConfigDocument,
} from "./config-set-utils";

function getMediaId(media) {
  if (!media) {
    return null;
  }

  if (typeof media === "number") {
    return media;
  }

  return media?.id || media?.data?.id || null;
}

const { TextArea } = Input;
const { Text } = Typography;
const PAGES_POPULATE_QUERY = "populate[paginas][populate][sessoes]=true";
const AUTH_ME_ENDPOINTS = [
  `${STRAPI_URL}/api/auth/me`,
];

const ICON_DEFAULTS = {
  home: "<HomeOutlined />",
  solucoes: "<BulbOutlined />",
  servicos: "<AppstoreOutlined />",
  sobre: "<InfoCircleOutlined />",
  contato: "<PhoneOutlined />",
  sou_cliente: "<CustomerServiceOutlined />",
};

const ITEM_TYPE_OPTIONS = [
  { label: "TEXTO", value: "TEXTO" },
  { label: "NUMERO INTEIRO", value: "NUMERO INTEIRO" },
  { label: "NUMERO REAL", value: "NUMERO REAL" },
  { label: "DATA", value: "DATA" },
  { label: "COR", value: "COR" },
  { label: "URL", value: "URL" },
];

const ITEM_TYPE_TO_STORAGE = {
  TEXTO: "String",
  "NUMERO INTEIRO": "Integer",
  "NUMERO REAL": "Float",
  DATA: "Date",
  COR: "String",
  URL: "String",
};

const STORAGE_TO_ITEM_TYPE = {
  String: "TEXTO",
  Integer: "NUMERO INTEIRO",
  Float: "NUMERO REAL",
  Date: "DATA",
};

const ITEM_TYPE_EXAMPLES = {
  TEXTO: "Ex: Digite seu texto aqui",
  "NUMERO INTEIRO": "Ex: 2",
  "NUMERO REAL": "Ex: 1,1111",
  DATA: "Ex: 2026-03-17",
  COR: "Ex: #111111",
  URL: "Ex: https://exemplo.com",
};

function parseCommaSeparatedList(value) {
  return String(value || "")
    .split(/[\n,]/)
    .map((entry) => entry.trim())
    .filter(Boolean);
}

function buildKeywordComponents(value) {
  return parseCommaSeparatedList(value).map((keyword) => ({ keyword }));
}

function normalizeComponentList(entries, key) {
  if (!Array.isArray(entries)) {
    return [];
  }

  return entries
    .map((entry) => String(entry?.[key] || "").trim())
    .filter(Boolean);
}

function buildGoogleTagComponents(gtmId, customScripts) {
  const tags = [];

  if (String(gtmId || "").trim()) {
    tags.push({ tag: String(gtmId).trim() });
  }

  String(customScripts || "")
    .split(/\n+/)
    .map((entry) => entry.trim())
    .filter(Boolean)
    .forEach((tag) => {
      tags.push({ tag });
    });

  return tags;
}

function sortMenuItems(items) {
  return [...(items || [])].sort(
    (left, right) => Number(left?.order || 0) - Number(right?.order || 0),
  );
}

function mapFooterItemToLine(columnType, item) {
  if (columnType === "social") {
    return {
      titulo_botao: String(item?.name || "").trim(),
      url: String(item?.url || "").trim(),
    };
  }

  if (columnType === "contact") {
    return {
      titulo_botao: String(item?.type || "").trim(),
      url: String(item?.value || "").trim(),
    };
  }

  return {
    titulo_botao: String(item?.label || "").trim(),
    url: String(item?.href || "").trim(),
  };
}

async function fetchPagesDocument(documentId) {
  const data = await fetchConfigDocument("pages", documentId, {
    queryString: PAGES_POPULATE_QUERY,
  });

  if (!data) {
    throw new Error(
      "Configuracao de Paginas nao encontrada para o set atual. Se esse documento foi apagado no Strapi, selecione outro set ou crie um novo.",
    );
  }

  return {
    documentId: data?.documentId || documentId || "",
    paginas: Array.isArray(data?.paginas) ? data.paginas : [],
  };
}

async function saveGlobalDocument(documentId, data) {
  if (!documentId) {
    throw new Error("Nenhum documentId Global foi selecionado para salvar.");
  }

  const currentConfig = await fetchConfigDocument("global", documentId);

  return updateConfigDocument("global", documentId, {
    nome_empresa: data.companyName,
    slogan: data.slogan,
    cor_primaria: data.primaryColor,
    cor_secundaria: data.secondaryColor,
    cor_destaque: data.accentColor,
    background_col: currentConfig?.background_col || "",
    meta_title: data.metaTitle,
    meta_description: data.metaDescription,
    meta_keywords: buildKeywordComponents(data.metaKeywords),
    google_tags: buildGoogleTagComponents(data.gtmId, data.customScripts),
  });
}

async function saveHeaderDocument(documentId, data) {
  if (!documentId) {
    throw new Error("Nenhum documentId Header foi selecionado para salvar.");
  }

  const currentConfig = await fetchConfigDocument("header", documentId, {
    queryString: "populate=logo_aioware",
  });

  return updateConfigDocument("header", documentId, {
    texto_alt_logo: data.logoAlt,
    header_fixo: data.headerFixed,
    menu_mobile: data.showMobileMenu,
    logo_aioware: data.logoId || getMediaId(currentConfig?.logo_aioware),
    menu_botoes: sortMenuItems(data.menuItems).map((item) => ({
      nome: String(item?.label || "").trim(),
      url: String(item?.href || "").trim(),
      cor_botao: String(item?.buttonColor || "").trim(),
    })),
  });
}

async function saveFooterDocument(documentId, data) {
  if (!documentId) {
    throw new Error("Nenhum documentId Footer foi selecionado para salvar.");
  }

  return updateConfigDocument("footer", documentId, {
    titulo: data.newsletterTitle,
    subtitulo: data.newsletterSubtitle,
    texto: data.institutionalText,
    coluna: (data.columns || []).map((column) => ({
      titulo_coluna: String(column?.title || "").trim(),
      linha: (column?.items || [])
        .map((item) => mapFooterItemToLine(column?.type, item))
        .filter((line) => line.titulo_botao || line.url),
    })),
  });
}

async function savePagesDocument(documentId, paginas) {
  if (!documentId) {
    throw new Error(
      "Nenhum documentId de Paginas foi selecionado para salvar.",
    );
  }

  return updateConfigDocument("pages", documentId, { paginas });
}

function createLocalId(prefix) {
  return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
}

function slugify(value) {
  return (
    (value || "")
      .normalize("NFD")
      .replace(/[\u0300-\u036f]/g, "")
      .toLowerCase()
      .trim()
      .replace(/[^a-z0-9]+/g, "_")
      .replace(/^_+|_+$/g, "") || "nova_pagina"
  );
}

function normalizeItem(item) {
  return {
    name: item?.name || "",
    value: item?.value || "",
    tipo: item?.tipo || STORAGE_TO_ITEM_TYPE[item?.id] || "TEXTO",
  };
}

function sortGroupKeys(items) {
  return Object.keys(items || {}).sort(
    (left, right) => Number(left) - Number(right),
  );
}

function normalizeItems(items) {
  if (!items || typeof items !== "object" || Array.isArray(items)) {
    return {};
  }

  const normalized = {};

  sortGroupKeys(items).forEach((key, index) => {
    const entries = Array.isArray(items[key])
      ? items[key].map(normalizeItem)
      : [];
    normalized[String(index + 1)] = entries;
  });

  return normalized;
}

function normalizeSession(session) {
  const name = session?.nome || "";

  return {
    id: session?.id,
    localId: createLocalId("session"),
    nome: name,
    nome_id: session?.nome_id || slugify(name || "nova_sessao"),
    items: normalizeItems(session?.items),
  };
}

function normalizePage(page) {
  const name = page?.nome || "";
  const nomeId = page?.nome_id || slugify(name);

  return {
    id: page?.id,
    localId: createLocalId("page"),
    nome: name,
    icone: page?.icone || ICON_DEFAULTS[nomeId] || "",
    nome_id: nomeId,
    sessoes: Array.isArray(page?.sessoes)
      ? page.sessoes.map(normalizeSession)
      : [],
  };
}

function createEmptySession(index = 0) {
  const sessionNumber = index + 1;

  return {
    localId: createLocalId("session"),
    nome: `Nova Sessao ${sessionNumber}`,
    nome_id: `nova_sessao_${sessionNumber}`,
    items: {},
  };
}

function createEmptyItem() {
  return {
    name: "",
    value: "",
    tipo: "TEXTO",
  };
}

function createEmptyPage(index = 0) {
  const pageNumber = index + 1;
  const pageName = `Nova Pagina ${pageNumber}`;
  const firstSession = createEmptySession(0);

  return {
    localId: createLocalId("page"),
    nome: pageName,
    nome_id: slugify(pageName),
    icone: "<FileOutlined />",
    sessoes: [
      {
        ...firstSession,
        items: {
          1: [createEmptyItem()],
        },
      },
    ],
  };
}

function getItemTypeExample(tipo) {
  return ITEM_TYPE_EXAMPLES[tipo] || ITEM_TYPE_EXAMPLES.TEXTO;
}

function clonePages(pages) {
  return pages.map((page) => ({
    ...page,
    sessoes: page.sessoes.map((session) => ({
      ...session,
      items: Object.fromEntries(
        Object.entries(session.items || {}).map(([groupKey, entries]) => [
          groupKey,
          (entries || []).map((entry) => ({ ...entry })),
        ]),
      ),
    })),
  }));
}

function serializePages(pages) {
  return pages.map((page) => ({
    nome: (page.nome || "").trim(),
    nome_id: (page.nome_id || "").trim() || slugify(page.nome),
    icone: (page.icone || "").trim(),
    sessoes: page.sessoes.map((session) => {
      const groupedItems = {};

      sortGroupKeys(session.items).forEach((groupKey) => {
        const validEntries = (session.items[groupKey] || [])
          .map((entry) => ({
            name: (entry?.name || "").trim(),
            value: (entry?.value || "").trim(),
            id: ITEM_TYPE_TO_STORAGE[entry?.tipo] || "String",
          }))
          .filter((entry) => entry.name || entry.value);

        if (validEntries.length) {
          groupedItems[String(Object.keys(groupedItems).length + 1)] =
            validEntries;
        }
      });

      return {
        nome: (session.nome || "").trim(),
        nome_id: (session.nome_id || "").trim() || slugify(session.nome),
        items: groupedItems,
      };
    }),
  }));
}

function buildPageIcon(page) {
  const iconValue = page?.icone || "";

  if (iconValue.includes("HomeOutlined")) return <HomeOutlined />;
  if (iconValue.includes("BulbOutlined")) return <BulbOutlined />;
  if (iconValue.includes("AppstoreOutlined")) return <AppstoreOutlined />;
  if (iconValue.includes("InfoCircleOutlined")) return <InfoCircleOutlined />;
  if (iconValue.includes("PhoneOutlined")) return <PhoneOutlined />;
  if (iconValue.includes("CustomerServiceOutlined"))
    return <CustomerServiceOutlined />;

  switch (page?.nome_id) {
    case "home":
      return <HomeOutlined />;
    case "solucoes":
      return <BulbOutlined />;
    case "servicos":
      return <AppstoreOutlined />;
    case "sobre":
      return <InfoCircleOutlined />;
    case "contato":
      return <PhoneOutlined />;
    case "sou_cliente":
      return <CustomerServiceOutlined />;
    default:
      return <FileOutlined />;
  }
}

function getDeletionTargetLabel(target) {
  if (target?.type === "page") {
    return "esta pagina";
  }

  if (target?.type === "session") {
    return "esta sessao";
  }

  if (target?.type === "group") {
    return "este grupo";
  }

  return "este item";
}

function createConfigSetOptionLabel(configSet) {
  const ids = [
    configSet?.globalDocumentId,
    configSet?.headerDocumentId,
    configSet?.footerDocumentId,
    configSet?.pagesDocumentId,
  ]
    .filter(Boolean)
    .map((value) => String(value).slice(0, 8))
    .join(" / ");

  return ids
    ? `${configSet?.name || "Configuracao"} (${ids})`
    : configSet?.name || "Configuracao";
}

function buildDefaultGlobalData() {
  return {
    nome_empresa: "AIOWARE",
    slogan: "Solucoes em Tecnologia",
    cor_primaria: "#0071C5",
    cor_secundaria: "#222864",
    cor_destaque: "#0094D9",
    background_col: "#ffffff",
    meta_title: "Aioware - Solucoes em Tecnologia",
    meta_description: "Aioware - Solucoes em Tecnologia",
    meta_keywords: [],
    google_tags: [],
  };
}

function buildDefaultHeaderData() {
  return {
    texto_alt_logo: "Logo AIOWARE",
    header_fixo: true,
    menu_mobile: true,
    menu_botoes: [],
  };
}

function buildDefaultFooterData() {
  return {
    titulo: "Novidade a caminho!",
    subtitulo: "Em breve voce podera receber noticias.",
    texto:
      "Conheca o suporte da AIOWARE e veja como podemos agregar nosso conhecimento tecnico para levar o seu negocio a um novo patamar",
    coluna: [],
  };
}

function buildDefaultPagesData() {
  return {
    paginas: [],
  };
}

export default function SiteConfigInterface() {
  const [activeTab, setActiveTab] = useState("global");
  const [userRole, setUserRole] = useState(null);
  const [configSets, setConfigSets] = useState([]);
  const [activeConfigSetId, setActiveConfigSetId] = useState("");
  const [configSetLoading, setConfigSetLoading] = useState(true);
  const [configSetSubmitting, setConfigSetSubmitting] = useState(false);
  const [configSetModalOpen, setConfigSetModalOpen] = useState(false);
  const [configSetError, setConfigSetError] = useState("");
  const [pagesLoading, setPagesLoading] = useState(true);
  const [savingConfig, setSavingConfig] = useState(false);
  const [pagesError, setPagesError] = useState("");
  const [pagesDocumentId, setPagesDocumentId] = useState("");
  const [pages, setPages] = useState([]);
  const pagesRef = useRef([]);
  const [hasPendingChanges, setHasPendingChanges] = useState(false);
  const [deletePagesModalOpen, setDeletePagesModalOpen] = useState(false);
  const [selectedPagesToDelete, setSelectedPagesToDelete] = useState([]);
  const [deletePagesSubmitting, setDeletePagesSubmitting] = useState(false);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [deleteIdentifier, setDeleteIdentifier] = useState("");
  const [deletePassword, setDeletePassword] = useState("");
  const [deleteSubmitting, setDeleteSubmitting] = useState(false);
  const [deleteError, setDeleteError] = useState("");
  const [pendingDeletion, setPendingDeletion] = useState(null);
  const [configSetForm] = Form.useForm();
  const globalConfigRef = useRef(null);
  const headerConfigRef = useRef(null);
  const footerConfigRef = useRef(null);
  const baselineSnapshotHashRef = useRef("");
  const dirtyCheckTimerRef = useRef(null);
  const baselineBootstrapTimerRef = useRef(null);
  const dirtyTrackingSuspendedRef = useRef(false);
  const handleAnyConfigDraftChangeRef = useRef(null);
  const handleAnyConfigDraftChangeStableRef = useRef(() => {
    handleAnyConfigDraftChangeRef.current?.();
  });
  const activeConfigSet =
    configSets.find((configSet) => configSet.id === activeConfigSetId) || null;

  function persistConfigSets(nextSets, nextActiveSetId) {
    setConfigSets(nextSets);
    setActiveConfigSetId(nextActiveSetId || "");
  }

  //29/05/2024: Tenta detectar automaticamente os documentos de configuração existentes no banco
  // 1. listar os documentos existentes de cada tipo;
  // 2. pegar o primeiro `documentId` encontrado;
  // 3. montar um set automaticamente;
  // 4. usar os IDs legados apenas se nao conseguir detectar.
  async function buildDetectedConfigSet() {
    try {
      const [globals, headers, footers, pagesDocs] = await Promise.all([
        listConfigDocuments("global"),
        listConfigDocuments("header"),
        listConfigDocuments("footer"),
        listConfigDocuments("pages"),
      ]);

      const detectedIds = {
        globalDocumentId:
          globals[0]?.documentId ||
          LEGACY_SITE_CONFIG_DOCUMENT_IDS.globalDocumentId,
        headerDocumentId:
          headers[0]?.documentId ||
          LEGACY_SITE_CONFIG_DOCUMENT_IDS.headerDocumentId,
        footerDocumentId:
          footers[0]?.documentId ||
          LEGACY_SITE_CONFIG_DOCUMENT_IDS.footerDocumentId,
        pagesDocumentId:
          pagesDocs[0]?.documentId ||
          LEGACY_SITE_CONFIG_DOCUMENT_IDS.pagesDocumentId,
      };

      return createSiteConfigSet({
        name: "Configuracao detectada",
        ...detectedIds,
      });
    } catch (error) {
      console.warn(
        "[site-config] Nao consegui detectar documentos automaticamente:",
        error,
      );

      return createSiteConfigSet({
        name: "Configuracao legada",
        ...LEGACY_SITE_CONFIG_DOCUMENT_IDS,
      });
    }
  }

  async function bootstrapConfigSets() {
    setConfigSetLoading(true);

    try {
      const savedState = await loadSiteConfigSets();

      if (savedState.sets.length) {
        const fallbackActiveSetId = savedState.sets[0]?.id || "";
        const nextActiveSetId = savedState.sets.find(
          (setItem) => setItem.id === savedState.activeSetId,
        )
          ? savedState.activeSetId
          : fallbackActiveSetId;

        persistConfigSets(savedState.sets, nextActiveSetId);
        return;
      }

      const detectedSet = await buildDetectedConfigSet();
      const savedSet = await saveSiteConfigSet(detectedSet);
      persistConfigSets([savedSet], savedSet.id);
    } catch (error) {
      console.warn(
        "[site-config] Nao consegui carregar/salvar Site_Cofig:",
        error,
      );
      const detectedSet = await buildDetectedConfigSet();
      persistConfigSets([detectedSet], detectedSet.id);
      setConfigSetError(
        error.message ||
          "Nao foi possivel carregar o Site_Cofig no backend.",
      );
    } finally {
      setConfigSetLoading(false);
    }
  }

  async function handleCreateConfigSet() {
    try {
      setConfigSetSubmitting(true);

      // Criamos o set inteiro de uma vez para nao cair de novo no fluxo antigo
      // de "salvar em um documentId fixo que nao existe nesse banco".
      const [globalEntry, headerEntry, footerEntry, pagesEntry] =
        await Promise.all([
          createConfigDocument("global", buildDefaultGlobalData()),
          createConfigDocument("header", buildDefaultHeaderData()),
          createConfigDocument("footer", buildDefaultFooterData()),
          createConfigDocument("pages", buildDefaultPagesData()),
        ]);

      const nextSet = createSiteConfigSet({
        name: `Novo set ${new Date().toLocaleString("pt-BR")}`,
        globalDocumentId: globalEntry?.documentId || "",
        headerDocumentId: headerEntry?.documentId || "",
        footerDocumentId: footerEntry?.documentId || "",
        pagesDocumentId: pagesEntry?.documentId || "",
      });
      const savedSet = await saveSiteConfigSet(nextSet);

      const nextSets = [
        savedSet,
        ...configSets.filter((setItem) => setItem.id !== savedSet.id),
      ];
      persistConfigSets(nextSets, savedSet.id);
      message.success("Novo set de configuracao criado com sucesso.");
    } catch (error) {
      message.error(
        error.message || "Nao foi possivel criar um novo set de configuracao.",
      );
    } finally {
      setConfigSetSubmitting(false);
    }
  }

  function openExistingConfigModal() {
    const initialValues = activeConfigSet || {
      name: "",
      ...LEGACY_SITE_CONFIG_DOCUMENT_IDS,
    };

    configSetForm.setFieldsValue({
      name: initialValues.name || "",
      globalDocumentId: initialValues.globalDocumentId || "",
      headerDocumentId: initialValues.headerDocumentId || "",
      footerDocumentId: initialValues.footerDocumentId || "",
      pagesDocumentId: initialValues.pagesDocumentId || "",
    });

    setConfigSetError("");
    setConfigSetModalOpen(true);
  }

  async function handleSaveExistingConfigSet() {
    try {
      setConfigSetSubmitting(true);
      setConfigSetError("");
      const values = await configSetForm.validateFields();

      // Antes de gravar o set, validamos se os quatro documentIds realmente
      // respondem no backend. Isso evita salvar um conjunto "bonito" na UI
      // que depois falha inteiro por apontar para documentos inexistentes.
      const [globalDoc, headerDoc, footerDoc, pagesDoc] = await Promise.all([
        fetchConfigDocument("global", values.globalDocumentId),
        fetchConfigDocument("header", values.headerDocumentId, {
          queryString: "populate=logo_aioware",
        }),
        fetchConfigDocument("footer", values.footerDocumentId),
        fetchConfigDocument("pages", values.pagesDocumentId, {
          queryString: PAGES_POPULATE_QUERY,
        }),
      ]);

      if (!globalDoc || !headerDoc || !footerDoc || !pagesDoc) {
        throw new Error(
          "Um ou mais documentIds informados nao existem ou nao estao acessiveis para este usuario.",
        );
      }

      const nextSet = createSiteConfigSet({
        name: values.name || "Configuracao manual",
        globalDocumentId: values.globalDocumentId,
        headerDocumentId: values.headerDocumentId,
        footerDocumentId: values.footerDocumentId,
        pagesDocumentId: values.pagesDocumentId,
      });

      const duplicatedSet = configSets.find(
        (setItem) =>
          setItem.globalDocumentId === nextSet.globalDocumentId &&
          setItem.headerDocumentId === nextSet.headerDocumentId &&
          setItem.footerDocumentId === nextSet.footerDocumentId &&
          setItem.pagesDocumentId === nextSet.pagesDocumentId,
      );

      const savedSet = duplicatedSet || (await saveSiteConfigSet(nextSet));
      const nextSets = duplicatedSet ? configSets : [...configSets, savedSet];
      const targetSetId = savedSet.id;

      persistConfigSets(nextSets, targetSetId);
      setConfigSetModalOpen(false);
      message.success("Set de configuracao salvo com sucesso.");
    } catch (error) {
      if (!error?.errorFields) {
        setConfigSetError(
          error.message ||
            "Nao foi possivel validar os documentIds informados.",
        );
      }
    } finally {
      setConfigSetSubmitting(false);
    }
  }

  useEffect(() => {
    const fetchUserRole = async () => {
      try {
        let res = null;

        for (const endpoint of AUTH_ME_ENDPOINTS) {
          const currentResponse = await fetch(endpoint, {
            credentials: "include",
            cache: "no-store",
          });

          if (currentResponse.ok) {
            res = currentResponse;
            break;
          }
        }

        if (res?.ok) {
          const data = await res.json();
          const roleName =
            data.user?.role?.name ||
            data.role?.name ||
            data.role ||
            "administrator";
          setUserRole(roleName);
        } else {
          setUserRole("administrator");
        }
      } catch (error) {
        console.error("Erro ao buscar role do usuário:", error);
        setUserRole("administrator");
      }
    };

    fetchUserRole();
  }, []);

  useEffect(() => {
    bootstrapConfigSets();
  }, []);

  useEffect(() => {
    if (configSetLoading) {
      return;
    }

    baselineSnapshotHashRef.current = "";
    setHasPendingChanges(false);
    setPages([]);
    pagesRef.current = [];
    setPagesDocumentId(activeConfigSet?.pagesDocumentId || "");

    if (!activeConfigSet?.pagesDocumentId) {
      setPagesLoading(false);
      setPagesError(
        "Selecione um set de configuracao valido para carregar as paginas.",
      );
      return;
    }

    loadPages(activeConfigSet.pagesDocumentId);
  }, [activeConfigSet?.id, activeConfigSet?.pagesDocumentId, configSetLoading]);

  useEffect(() => {
    pagesRef.current = pages;
  }, [pages]);

  useEffect(() => {
    return () => {
      if (dirtyCheckTimerRef.current) {
        clearTimeout(dirtyCheckTimerRef.current);
      }

      if (baselineBootstrapTimerRef.current) {
        clearTimeout(baselineBootstrapTimerRef.current);
      }
    };
  }, []);

  async function loadPages(documentId) {
    if (!documentId) {
      setPagesDocumentId("");
      setPages([]);
      pagesRef.current = [];
      setPagesLoading(false);
      return;
    }

    try {
      setPagesLoading(true);
      setPagesError("");
      const payload = await fetchPagesDocument(documentId);
      const normalizedPages = Array.isArray(payload?.paginas)
        ? payload.paginas.map(normalizePage)
        : [];

      setPagesDocumentId(payload?.documentId || documentId);
      pagesRef.current = normalizedPages;
      setPages(normalizedPages);
    } catch (error) {
      setPagesError(error.message || "Erro ao carregar páginas dinâmicas");
    } finally {
      setPagesLoading(false);
      scheduleBaselineBootstrap();
    }
  }

  function normalizeValue(value) {
    return String(value ?? "").trim();
  }

  function normalizeColorValue(value) {
    if (
      value &&
      typeof value === "object" &&
      typeof value.toHexString === "function"
    ) {
      return value.toHexString();
    }

    return normalizeValue(value);
  }

  function normalizeGlobalSnapshot(values) {
    return {
      companyName: normalizeValue(values?.companyName),
      slogan: normalizeValue(values?.slogan),
      primaryColor: normalizeColorValue(values?.primaryColor),
      secondaryColor: normalizeColorValue(values?.secondaryColor),
      accentColor: normalizeColorValue(values?.accentColor),
      metaTitle: normalizeValue(values?.metaTitle),
      metaDescription: normalizeValue(values?.metaDescription),
      metaKeywords: normalizeValue(values?.metaKeywords),
      gtmId: normalizeValue(values?.gtmId),
      customScripts: normalizeValue(values?.customScripts),
    };
  }

  function normalizeHeaderSnapshot(values) {
    const menuItems = Array.isArray(values?.menuItems) ? values.menuItems : [];

    return {
      logoAlt: normalizeValue(values?.logoAlt),
      headerFixed: Boolean(values?.headerFixed),
      showMobileMenu: Boolean(values?.showMobileMenu),
      logoId: Number(values?.logoId || 0) || 0,
      menuItems: menuItems
        .map((item, index) => ({
          label: normalizeValue(item?.label),
          href: normalizeValue(item?.href),
          buttonColor: normalizeValue(item?.buttonColor),
          order: Number(item?.order || index + 1),
        }))
        .sort(
          (left, right) =>
            left.order - right.order || left.label.localeCompare(right.label),
        ),
    };
  }

  function normalizeFooterItem(type, item) {
    if (type === "social") {
      return {
        name: normalizeValue(item?.name),
        url: normalizeValue(item?.url),
      };
    }

    if (type === "contact") {
      return {
        type: normalizeValue(item?.type),
        value: normalizeValue(item?.value),
      };
    }

    return {
      label: normalizeValue(item?.label),
      href: normalizeValue(item?.href),
    };
  }

  function normalizeFooterSnapshot(values) {
    const columns = Array.isArray(values?.columns) ? values.columns : [];

    return {
      newsletterTitle: normalizeValue(values?.newsletterTitle),
      newsletterSubtitle: normalizeValue(values?.newsletterSubtitle),
      institutionalText: normalizeValue(values?.institutionalText),
      columns: columns.map((column) => {
        const type = normalizeValue(column?.type) || "links";
        const items = Array.isArray(column?.items) ? column.items : [];

        return {
          title: normalizeValue(column?.title),
          type,
          items: items.map((item) => normalizeFooterItem(type, item)),
        };
      }),
    };
  }

  function buildSnapshotHash(snapshot) {
    return JSON.stringify(snapshot);
  }

  function buildNormalizedSnapshot(
    globalValues,
    headerValues,
    footerValues,
    nextPages = pagesRef.current,
  ) {
    return {
      global: normalizeGlobalSnapshot(globalValues || {}),
      header: normalizeHeaderSnapshot(headerValues || {}),
      footer: normalizeFooterSnapshot(footerValues || {}),
      pages: serializePages(nextPages || []),
    };
  }

  async function collectCurrentSnapshot() {
    const globalGetter = globalConfigRef.current?.getDraftValues;
    const headerGetter = headerConfigRef.current?.getDraftValues;
    const footerGetter = footerConfigRef.current?.getDraftValues;

    if (!globalGetter || !headerGetter || !footerGetter) {
      return null;
    }

    try {
      const [globalValues, headerValues, footerValues] = await Promise.all([
        Promise.resolve(globalGetter()),
        Promise.resolve(headerGetter()),
        Promise.resolve(footerGetter()),
      ]);

      return buildNormalizedSnapshot(
        globalValues,
        headerValues,
        footerValues,
        pagesRef.current,
      );
    } catch {
      return null;
    }
  }

  async function applyCurrentSnapshotAsBaseline() {
    const snapshot = await collectCurrentSnapshot();

    if (!snapshot) {
      return false;
    }

    baselineSnapshotHashRef.current = buildSnapshotHash(snapshot);
    setHasPendingChanges(false);
    return true;
  }

  async function recalculatePendingChanges() {
    if (dirtyTrackingSuspendedRef.current || !baselineSnapshotHashRef.current) {
      return;
    }

    const snapshot = await collectCurrentSnapshot();
    if (!snapshot) {
      return;
    }

    const currentHash = buildSnapshotHash(snapshot);
    setHasPendingChanges(currentHash !== baselineSnapshotHashRef.current);
  }

  function schedulePendingChangesRecalc(delay = 120) {
    if (dirtyTrackingSuspendedRef.current) {
      return;
    }

    if (dirtyCheckTimerRef.current) {
      clearTimeout(dirtyCheckTimerRef.current);
    }

    dirtyCheckTimerRef.current = setTimeout(() => {
      recalculatePendingChanges();
    }, delay);
  }

  function scheduleBaselineBootstrap() {
    if (baselineSnapshotHashRef.current) {
      return;
    }

    if (baselineBootstrapTimerRef.current) {
      clearTimeout(baselineBootstrapTimerRef.current);
    }

    baselineBootstrapTimerRef.current = setTimeout(async () => {
      const baselineSet = await applyCurrentSnapshotAsBaseline();
      if (!baselineSet) {
        scheduleBaselineBootstrap();
      }
    }, 200);
  }

  handleAnyConfigDraftChangeRef.current = () => {
    if (dirtyTrackingSuspendedRef.current) {
      return;
    }

    if (!baselineSnapshotHashRef.current) {
      scheduleBaselineBootstrap();
      return;
    }

    schedulePendingChangesRecalc();
  };

  const handleAnyConfigDraftChange = handleAnyConfigDraftChangeStableRef.current;

  function updatePages(updater) {
    setPages((currentPages) => {
      const nextPages = clonePages(currentPages);
      const updatedPages = updater(nextPages);
      pagesRef.current = updatedPages;
      schedulePendingChangesRecalc();
      return updatedPages;
    });
  }

  function updatePageField(pageId, field, value) {
    updatePages((nextPages) => {
      const page = nextPages.find((entry) => entry.localId === pageId);
      if (page) {
        page[field] = value;
      }
      return nextPages;
    });
  }

  function updateSessionField(pageId, sessionId, field, value) {
    updatePages((nextPages) => {
      const page = nextPages.find((entry) => entry.localId === pageId);
      const session = page?.sessoes.find(
        (entry) => entry.localId === sessionId,
      );
      if (session) {
        session[field] = value;
      }
      return nextPages;
    });
  }

  function updateItemEntry(
    pageId,
    sessionId,
    groupKey,
    itemIndex,
    field,
    value,
  ) {
    updatePages((nextPages) => {
      const page = nextPages.find((entry) => entry.localId === pageId);
      const session = page?.sessoes.find(
        (entry) => entry.localId === sessionId,
      );
      const item = session?.items?.[groupKey]?.[itemIndex];

      if (item) {
        item[field] = value;
      }

      return nextPages;
    });
  }

  function addSession(pageId) {
    updatePages((nextPages) => {
      const page = nextPages.find((entry) => entry.localId === pageId);

      if (page) {
        page.sessoes.push(createEmptySession(page.sessoes.length));
      }

      return nextPages;
    });
  }

  function addPage() {
    const nextPage = createEmptyPage(pagesRef.current.length);

    setPages((currentPages) => {
      const updatedPages = [...clonePages(currentPages), nextPage];
      pagesRef.current = updatedPages;
      return updatedPages;
    });
    setActiveTab(nextPage.localId);
    schedulePendingChangesRecalc();
  }

  function openDeletePagesModal() {
    setSelectedPagesToDelete([]);
    setDeletePagesModalOpen(true);
  }

  function closeDeletePagesModal() {
    if (deletePagesSubmitting) {
      return;
    }

    setDeletePagesModalOpen(false);
    setSelectedPagesToDelete([]);
  }

  function addItemGroup(pageId, sessionId) {
    updatePages((nextPages) => {
      const page = nextPages.find((entry) => entry.localId === pageId);
      const session = page?.sessoes.find(
        (entry) => entry.localId === sessionId,
      );

      if (session) {
        const nextGroupKey = String(sortGroupKeys(session.items).length + 1);
        session.items[nextGroupKey] = [createEmptyItem()];
      }

      return nextPages;
    });
  }

  function addItemEntry(pageId, sessionId, groupKey) {
    updatePages((nextPages) => {
      const page = nextPages.find((entry) => entry.localId === pageId);
      const session = page?.sessoes.find(
        (entry) => entry.localId === sessionId,
      );

      if (session?.items?.[groupKey]) {
        session.items[groupKey].push(createEmptyItem());
      }

      return nextPages;
    });
  }

  function deleteItemEntry(pageId, sessionId, groupKey, itemIndex) {
    updatePages((nextPages) => {
      const page = nextPages.find((entry) => entry.localId === pageId);
      const session = page?.sessoes.find(
        (entry) => entry.localId === sessionId,
      );
      const groupItems = session?.items?.[groupKey];

      if (Array.isArray(groupItems)) {
        session.items[groupKey] = groupItems.filter(
          (_, currentIndex) => currentIndex !== itemIndex,
        );
      }

      return nextPages;
    });
  }

  function deleteSession(pageId, sessionId) {
    updatePages((nextPages) => {
      const page = nextPages.find((entry) => entry.localId === pageId);

      if (page) {
        page.sessoes = page.sessoes.filter(
          (entry) => entry.localId !== sessionId,
        );
      }

      return nextPages;
    });
  }

  function deleteItemGroup(pageId, sessionId, groupKey) {
    updatePages((nextPages) => {
      const page = nextPages.find((entry) => entry.localId === pageId);
      const session = page?.sessoes.find(
        (entry) => entry.localId === sessionId,
      );

      if (session?.items?.[groupKey]) {
        const remainingGroups = sortGroupKeys(session.items)
          .filter((currentGroupKey) => currentGroupKey !== groupKey)
          .map((currentGroupKey) => session.items[currentGroupKey]);

        session.items = Object.fromEntries(
          remainingGroups.map((entries, index) => [String(index + 1), entries]),
        );
      }

      return nextPages;
    });
  }

  function deletePage(pageId) {
    setPages((currentPages) => {
      const updatedPages = currentPages.filter(
        (page) => page.localId !== pageId,
      );
      pagesRef.current = updatedPages;
      return updatedPages;
    });
    setActiveTab((currentTab) =>
      currentTab === pageId ? "global" : currentTab,
    );
    schedulePendingChangesRecalc();
  }

  async function handleDeleteSelectedPages() {
    if (!selectedPagesToDelete.length) {
      message.warning("Selecione pelo menos uma pagina para deletar.");
      return;
    }

    if (!pagesDocumentId) {
      message.error("documentId do c-pages nao encontrado.");
      return;
    }

    if (hasPendingChanges) {
      message.warning(
        "Você precisa salvar primeiro as configurações para poder deletar paginas.",
      );
      return;
    }

    const selectedIds = new Set(selectedPagesToDelete);

    Modal.confirm({
      title: "Confirmar exclusao",
      content:
        "Todas as configuracoes feitas nas paginas selecionadas serao deletadas, tem certeza que quer deletar?",
      okText: "Sim",
      cancelText: "Não",
      okButtonProps: { danger: true },
      centered: true,
      async onOk() {
        try {
          dirtyTrackingSuspendedRef.current = true;
          setDeletePagesSubmitting(true);
          const remainingPages = pages.filter(
            (page) => !selectedIds.has(page.localId),
          );
          const deletedCount = pages.length - remainingPages.length;
          const currentGlobalValues = await Promise.resolve(
            globalConfigRef.current?.getDraftValues?.(),
          );
          const currentHeaderValues = await Promise.resolve(
            headerConfigRef.current?.getDraftValues?.(),
          );
          const currentFooterValues = await Promise.resolve(
            footerConfigRef.current?.getDraftValues?.(),
          );

          await savePagesDocument(
            pagesDocumentId,
            serializePages(remainingPages),
          );
          baselineSnapshotHashRef.current = buildSnapshotHash(
            buildNormalizedSnapshot(
              currentGlobalValues,
              currentHeaderValues,
              currentFooterValues,
              remainingPages,
            ),
          );
          setHasPendingChanges(false);
          setPages(remainingPages);

          if (selectedIds.has(activeTab)) {
            setActiveTab("global");
          }

          setDeletePagesModalOpen(false);
          setSelectedPagesToDelete([]);
          message.success(`${deletedCount} pagina(s) deletada(s) com sucesso.`);
          await loadPages(pagesDocumentId);
          await applyCurrentSnapshotAsBaseline();
        } catch (error) {
          message.error(
            error.message || "Erro ao deletar paginas selecionadas.",
          );
          throw error;
        } finally {
          dirtyTrackingSuspendedRef.current = false;
          setDeletePagesSubmitting(false);
        }
      },
    });
  }

  function requestDeletion(target) {
    if (target?.type === "item") {
      deleteItemEntry(
        target.pageId,
        target.sessionId,
        target.groupKey,
        target.itemIndex,
      );
      return;
    }

    setPendingDeletion(target);
    setDeleteIdentifier("");
    setDeletePassword("");
    setDeleteError("");
    setDeleteModalOpen(true);
  }

  function closeDeleteModal() {
    if (deleteSubmitting) {
      return;
    }

    setDeleteModalOpen(false);
    setDeleteError("");
    setPendingDeletion(null);
  }

  async function handleConfirmDeletion() {
    if (!pendingDeletion) {
      return;
    }

    if (!deleteIdentifier.trim() || !deletePassword) {
      setDeleteError("Informe login e senha para confirmar a exclusao.");
      return;
    }

    try {
      setDeleteSubmitting(true);
      setDeleteError("");

      const response = await fetch(`${STRAPI_URL}/api/auth/local`, {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          identifier: deleteIdentifier.trim(),
          password: deletePassword,
        }),
      });

      const payload = await response.json().catch(() => null);

      if (!response.ok) {
        throw new Error(
          payload?.error?.message || payload?.error?.name || "Login invalido",
        );
      }

      if (pendingDeletion.type === "page") {
        deletePage(pendingDeletion.pageId);
      }

      if (pendingDeletion.type === "session") {
        deleteSession(pendingDeletion.pageId, pendingDeletion.sessionId);
      }

      if (pendingDeletion.type === "group") {
        deleteItemGroup(
          pendingDeletion.pageId,
          pendingDeletion.sessionId,
          pendingDeletion.groupKey,
        );
      }

      if (pendingDeletion.type === "item") {
        deleteItemEntry(
          pendingDeletion.pageId,
          pendingDeletion.sessionId,
          pendingDeletion.groupKey,
          pendingDeletion.itemIndex,
        );
      }

      setDeleteModalOpen(false);
      setPendingDeletion(null);
      setDeleteIdentifier("");
      setDeletePassword("");
      message.success("Exclusao confirmada com sucesso.");
    } catch (error) {
      setDeleteError(
        error.message || "Nao foi possivel validar o login para exclusao.",
      );
    } finally {
      setDeleteSubmitting(false);
    }
  }

  async function handleReloadAll() {
    await Promise.allSettled([
      globalConfigRef.current?.reloadConfig?.(),
      headerConfigRef.current?.reloadConfig?.(),
      footerConfigRef.current?.reloadConfig?.(),
      loadPages(activeConfigSet?.pagesDocumentId || pagesDocumentId),
    ]);
  }

  async function handleSaveAll() {
    if (!pagesDocumentId) {
      message.error("documentId do c-pages não encontrado.");
      return;
    }

    try {
      const [globalValues, headerValues, footerValues] = await Promise.all([
        globalConfigRef.current?.getConfigValues?.(),
        headerConfigRef.current?.getConfigValues?.(),
        footerConfigRef.current?.getConfigValues?.(),
      ]);

      if (!globalValues || !headerValues || !footerValues) {
        message.error("Os formularios ainda nao estao prontos para salvar.");
        return;
      }

      dirtyTrackingSuspendedRef.current = true;
      setSavingConfig(true);
      const currentPages = pagesRef.current;
      const serializedPages = serializePages(currentPages);
      const savedSnapshotHash = buildSnapshotHash(
        buildNormalizedSnapshot(
          globalValues,
          headerValues,
          footerValues,
          currentPages,
        ),
      );

      await saveGlobalDocument(activeConfigSet?.globalDocumentId, globalValues);
      await saveHeaderDocument(activeConfigSet?.headerDocumentId, headerValues);
      await saveFooterDocument(activeConfigSet?.footerDocumentId, footerValues);
      await savePagesDocument(pagesDocumentId, serializedPages);
      baselineSnapshotHashRef.current = savedSnapshotHash;
      setHasPendingChanges(false);
      setActiveTab("global");
      message.success("Configuracoes salvas com sucesso.");

      if (typeof window !== "undefined") {
        window.location.reload();
      }

      return;
    } catch (error) {
      if (error?.errorFields) {
        message.error(
          "Por favor, revise os campos obrigatorios antes de salvar.",
        );
      } else {
        message.error(error.message || "Erro ao salvar configuracoes");
      }
    } finally {
      dirtyTrackingSuspendedRef.current = false;
      setSavingConfig(false);
    }
  }

  function renderPageEditor(page) {
    const sessionItems = page.sessoes.map((session, index) => ({
      key: session.localId,
      label: (
        <Space size="small">
          <span>
            {session.nome || `Sessão ${index + 1}`}
            <Text type="secondary" style={{ marginLeft: 8 }}>
              {session.nome_id || "sem nome_id"}
            </Text>
          </span>
          <Button
            type="text"
            size="small"
            icon={<DeleteOutlined />}
            style={{ color: "#8c8c8c" }}
            title="Excluir sessao"
            onClick={(event) => {
              event.stopPropagation();
              requestDeletion({
                type: "session",
                pageId: page.localId,
                sessionId: session.localId,
              });
            }}
          />
        </Space>
      ),
      children: (
        <Space orientation="vertical" size="large" style={{ width: "100%" }}>
          <Input
            placeholder="Nome da sessão"
            value={session.nome}
            onChange={(event) =>
              updateSessionField(
                page.localId,
                session.localId,
                "nome",
                event.target.value,
              )
            }
          />
          <Input
            placeholder="nome_id da sessão"
            value={session.nome_id}
            onChange={(event) =>
              updateSessionField(
                page.localId,
                session.localId,
                "nome_id",
                event.target.value,
              )
            }
          />

          <Space orientation="vertical" size="middle" style={{ width: "100%" }}>
            {sortGroupKeys(session.items).map((groupKey, groupIndex) => (
              <Card
                key={`${session.localId}-${groupKey}`}
                size="small"
                title={`Grupo ${groupIndex + 1}`}
                extra={
                  <Space>
                    <Button
                      type="dashed"
                      size="small"
                      icon={<PlusOutlined />}
                      onClick={() =>
                        addItemEntry(page.localId, session.localId, groupKey)
                      }
                    >
                      Adicionar item
                    </Button>
                    <Button
                      type="text"
                      size="small"
                      icon={<DeleteOutlined />}
                      style={{ color: "#8c8c8c" }}
                      title="Excluir grupo"
                      onClick={() =>
                        requestDeletion({
                          type: "group",
                          pageId: page.localId,
                          sessionId: session.localId,
                          groupKey,
                        })
                      }
                    />
                  </Space>
                }
              >
                <Space
                  orientation="vertical"
                  size="middle"
                  style={{ width: "100%" }}
                >
                  {(session.items[groupKey] || []).map((item, itemIndex) => (
                    <Card
                      key={`${session.localId}-${groupKey}-${itemIndex}`}
                      size="small"
                      type="inner"
                      title={`Item ${itemIndex + 1}`}
                      extra={
                        <Button
                          type="text"
                          size="small"
                          icon={<DeleteOutlined />}
                          style={{ color: "#8c8c8c" }}
                          title="Excluir item"
                          onClick={() =>
                            requestDeletion({
                              type: "item",
                              pageId: page.localId,
                              sessionId: session.localId,
                              groupKey,
                              itemIndex,
                            })
                          }
                        />
                      }
                    >
                      <Space
                        orientation="vertical"
                        size="middle"
                        style={{ width: "100%" }}
                      >
                        <Input
                          placeholder="Nome do campo"
                          value={item.name}
                          onChange={(event) =>
                            updateItemEntry(
                              page.localId,
                              session.localId,
                              groupKey,
                              itemIndex,
                              "name",
                              event.target.value,
                            )
                          }
                        />
                        <Select
                          value={item.tipo}
                          options={ITEM_TYPE_OPTIONS}
                          onChange={(value) =>
                            updateItemEntry(
                              page.localId,
                              session.localId,
                              groupKey,
                              itemIndex,
                              "tipo",
                              value,
                            )
                          }
                        />
                        <TextArea
                          placeholder={getItemTypeExample(item.tipo)}
                          autoSize={{ minRows: 2, maxRows: 6 }}
                          value={item.value}
                          onChange={(event) =>
                            updateItemEntry(
                              page.localId,
                              session.localId,
                              groupKey,
                              itemIndex,
                              "value",
                              event.target.value,
                            )
                          }
                        />
                      </Space>
                    </Card>
                  ))}

                  {!(session.items[groupKey] || []).length ? (
                    <Empty
                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                      description="Nenhum item neste grupo"
                    >
                      <Button
                        type="dashed"
                        size="small"
                        icon={<PlusOutlined />}
                        onClick={() =>
                          addItemEntry(page.localId, session.localId, groupKey)
                        }
                      >
                        Adicionar item
                      </Button>
                    </Empty>
                  ) : null}
                </Space>
              </Card>
            ))}

            {!sortGroupKeys(session.items).length && (
              <Empty description="Nenhum item cadastrado nesta sessão">
                <Button
                  type="dashed"
                  icon={<PlusOutlined />}
                  onClick={() => addItemGroup(page.localId, session.localId)}
                >
                  Adicionar primeiro grupo
                </Button>
              </Empty>
            )}

            {sortGroupKeys(session.items).length ? (
              <Button
                type="dashed"
                icon={<PlusOutlined />}
                onClick={() => addItemGroup(page.localId, session.localId)}
              >
                Adicionar grupo
              </Button>
            ) : null}
          </Space>
        </Space>
      ),
    }));

    return (
      <Space orientation="vertical" size="large" style={{ width: "100%" }}>
        <Alert
          type="info"
          showIcon
          title={`Página ${page.nome || "sem nome"}`}
          description="Os dados abaixo são carregados automaticamente do JSON retornado por /api/c-pages com páginas, sessões e itens."
        />

        <Card title="Dados da Página">
          <Space orientation="vertical" size="middle" style={{ width: "100%" }}>
            <Input
              placeholder="Nome da página"
              value={page.nome}
              onChange={(event) =>
                updatePageField(page.localId, "nome", event.target.value)
              }
            />
            <Input
              placeholder="nome_id"
              value={page.nome_id}
              onChange={(event) =>
                updatePageField(page.localId, "nome_id", event.target.value)
              }
            />
            <Input
              placeholder="Ícone serializado, ex: <HomeOutlined />"
              value={page.icone}
              onChange={(event) =>
                updatePageField(page.localId, "icone", event.target.value)
              }
            />
          </Space>
        </Card>

        <Card
          title="Sessões"
          extra={
            <Button
              type="dashed"
              icon={<PlusOutlined />}
              onClick={() => addSession(page.localId)}
            >
              Adicionar sessao
            </Button>
          }
        >
          {sessionItems.length ? (
            <Collapse items={sessionItems} defaultActiveKey={[]} />
          ) : (
            <Empty description="Nenhuma sessão encontrada para esta página">
              <Button
                type="dashed"
                icon={<PlusOutlined />}
                onClick={() => addSession(page.localId)}
              >
                Adicionar primeira sessao
              </Button>
            </Empty>
          )}
        </Card>
      </Space>
    );
  }

  const fixedTabItems = [
    {
      key: "global",
      label: (
        <span>
          <GlobalOutlined />
          Global
        </span>
      ),
      children: (
        <GlobalConfig
          key={`global-${activeConfigSet?.globalDocumentId || "empty"}`}
          ref={globalConfigRef}
          documentId={activeConfigSet?.globalDocumentId || ""}
          onDraftChange={handleAnyConfigDraftChange}
        />
      ),
      forceRender: true,
    },
    {
      key: "header",
      label: (
        <span>
          <MenuOutlined />
          Header
        </span>
      ),
      children: (
        <HeaderConfig
          key={`header-${activeConfigSet?.headerDocumentId || "empty"}`}
          ref={headerConfigRef}
          documentId={activeConfigSet?.headerDocumentId || ""}
          onDraftChange={handleAnyConfigDraftChange}
        />
      ),
      forceRender: true,
    },
    {
      key: "footer",
      label: (
        <span>
          <LayoutOutlined />
          Footer
        </span>
      ),
      children: (
        <FooterConfig
          key={`footer-${activeConfigSet?.footerDocumentId || "empty"}`}
          ref={footerConfigRef}
          documentId={activeConfigSet?.footerDocumentId || ""}
          onDraftChange={handleAnyConfigDraftChange}
        />
      ),
      forceRender: true,
    },
  ];

  const dynamicTabItems = pages.map((page) => ({
    key: page.localId,
    label: (
      <span
        style={{
          display: "inline-flex",
          alignItems: "center",
          gap: "8px",
        }}
      >
        {buildPageIcon(page)}
        {page.nome || "Nova Pagina"}
      </span>
    ),
    children: renderPageEditor(page),
  }));

  const addPageTabItem = {
    key: "__add_page__",
    label: (
      <span title="Adicionar pagina">
        <PlusOutlined />
      </span>
    ),
    children: null,
  };

  const tabItems = [...fixedTabItems, ...dynamicTabItems, addPageTabItem];
  const hasCompleteActiveSet =
    Boolean(activeConfigSet?.globalDocumentId) &&
    Boolean(activeConfigSet?.headerDocumentId) &&
    Boolean(activeConfigSet?.footerDocumentId) &&
    Boolean(activeConfigSet?.pagesDocumentId);
  const saveButtonDisabled =
    !hasCompleteActiveSet ||
    !pagesDocumentId ||
    pagesLoading ||
    savingConfig ||
    !hasPendingChanges;
  const deletePagesButtonDisabled =
    pagesLoading || savingConfig || !pages.length || hasPendingChanges;
  const saveButtonTooltip = !hasPendingChanges
    ? "Não tem alterações para serem salvas no momento"
    : "";
  const deletePagesButtonTooltip = hasPendingChanges
    ? "Você precisa salvar primeiro as configurações para poder deletar paginas"
    : "";

  return (
    <div
      style={{
        display: "flex",
        minHeight: "100vh",
        backgroundColor: "#f5f5f5",
      }}
    >
      <AdminSidebar
        currentPage="site-configuration"
        pageName="Configurações do Site"
        pageIcon={<LayoutOutlined />}
        userRole={userRole}
      />

      <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
        <AdminHeader userName="Admin" />

        <div
          style={{
            flex: 1,
            padding: "24px",
            overflowY: "auto",
          }}
        >
          <Card
            title="Configurações do Site"
            style={{
              maxWidth: "1400px",
              margin: "0 auto",
              boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
            }}
            extra={
              <Space>
                <Tooltip title={deletePagesButtonTooltip}>
                  <span>
                    <Button
                      danger
                      icon={<DeleteOutlined />}
                      onClick={openDeletePagesModal}
                      disabled={deletePagesButtonDisabled}
                    >
                      Deletar paginas
                    </Button>
                  </span>
                </Tooltip>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={handleReloadAll}
                  loading={pagesLoading || savingConfig}
                >
                  Recarregar configuracoes
                </Button>
                <Tooltip title={saveButtonTooltip}>
                  <span>
                    <Button
                      type="primary"
                      icon={<SaveOutlined />}
                      onClick={handleSaveAll}
                      loading={savingConfig}
                      disabled={saveButtonDisabled}
                    >
                      Salvar configuracoes
                    </Button>
                  </span>
                </Tooltip>
              </Space>
            }
          >
            <Card
              size="small"
              style={{
                marginBottom: "16px",
                borderColor: "#d9e8ff",
                backgroundColor: "#fafcff",
              }}
              title="Set de configuracao ativo"
            >
              <Space
                direction="vertical"
                size="middle"
                style={{ width: "100%" }}
              >
                <Space wrap>
                  <Select
                    placeholder="Selecione um set salvo"
                    style={{ minWidth: 320 }}
                    loading={configSetLoading}
                    value={activeConfigSetId || undefined}
                    options={configSets.map((configSet) => ({
                      value: configSet.id,
                      label: createConfigSetOptionLabel(configSet),
                    }))}
                    onChange={(value) => persistConfigSets(configSets, value)}
                  />
                  <Button
                    onClick={openExistingConfigModal}
                    loading={configSetSubmitting}
                  >
                    Usar configuracoes existentes
                  </Button>
                  <Button
                    type="primary"
                    ghost
                    onClick={handleCreateConfigSet}
                    loading={configSetSubmitting}
                  >
                    Criar novo set
                  </Button>
                </Space>

                {activeConfigSet ? (
                  <Alert
                    type="info"
                    showIcon
                    message={activeConfigSet.name}
                    description={
                      <div>
                        <div>
                          <strong>Global:</strong>{" "}
                          {activeConfigSet.globalDocumentId || "nao definido"}
                        </div>
                        <div>
                          <strong>Header:</strong>{" "}
                          {activeConfigSet.headerDocumentId || "nao definido"}
                        </div>
                        <div>
                          <strong>Footer:</strong>{" "}
                          {activeConfigSet.footerDocumentId || "nao definido"}
                        </div>
                        <div>
                          <strong>Paginas:</strong>{" "}
                          {activeConfigSet.pagesDocumentId || "nao definido"}
                        </div>
                      </div>
                    }
                  />
                ) : (
                  <Alert
                    type="warning"
                    showIcon
                    message="Nenhum set ativo"
                    description="Selecione um set existente ou crie um novo set antes de editar as configuracoes."
                  />
                )}
              </Space>
            </Card>

            {pagesError && (
              <Alert
                type="error"
                showIcon
                title="Erro ao carregar páginas dinâmicas"
                description={pagesError}
                style={{ marginBottom: "16px" }}
              />
            )}

            {configSetLoading ? (
              <div style={{ textAlign: "center", padding: "40px 0" }}>
                <Spin size="large" />
              </div>
            ) : pagesLoading && !pages.length ? (
              <div style={{ textAlign: "center", padding: "40px 0" }}>
                <Spin size="large" />
              </div>
            ) : (
              <Tabs
                className="site-config-tabs"
                activeKey={activeTab}
                onChange={(key) => {
                  if (key === "__add_page__") {
                    addPage();
                    return;
                  }

                  setActiveTab(key);
                }}
                items={tabItems}
                type="card"
                size="large"
                style={{ marginTop: "16px" }}
              />
            )}
          </Card>
        </div>
      </div>

      <style jsx global>{`
        .site-config-tabs .ant-tabs-nav {
          margin-bottom: 12px;
        }

        .site-config-tabs .ant-tabs-nav-wrap {
          overflow-x: auto !important;
          overflow-y: hidden !important;
          scrollbar-width: thin;
          scrollbar-color: #bfbfbf #f0f0f0;
        }

        .site-config-tabs .ant-tabs-nav-wrap::-webkit-scrollbar {
          height: 8px;
        }

        .site-config-tabs .ant-tabs-nav-wrap::-webkit-scrollbar-track {
          background: #f0f0f0;
          border-radius: 999px;
        }

        .site-config-tabs .ant-tabs-nav-wrap::-webkit-scrollbar-thumb {
          background: #bfbfbf;
          border-radius: 999px;
        }

        .site-config-tabs .ant-tabs-nav-wrap::-webkit-scrollbar-thumb:hover {
          background: #9f9f9f;
        }

        .site-config-tabs .ant-tabs-nav-list {
          flex-wrap: nowrap;
        }

        .site-config-tabs .ant-tabs-nav-operations {
          display: none !important;
        }
      `}</style>

      <Modal
        title="Usar configuracoes existentes"
        open={configSetModalOpen}
        onOk={handleSaveExistingConfigSet}
        onCancel={() => {
          if (!configSetSubmitting) {
            setConfigSetModalOpen(false);
          }
        }}
        okText="Salvar set"
        cancelText="Cancelar"
        confirmLoading={configSetSubmitting}
        destroyOnHidden
      >
        <Form form={configSetForm} layout="vertical">
          <Alert
            type="info"
            showIcon
            style={{ marginBottom: "16px" }}
            message="Esse painel salva o vinculo no Site_Cofig"
            description="O conjunto de documentIds escolhido para Global, Header, Footer e Paginas fica persistido no backend pela rota /api/site-cofigs."
          />

          {configSetError ? (
            <Alert
              type="error"
              showIcon
              style={{ marginBottom: "16px" }}
              message="Nao foi possivel validar os IDs informados"
              description={configSetError}
            />
          ) : null}

          <Form.Item label="Nome do set" name="name">
            <Input placeholder="Ex: Configuracao principal do cliente" />
          </Form.Item>

          <Form.Item
            label="documentId Global"
            name="globalDocumentId"
            rules={[
              {
                required: true,
                message: "Informe o documentId da configuracao Global.",
              },
            ]}
          >
            <Input placeholder={SITE_CONFIG_RESOURCES.global.label} />
          </Form.Item>

          <Form.Item
            label="documentId Header"
            name="headerDocumentId"
            rules={[
              {
                required: true,
                message: "Informe o documentId da configuracao Header.",
              },
            ]}
          >
            <Input placeholder={SITE_CONFIG_RESOURCES.header.label} />
          </Form.Item>

          <Form.Item
            label="documentId Footer"
            name="footerDocumentId"
            rules={[
              {
                required: true,
                message: "Informe o documentId da configuracao Footer.",
              },
            ]}
          >
            <Input placeholder={SITE_CONFIG_RESOURCES.footer.label} />
          </Form.Item>

          <Form.Item
            label="documentId Paginas"
            name="pagesDocumentId"
            rules={[
              {
                required: true,
                message: "Informe o documentId da configuracao de Paginas.",
              },
            ]}
          >
            <Input placeholder={SITE_CONFIG_RESOURCES.pages.label} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Deletar paginas"
        open={deletePagesModalOpen}
        onCancel={closeDeletePagesModal}
        onOk={handleDeleteSelectedPages}
        okText="Deletar Selecionados"
        cancelText="Cancelar"
        okButtonProps={{
          danger: true,
          disabled: !selectedPagesToDelete.length,
        }}
        confirmLoading={deletePagesSubmitting}
        destroyOnHidden
      >
        <Space orientation="vertical" size="middle" style={{ width: "100%" }}>
          <Text type="secondary">
            Selecione uma ou mais paginas para excluir.
          </Text>

          <Checkbox
            indeterminate={
              selectedPagesToDelete.length > 0 &&
              selectedPagesToDelete.length < pages.length
            }
            checked={
              pages.length > 0 && selectedPagesToDelete.length === pages.length
            }
            onChange={(event) =>
              setSelectedPagesToDelete(
                event.target.checked ? pages.map((page) => page.localId) : [],
              )
            }
          >
            Selecionar todas
          </Checkbox>

          <div
            style={{
              maxHeight: "320px",
              overflowY: "auto",
              border: "1px solid #f0f0f0",
              borderRadius: "8px",
              padding: "8px 12px",
            }}
          >
            <Checkbox.Group
              style={{ width: "100%" }}
              value={selectedPagesToDelete}
              onChange={(values) => setSelectedPagesToDelete(values)}
            >
              <Space
                orientation="vertical"
                size="small"
                style={{ width: "100%" }}
              >
                {pages.map((page) => (
                  <Checkbox key={page.localId} value={page.localId}>
                    <Space size="small">
                      {buildPageIcon(page)}
                      <span>{page.nome || "Nova Pagina"}</span>
                      <Text type="secondary">
                        ({page.nome_id || "sem nome_id"})
                      </Text>
                    </Space>
                  </Checkbox>
                ))}
              </Space>
            </Checkbox.Group>
          </div>
        </Space>
      </Modal>

      <Modal
        title="Confirmar exclusao"
        open={deleteModalOpen}
        onOk={handleConfirmDeletion}
        okText="Confirmar exclusao"
        cancelText="Cancelar"
        onCancel={closeDeleteModal}
        confirmLoading={deleteSubmitting}
        destroyOnHidden
      >
        <Space orientation="vertical" size="middle" style={{ width: "100%" }}>
          <Text>
            {`Para excluir ${getDeletionTargetLabel(pendingDeletion)}, faca login novamente e depois clique em Confirmar exclusao.`}
          </Text>

          {deleteError ? (
            <Alert
              type="error"
              showIcon
              title="Falha na validacao"
              description={deleteError}
            />
          ) : null}

          <Input
            placeholder="Login"
            value={deleteIdentifier}
            onChange={(event) => setDeleteIdentifier(event.target.value)}
            disabled={deleteSubmitting}
          />
          <Input.Password
            placeholder="Senha"
            value={deletePassword}
            onChange={(event) => setDeletePassword(event.target.value)}
            disabled={deleteSubmitting}
            onPressEnter={handleConfirmDeletion}
          />
        </Space>
      </Modal>
    </div>
  );
}
