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-border bg-card text-foreground transition hover:border-[#10B981]/30 hover:bg-accent hover:text-accent-foreground";

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-foreground transition hover:bg-accent hover:text-accent-foreground"
    >
      {theme === "dark" ? (
        <Sun className="h-4 w-4" />
      ) : (
        <Moon className="h-4 w-4" />
      )}
    </button>
  ) : null;

  return (
    <div className="flex min-h-screen">
      <Sidebar
        title={title}
        items={sidebarItems}
        activeHref={activeHref}
        onNavigate={onNavigate}
        headerExtra={themeToggleButton}
      />
      <div className="flex flex-1 flex-col">
        <header className="flex h-16 items-center justify-between border-b border-border bg-background px-6 text-foreground">
          <div className="text-base font-medium">{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-accent aria-expanded:border-[#10B981]/30 aria-expanded:bg-accent"
                >
                <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-foreground md:block">
                  {userName}
                </span>
                <ChevronDown
                  className={`h-4 w-4 text-muted-foreground transition ${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-border bg-card py-1 shadow-lg"
                >
                  <div className="border-b border-border px-4 py-3">
                    <p className="text-sm font-semibold text-card-foreground">
                      {userName}
                    </p>
                    {userEmail ? (
                      <p className="text-xs text-muted-foreground">
                        {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-card-foreground transition hover:bg-accent hover:text-accent-foreground"
                  >
                    <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-background ">{children}</main>
      </div>
    </div>
  );
};

export default DashboardLayout;
