import { ReactNode, useEffect, useRef, useState } from "react";
import {
  Bell,
  ChevronDown,
  Languages,
  LogOut,
  Moon,
  Sun,
  User,
} from "lucide-react";
import Sidebar, { SidebarItem } from "./Sidebar";

export interface DashboardLayoutProps {
  title?: string;
  sidebarItems: SidebarItem[];
  activeHref?: string;
  onNavigate?: (href: string) => void;
  headerRight?: ReactNode;
  enableThemeToggle?: boolean;
  userName?: string;
  userEmail?: string;
  userInitials?: string;
  onLogout?: () => void;
  children: ReactNode;
}

type Theme = "light" | "dark";
const THEME_STORAGE_KEY = "edr-theme";

function getInitialTheme(): Theme {
  if (typeof window === "undefined") return "light";
  const stored = window.localStorage.getItem(THEME_STORAGE_KEY);
  if (stored === "dark" || stored === "light") return stored;
  return window.matchMedia?.("(prefers-color-scheme: dark)").matches
    ? "dark"
    : "light";
}

const iconButtonClass =
  "inline-flex h-10 w-10 items-center justify-center rounded-xl border border-slate-200 text-slate-600 transition hover:border-[#10B981]/30 hover:bg-[#10B981]/10 hover:text-[#10B981] dark:border-slate-700 dark:text-slate-300 dark:hover:border-[#10B981]/40 dark:hover:bg-[#10B981]/20 dark:hover:text-white";

const DashboardLayout = ({
  title,
  sidebarItems,
  activeHref,
  onNavigate,
  headerRight,
  enableThemeToggle = false,
  userName = "User",
  userEmail,
  userInitials,
  onLogout,
  children,
}: DashboardLayoutProps) => {
  const initials =
    userInitials ??
    userName
      .split(" ")
      .filter(Boolean)
      .slice(0, 2)
      .map((n) => n[0].toUpperCase())
      .join("");
  const [theme, setTheme] = useState<Theme>(() =>
    enableThemeToggle ? getInitialTheme() : "light",
  );

  useEffect(() => {
    if (!enableThemeToggle) return;
    const root = document.documentElement;
    if (theme === "dark") {
      root.classList.add("dark");
    } else {
      root.classList.remove("dark");
    }
    window.localStorage.setItem(THEME_STORAGE_KEY, theme);
  }, [theme, enableThemeToggle]);

  const toggleTheme = () =>
    setTheme((current) => (current === "dark" ? "light" : "dark"));

  const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);
  const userMenuRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (!isUserMenuOpen) return;

    const handlePointerDown = (event: MouseEvent) => {
      if (
        userMenuRef.current &&
        !userMenuRef.current.contains(event.target as Node)
      ) {
        setIsUserMenuOpen(false);
      }
    };

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") setIsUserMenuOpen(false);
    };

    document.addEventListener("mousedown", handlePointerDown);
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("mousedown", handlePointerDown);
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [isUserMenuOpen]);

  const themeToggleButton = enableThemeToggle ? (
    <button
      type="button"
      onClick={toggleTheme}
      aria-label={
        theme === "dark" ? "Switch to light mode" : "Switch to dark mode"
      }
      className="inline-flex h-8 w-8 items-center justify-center rounded-lg text-slate-600 transition hover:bg-[#10B981]/10 hover:text-[#10B981] dark:text-slate-300 dark:hover:bg-[#10B981]/20 dark:hover:text-white"
    >
      {theme === "dark" ? (
        <Sun className="h-4 w-4" />
      ) : (
        <Moon className="h-4 w-4" />
      )}
    </button>
  ) : null;

  return (
    <div className="flex h-screen overflow-hidden bg-slate-50 dark:bg-slate-950">
      <Sidebar
        title={title}
        items={sidebarItems}
        activeHref={activeHref}
        onNavigate={onNavigate}
        headerExtra={themeToggleButton}
      />
      <div className="flex min-w-0 flex-1 flex-col">
        <header className="flex h-16 items-center justify-between border-b border-slate-200 bg-white px-6 dark:border-slate-800 dark:bg-slate-900">
          <div className="text-base font-medium text-slate-700 dark:text-slate-200">
            {title}
          </div>

          <div className="flex items-center gap-2">
            <button
              type="button"
              aria-label="Change language"
              className={iconButtonClass}
            >
              <Languages className="h-5 w-5" />
            </button>

            <button
              type="button"
              aria-label="Notifications"
              className={`${iconButtonClass} relative`}
            >
              <Bell className="h-5 w-5" />
              <span className="absolute right-2 top-2 h-2 w-2 rounded-full bg-red-500 ring-2 ring-white dark:ring-slate-900" />
            </button>

            <div ref={userMenuRef} className="relative ml-1">
              <button
                type="button"
                aria-haspopup="menu"
                aria-expanded={isUserMenuOpen}
                onClick={() => setIsUserMenuOpen((open) => !open)}
                className="flex items-center gap-2 rounded-xl border border-transparent px-2 py-1.5 transition hover:border-[#10B981]/20 hover:bg-[#10B981]/5 aria-expanded:border-[#10B981]/30 aria-expanded:bg-[#10B981]/10 dark:hover:border-[#10B981]/30 dark:hover:bg-[#10B981]/10 dark:aria-expanded:border-[#10B981]/40 dark:aria-expanded:bg-[#10B981]/20"
              >
                <div className="flex h-8 w-8 items-center justify-center rounded-full bg-[#10B981] text-xs font-semibold text-white">
                  {initials}
                </div>
                <span className="hidden text-sm font-medium text-slate-700 md:block dark:text-slate-200">
                  {userName}
                </span>
                <ChevronDown
                  className={`h-4 w-4 text-slate-400 transition dark:text-slate-500 ${
                    isUserMenuOpen ? "rotate-180 text-[#10B981]" : ""
                  }`}
                />
              </button>

              {isUserMenuOpen ? (
                <div
                  role="menu"
                  className="absolute right-0 top-full z-50 mt-2 w-52 overflow-hidden rounded-xl border border-slate-200 bg-white py-1 shadow-lg dark:border-slate-700 dark:bg-slate-800"
                >
                  <div className="border-b border-slate-100 px-4 py-3 dark:border-slate-700">
                    <p className="text-sm font-semibold text-slate-900 dark:text-slate-100">
                      {userName}
                    </p>
                    {userEmail ? (
                      <p className="text-xs text-slate-500 dark:text-slate-400">
                        {userEmail}
                      </p>
                    ) : null}
                  </div>
                  <a
                    href="#profile"
                    role="menuitem"
                    onClick={() => setIsUserMenuOpen(false)}
                    className="flex items-center gap-2 px-4 py-2 text-sm text-slate-700 transition hover:bg-[#10B981]/10 hover:text-[#10B981] dark:text-slate-300 dark:hover:bg-[#10B981]/20 dark:hover:text-white"
                  >
                    <User className="h-4 w-4" />
                    Profile
                  </a>
                  <button
                    type="button"
                    role="menuitem"
                    onClick={() => {
                      setIsUserMenuOpen(false);
                      onLogout?.();
                    }}
                    className="flex w-full items-center gap-2 px-4 py-2 text-sm text-red-600 transition hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-950/30"
                  >
                    <LogOut className="h-4 w-4" />
                    Logout
                  </button>
                </div>
              ) : null}
            </div>

            {headerRight}
          </div>
        </header>

        <main className="flex-1 overflow-auto bg-slate-50 p-6 dark:bg-slate-950">
          {children}
        </main>
      </div>
    </div>
  );
};

export default DashboardLayout;
