import type { PropsWithChildren } from "react";
import { Button, ConfigProvider, Layout } from "antd";
import { useNavigate } from "react-router-dom";
import { useAuth } from "@modules/auth";
import { AdminSider, readAdminSidebarCollapsedPreference, type AdminTab } from "./AdminSider";
import {
  getAdminAntdTheme,
  persistAdminThemePreference,
  readAdminThemePreference,
  toggleAdminColorMode,
  type AdminColorMode
} from "../config/adminTheme";
import "../styles/wesp-admin-panel.css";
import { useEffect, useLayoutEffect, useState } from "react";

interface AdminShellProps extends PropsWithChildren {
  tab: AdminTab;
  isSuperuser: boolean;
  onSelectTab: (tab: AdminTab) => void;
}

function applyAdminThemeAttribute(mode: AdminColorMode): void {
  if (mode === "dark") {
    document.documentElement.setAttribute("data-admin-theme", "dark");
    return;
  }
  document.documentElement.removeAttribute("data-admin-theme");
}

export function AdminShell({ tab, isSuperuser, onSelectTab, children }: AdminShellProps): JSX.Element {
  const navigate = useNavigate();
  const auth = useAuth();
  const [siderCollapsed, setSiderCollapsed] = useState(readAdminSidebarCollapsedPreference);
  const [colorMode, setColorMode] = useState<AdminColorMode>(readAdminThemePreference);

  useLayoutEffect(() => {
    applyAdminThemeAttribute(colorMode);
    return () => document.documentElement.removeAttribute("data-admin-theme");
  }, [colorMode]);

  useEffect(() => {
    const syncSidebarForViewport = (): void => {
      if (window.matchMedia("(max-width: 768px)").matches) {
        setSiderCollapsed(false);
        return;
      }
      setSiderCollapsed(readAdminSidebarCollapsedPreference());
    };

    syncSidebarForViewport();
    window.addEventListener("resize", syncSidebarForViewport);
    return () => window.removeEventListener("resize", syncSidebarForViewport);
  }, []);

  useEffect(() => {
    document.documentElement.classList.add("wesp-admin-loading");
    const blocks = Array.from(
      document.querySelectorAll<HTMLElement>(".wesp-admin-content .wesp-admin-block")
    );
    blocks.forEach((el) => {
      if (el.querySelector(":scope > .wesp-admin-skel-overlay")) {
        return;
      }
      const overlay = document.createElement("div");
      overlay.className = "wesp-admin-skel-overlay";
      overlay.setAttribute("aria-hidden", "true");
      el.appendChild(overlay);
    });
    const timer = window.setTimeout(() => {
      blocks.forEach((el, index) => el.style.setProperty("--wesp-reveal-i", String(index)));
      document.documentElement.classList.remove("wesp-admin-loading");
      document.documentElement.classList.add("wesp-admin-loaded");
      window.setTimeout(() => {
        document.querySelectorAll(".wesp-admin-skel-overlay").forEach((overlay) => overlay.remove());
      }, 420);
    }, 320);

    return () => {
      window.clearTimeout(timer);
      document.documentElement.classList.remove("wesp-admin-loading", "wesp-admin-loaded");
      document.querySelectorAll(".wesp-admin-skel-overlay").forEach((overlay) => overlay.remove());
    };
  }, []);

  return (
    <ConfigProvider theme={getAdminAntdTheme(colorMode)}>
      <Layout
        className={`wesp-admin-layout wesp-admin-layout--${colorMode}${siderCollapsed ? "" : " wesp-admin-sider-expanded"}`}
      >
        <AdminSider
          tab={tab}
          isSuperuser={isSuperuser}
          collapsed={siderCollapsed}
          colorMode={colorMode}
          onCollapse={setSiderCollapsed}
          onSelect={onSelectTab}
        />
        <Layout>
          <Layout.Content className="wesp-admin-content">
            <header className="wesp-admin-content-topbar">
              <div className="wesp-admin-content-topbar-actions">
                <Button
                  onClick={() => {
                    const nextMode = toggleAdminColorMode(colorMode);
                    setColorMode(nextMode);
                    persistAdminThemePreference(nextMode);
                  }}
                >
                  Light/Dark
                </Button>
                <Button href="/">На сайт</Button>
                <Button
                  danger
                  onClick={() => {
                    void auth.logout().then(() => navigate("/login", { replace: true }));
                  }}
                >
                  Logout
                </Button>
              </div>
            </header>
            <main className="wesp-admin-main">{children}</main>
          </Layout.Content>
        </Layout>
      </Layout>
    </ConfigProvider>
  );
}
