'use client';

import {
  LogOut,
  Menu,
  Moon,
  Sun,
  User as UserIcon,
  X,
  LayoutDashboard,
  Shield,
} from 'lucide-react';
import * as React from 'react';
import { cn } from '@/lib/utils';

/* -------------------------------------------------------------------------- */
/*  Types                                                                      */
/* -------------------------------------------------------------------------- */

export interface NavLink {
  href: string;
  label: string;
  isActive?: boolean;
  /** Nested links shown on hover / accordion. */
  children?: NavLink[];
}

export interface NavUser {
  fullName: string;
  email?: string | null;
  phone?: string | null;
  role: string;
  avatarUrl?: string | null;
}

export interface NavbarProps {
  /** Brand name shown in the header. */
  brand: string;
  /** Primary navigation links. */
  links: NavLink[];
  /** Current user or null if unauthenticated. */
  user: NavUser | null;
  /** Dashboard href (role-dependent). */
  dashboardHref: string;
  /** Slot: notification bell or other widgets. */
  notifications?: React.ReactNode;
  /** Slot: language switcher. */
  languageSwitcher?: React.ReactNode;
  /** Light / dark theme. */
  theme: 'light' | 'dark';
  /** Toggle theme callback. */
  onToggleTheme: () => void;
  /** Logout callback. */
  onLogout: () => Promise<void> | void;
  /** i18n labels. */
  labels: {
    login: string;
    register: string;
    dashboard: string;
    admin: string;
    profile: string;
    logout: string;
    openMenu: string;
    closeMenu: string;
    darkMode: string;
    lightMode: string;
    mainNav: string;
  };
  /** Login / register hrefs — rendered via renderLink. */
  loginHref?: string;
  registerHref?: string;
  profileHref?: string;
  /** Custom link renderer for framework-specific Link component (Next/i18n). */
  renderLink: (props: {
    href: string;
    children: React.ReactNode;
    className?: string;
    onClick?: () => void;
  }) => React.ReactNode;
}

/* -------------------------------------------------------------------------- */
/*  Helpers                                                                    */
/* -------------------------------------------------------------------------- */

const ROLE_LABELS: Record<string, string> = {
  ADMIN: 'Quản trị viên',
  AGENT: 'Đại lý',
  SELLER: 'Người bán',
  BUYER: 'Người mua',
};

function getInitials(fullName: string): string {
  const parts = fullName.trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return '?';
  if (parts.length === 1) return parts[0]!.slice(0, 2).toUpperCase();
  return (parts[0]![0]! + parts[parts.length - 1]![0]!).toUpperCase();
}

/* -------------------------------------------------------------------------- */
/*  Component                                                                  */
/* -------------------------------------------------------------------------- */

export function Navbar({
  brand,
  links,
  user,
  dashboardHref,
  notifications,
  languageSwitcher,
  theme,
  onToggleTheme,
  onLogout,
  labels,
  loginHref = '/login',
  registerHref = '/register',
  profileHref = '/dashboard/profile',
  renderLink,
}: NavbarProps) {
  const [mobileOpen, setMobileOpen] = React.useState(false);

  const close = () => setMobileOpen(false);

  const handleLogout = async () => {
    close();
    await onLogout();
  };

  return (
    <header
      role="banner"
      className="sticky top-0 z-50 border-b border-border bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60"
    >
      {/* -------- Main bar -------- */}
      <div className="mx-auto flex h-14 max-w-7xl items-center px-4">
        {/* Brand */}
        {renderLink({
          href: '/',
          className: 'mr-6 flex items-center gap-2 group',
          children: (
            <>
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary text-primary-foreground text-sm font-bold transition-transform group-hover:scale-105">
                G
              </div>
              <span className="text-lg font-bold tracking-tight text-foreground">
                {brand}
              </span>
            </>
          ),
        })}

        {/* Desktop nav */}
        <nav aria-label={labels.mainNav} className="hidden items-center gap-0.5 lg:flex">
          {links.map((link) => (
            <React.Fragment key={link.href}>
              {renderLink({
                href: link.href,
                className: cn(
                  'relative rounded-md px-3 py-2 text-sm font-medium transition-colors',
                  'hover:bg-accent hover:text-accent-foreground',
                  link.isActive
                    ? 'text-foreground'
                    : 'text-muted-foreground',
                ),
                children: (
                  <>
                    {link.label}
                    {link.isActive && (
                      <span className="absolute inset-x-1 -bottom-[13px] h-0.5 rounded-full bg-primary" />
                    )}
                  </>
                ),
              })}
            </React.Fragment>
          ))}
        </nav>

        {/* Right actions */}
        <div className="ml-auto flex min-w-0 items-center gap-1 sm:gap-2">
          {languageSwitcher}

          <button
            type="button"
            onClick={onToggleTheme}
            aria-label={theme === 'light' ? labels.darkMode : labels.lightMode}
            className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"
          >
            {theme === 'light' ? (
              <Moon className="h-4 w-4" aria-hidden />
            ) : (
              <Sun className="h-4 w-4" aria-hidden />
            )}
          </button>

          {user ? (
            <>
              <div className="hidden sm:block">{notifications}</div>

              {/* User pill */}
              <div className="hidden items-center gap-2 rounded-full border border-border bg-background-elevated px-2 py-1 sm:flex">
                {user.avatarUrl ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={user.avatarUrl}
                    alt=""
                    className="h-6 w-6 rounded-full border object-cover"
                  />
                ) : (
                  <div className="flex h-6 w-6 items-center justify-center rounded-full bg-primary/15 text-[10px] font-semibold text-primary">
                    {getInitials(user.fullName)}
                  </div>
                )}
                <span className="max-w-[10rem] truncate text-sm text-foreground">
                  {user.fullName}
                </span>
                {ROLE_LABELS[user.role] && (
                  <span className="rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary">
                    {ROLE_LABELS[user.role]}
                  </span>
                )}
              </div>

              {renderLink({
                href: dashboardHref,
                className: 'hidden sm:inline-flex',
                children: (
                  <button
                    type="button"
                    className="inline-flex h-9 items-center gap-1.5 rounded-md bg-primary px-3 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary-hover"
                  >
                    {user.role === 'ADMIN' ? (
                      <Shield className="h-3.5 w-3.5" aria-hidden />
                    ) : (
                      <LayoutDashboard className="h-3.5 w-3.5" aria-hidden />
                    )}
                    {user.role === 'ADMIN' ? labels.admin : labels.dashboard}
                  </button>
                ),
              })}
            </>
          ) : (
            <>
              {renderLink({
                href: loginHref,
                className: 'hidden sm:inline-flex',
                children: (
                  <button
                    type="button"
                    className="inline-flex h-9 items-center rounded-md px-3 text-sm font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"
                  >
                    {labels.login}
                  </button>
                ),
              })}
              {renderLink({
                href: registerHref,
                className: 'hidden sm:inline-flex',
                children: (
                  <button
                    type="button"
                    className="inline-flex h-9 items-center rounded-md bg-primary px-3 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary-hover"
                  >
                    {labels.register}
                  </button>
                ),
              })}
            </>
          )}

          {/* Mobile hamburger */}
          <button
            type="button"
            aria-label={mobileOpen ? labels.closeMenu : labels.openMenu}
            aria-expanded={mobileOpen}
            className="inline-flex shrink-0 items-center justify-center rounded-md p-2 text-muted-foreground hover:bg-accent hover:text-accent-foreground lg:hidden"
            onClick={() => setMobileOpen(!mobileOpen)}
          >
            {mobileOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
          </button>
        </div>
      </div>

      {/* -------- Mobile drawer -------- */}
      {mobileOpen && (
        <nav aria-label={labels.mainNav} className="border-t px-4 pb-4 pt-2 lg:hidden">
          <div className="space-y-0.5">
            {links.map((link) => (
              <React.Fragment key={link.href}>
                {renderLink({
                  href: link.href,
                  onClick: close,
                  className: cn(
                    'flex items-center rounded-md px-3 py-2.5 text-sm font-medium transition-colors',
                    link.isActive
                      ? 'bg-primary/10 text-primary'
                      : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
                  ),
                  children: (
                    <>
                      {link.isActive && (
                        <span className="mr-2 h-1.5 w-1.5 rounded-full bg-primary" />
                      )}
                      {link.label}
                    </>
                  ),
                })}
              </React.Fragment>
            ))}
          </div>

          <div className="mt-3 space-y-2 border-t border-border pt-3">
            {user ? (
              <>
                {/* Mobile user card */}
                <div className="flex items-center gap-3 rounded-lg bg-background-elevated px-3 py-2.5">
                  {user.avatarUrl ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={user.avatarUrl}
                      alt=""
                      className="h-10 w-10 shrink-0 rounded-full border object-cover"
                    />
                  ) : (
                    <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-primary/15 text-sm font-semibold text-primary">
                      {getInitials(user.fullName)}
                    </div>
                  )}
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-medium text-foreground">
                      {user.fullName}
                    </p>
                    <p className="truncate text-xs text-muted-foreground">
                      {user.email ?? user.phone}
                    </p>
                  </div>
                  {ROLE_LABELS[user.role] && (
                    <span className="shrink-0 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary">
                      {ROLE_LABELS[user.role]}
                    </span>
                  )}
                </div>

                {renderLink({
                  href: dashboardHref,
                  onClick: close,
                  className: 'block',
                  children: (
                    <button
                      type="button"
                      className="flex w-full items-center justify-center gap-2 rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary-hover"
                    >
                      {user.role === 'ADMIN' ? (
                        <Shield className="h-4 w-4" aria-hidden />
                      ) : (
                        <LayoutDashboard className="h-4 w-4" aria-hidden />
                      )}
                      {user.role === 'ADMIN' ? labels.admin : labels.dashboard}
                    </button>
                  ),
                })}

                {renderLink({
                  href: profileHref,
                  onClick: close,
                  className: 'block',
                  children: (
                    <button
                      type="button"
                      className="flex w-full items-center justify-center gap-2 rounded-md border border-border px-3 py-2 text-sm font-medium text-foreground transition-colors hover:bg-accent"
                    >
                      <UserIcon className="h-4 w-4" aria-hidden />
                      {labels.profile}
                    </button>
                  ),
                })}

                <button
                  type="button"
                  className="flex w-full items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-medium text-destructive transition-colors hover:bg-destructive/10"
                  onClick={handleLogout}
                >
                  <LogOut className="h-4 w-4" aria-hidden />
                  {labels.logout}
                </button>
              </>
            ) : (
              <div className="flex gap-2">
                {renderLink({
                  href: loginHref,
                  onClick: close,
                  className: 'flex-1',
                  children: (
                    <button
                      type="button"
                      className="w-full rounded-md border border-border px-3 py-2 text-sm font-medium text-foreground transition-colors hover:bg-accent"
                    >
                      {labels.login}
                    </button>
                  ),
                })}
                {renderLink({
                  href: registerHref,
                  onClick: close,
                  className: 'flex-1',
                  children: (
                    <button
                      type="button"
                      className="w-full rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary-hover"
                    >
                      {labels.register}
                    </button>
                  ),
                })}
              </div>
            )}
          </div>
        </nav>
      )}
    </header>
  );
}
