import { type ReactNode, useEffect, useRef, useState } from "react";
import {
  Bell,
  ChevronDown,
  Languages,
  LogOut,
  MessageSquare,
  Moon,
  Sun,
  User,
} from "lucide-react";
import { Group, Stack, Text, Avatar, Menu, ActionIcon, Badge, Box } from "@mantine/core";

import type { PageMeta } from "./types";
import { freightBrand } from "@/theme/freight-brand";

export interface FreightDashboardHeaderProps {
  pageMeta: PageMeta;
  headerRight?: ReactNode;
  enableThemeToggle?: boolean;
  userName?: string;
  userEmail?: string;
  userInitials?: string;
  onLogout?: () => void;
  theme: "light" | "dark";
  onToggleTheme: () => void;
}

const FreightDashboardHeader = ({
  pageMeta,
  headerRight,
  enableThemeToggle = false,
  userName = "User",
  userEmail,
  userInitials,
  onLogout,
  theme,
  onToggleTheme,
}: FreightDashboardHeaderProps) => {
  const initials =
    userInitials ??
    userName
      .split(" ")
      .filter(Boolean)
      .slice(0, 2)
      .map((n) => n[0].toUpperCase())
      .join("");

  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]);

  return (
    <header
      style={{
        display: "flex",
        height: "80px",
        alignItems: "center",
        justifyContent: "space-between",
        gap: "16px",
        padding: "0 24px",
        // borderBottom: `3px solid ${freightBrand.primary}`,
      }}
    >
      <Stack gap={2} style={{ flex: 1, minWidth: 0 }}>
        <Text size="lg" fw={700} truncate style={{ color: freightBrand.primaryDark }}>
          {pageMeta.title}
        </Text>
        <Text size="sm" c="dimmed" truncate>
          {pageMeta.subtitle}
        </Text>
      </Stack>

      <Group gap="sm" wrap="nowrap">
        {enableThemeToggle && (
          <ActionIcon
            variant="default"
            size={40}
            radius="lg"
            onClick={onToggleTheme}
            style={{
              background: "var(--mantine-color-gray-1)",
              border: "1px solid var(--mantine-color-gray-2)",
              color: "var(--mantine-color-gray-7)",
            }}
          >
            {theme === "dark" ? <Sun size={18} /> : <Moon size={18} />}
          </ActionIcon>
        )}

        <ActionIcon
          variant="default"
          size={40}
          radius="lg"
          style={{
            background: "var(--mantine-color-gray-1)",
            border: "1px solid var(--mantine-color-gray-2)",
            color: "var(--mantine-color-gray-7)",
          }}
        >
          <Languages size={18} />
        </ActionIcon>

        <ActionIcon
          variant="default"
          size={40}
          radius="lg"
          style={{
            background: "var(--mantine-color-gray-1)",
            border: "1px solid var(--mantine-color-gray-2)",
            color: "var(--mantine-color-gray-7)",
            position: "relative",
          }}
        >
          <MessageSquare size={18} />
          <Badge
            size="xs"
            color="red"
            circle
            style={{
              position: "absolute",
              top: "-3px",
              right: "-3px",
            }}
          />
        </ActionIcon>

        <ActionIcon
          variant="default"
          size={40}
          radius="lg"
          style={{
            background: "var(--mantine-color-gray-1)",
            border: "1px solid var(--mantine-color-gray-2)",
            color: "var(--mantine-color-gray-7)",
            position: "relative",
          }}
        >
          <Bell size={18} />
          <Badge
            size="xs"
            color="red"
            circle
            style={{
              position: "absolute",
              top: "-3px",
              right: "-3px",
            }}
          />
        </ActionIcon>

        <Menu position="bottom-end" shadow="md" opened={isUserMenuOpen} onOpen={() => setIsUserMenuOpen(true)} onClose={() => setIsUserMenuOpen(false)}>
          <Menu.Target>
            <Group gap="sm" p="xs" style={{ cursor: "pointer", borderRadius: "12px" }}>
              <Avatar name={initials} color="green" size="md" styles={{ root: { background: freightBrand.primary } }} />
              <ChevronDown size={16} style={{ transition: "transform 0.2s", transform: isUserMenuOpen ? "rotate(180deg)" : "rotate(0deg)" }} />
            </Group>
          </Menu.Target>
          <Menu.Dropdown>
            <Menu.Item disabled>
              <Stack gap={0}>
                <Text size="sm" fw={600}>
                  {userName}
                </Text>
                {userEmail && (
                  <Text size="xs" c="dimmed">
                    {userEmail}
                  </Text>
                )}
              </Stack>
            </Menu.Item>
            <Menu.Divider />
            <Menu.Item
              leftSection={<User size={14} />}
              onClick={() => setIsUserMenuOpen(false)}
            >
              Profile
            </Menu.Item>
            <Menu.Item
              leftSection={<LogOut size={14} />}
              color="red"
              onClick={() => {
                setIsUserMenuOpen(false);
                onLogout?.();
              }}
            >
              Logout
            </Menu.Item>
          </Menu.Dropdown>
        </Menu>

        {headerRight}
      </Group>
    </header>
  );
};

export default FreightDashboardHeader;
