import React from 'react';
import { Menu, ChevronRight, LogOut, Settings as SettingsIcon } from 'lucide-react';
import { Button } from '../../ui/button';
import { ThemeToggle } from '../../brand/theme-toggle';
import { LanguageSelector } from '../../brand/language-selector';
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
  BreadcrumbLink,
} from '../../ui/breadcrumb';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '../../ui/dropdown-menu';
import { Avatar, AvatarFallback, AvatarImage } from '../../ui/avatar';

import { useOptionalLayout } from '../../../contexts/LayoutContext';

/**
 * Breadcrumb entry for the header navigation.
 */
export interface BreadcrumbType {
  /** Text label to display */
  label: string;
  /**
   * URL to navigate to.
   * When `renderLink` is provided on the Header, this value is passed to your
   * custom link component (e.g., React Router's `<Link to={href}>`).
   * Otherwise it's used as a standard `<a href>`.
   */
  href?: string;
  /** Optional leading icon */
  icon?: React.ReactNode;
}

/**
 * Action button configuration for the header.
 */
export interface HeaderAction {
  /** Unique identifier for the action */
  id: string;
  /** Optional text label (hidden on mobile) */
  label?: string;
  /** Icon element to display */
  icon: React.ReactNode;
  /** Click handler */
  onClick?: () => void;
  /** Additional CSS classes */
  className?: string;
}

/**
 * Props for the Header component.
 */
export interface HeaderProps {
  /**
   * Page title — used only when the page has no navigation hierarchy.
   * Renders as a plain text label without breadcrumb separators.
   * This is the **exception** pattern; prefer `breadcrumbs` for all navigable pages.
   */
  title?: string;
  /**
   * Navigation breadcrumb trail — the **primary** and recommended pattern.
   * Supports unlimited levels. The last item (without `href`) is treated as the current page.
   */
  breadcrumbs?: BreadcrumbType[];
  /** Whether to show the language selector */
  showLanguageSelector?: boolean;
  /** Whether to show the theme toggle button */
  showThemeToggle?: boolean;
  /** Additional CSS classes */
  className?: string;
  /** Logged-in user information and menu */
  user?: {
    name?: string;
    email?: string;
    avatar?: string;
    menuItems?: HeaderAction[];
  };
  /** Custom action buttons to display */
  actions?: HeaderAction[];
  /** Whether to show a quick settings button */
  showSettings?: boolean;
  /** Click handler for settings */
  onSettingsClick?: () => void;
  /** Whether to show a quick logout button */
  showLogout?: boolean;
  /** Click handler for logout */
  onLogout?: () => void;
  /**
   * Custom element rendered immediately after the breadcrumb / title area.
   * Accepts any React node — badges, buttons, status chips, etc.
   *
   * @example
   * ```tsx
   * <Header
   *   breadcrumbs={[...]}
   *   breadcrumbSlot={<Badge variant="warning">Beta</Badge>}
   * />
   * ```
   */
  breadcrumbSlot?: React.ReactNode;
  /**
   * Custom link renderer for breadcrumb navigation.
   * Use this to integrate with client-side routers (e.g., React Router, Next.js Link)
   * to prevent full-page reloads on navigation.
   *
   * When omitted, breadcrumbs render standard `<a>` tags.
   *
   * @example
   * ```tsx
   * import { Link } from 'react-router-dom';
   *
   * <Header
   *   breadcrumbs={[...]}
   *   renderLink={(href, props) => <Link to={href} {...props} />}
   * />
   * ```
   */
  renderLink?: (
    href: string,
    props: { className?: string; children: React.ReactNode }
  ) => React.ReactNode;
}

/**
 * Main application Header component.
 *
 * @description
 * Provides a sticky top navigation bar with breadcrumbs, responsive mobile menu trigger,
 * theme/language selectors, and user profile management.
 *
 * The Header supports two navigation modes:
 * - **Breadcrumbs (default)**: Pass the `breadcrumbs` array for pages with navigation hierarchy.
 *   Supports unlimited depth levels.
 * - **Title-only (exception)**: Pass `title` for pages without any navigation (e.g., standalone pages).
 *   This renders a simple text label without separators.
 *
 * @ai-rules
 * 1. **Always prefer `breadcrumbs`** for any page that has a parent or navigation context.
 * 2. Use `title` **only** when the page is a top-level standalone page with no navigation hierarchy.
 * 3. Use `actions` for page-specific global actions (e.g., Save, Edit).
 * 4. The `user` prop is mandatory for authenticated states to show the profile dropdown.
 * 5. Breadcrumbs support unlimited levels — do not limit to 2 or 3 items.
 */
export function Header({
  title,
  breadcrumbs,
  showLanguageSelector = true,
  showThemeToggle = true,
  className,
  user,
  actions,
  showSettings,
  onSettingsClick,
  showLogout,
  onLogout,
  renderLink,
  breadcrumbSlot,
}: HeaderProps) {
  const layout = useOptionalLayout();
  const toggleSidebar = layout?.toggleSidebar ?? (() => {});

  return (
    <header
      className={`bg-card text-foreground shadow-sm border-b border-border px-[24px] h-[64px] flex-shrink-0 flex items-center ${className || ''}`}
    >
      <div className="flex items-center justify-between w-full p-[0px]">
        <div className="flex items-center gap-2 text-muted-foreground w-full overflow-x-auto">
          {/* Mobile menu trigger */}
          <Button
            variant="ghost"
            size="sm"
            onClick={toggleSidebar}
            className="md:hidden mr-2 p-2 shrink-0"
            aria-label="Abrir menu lateral"
          >
            <Menu className="w-5 h-5" />
          </Button>

          {/* Breadcrumbs or Title */}
          {breadcrumbs && breadcrumbs.length > 0 ? (
            <Breadcrumb>
              <BreadcrumbList className="flex-nowrap whitespace-nowrap">
                {breadcrumbs.map((item, index) => (
                  <React.Fragment key={index}>
                    <BreadcrumbItem>
                      {item.href ? (
                        renderLink ? (
                          <BreadcrumbLink asChild className="flex items-center gap-1.5">
                            {renderLink(item.href, {
                              className: 'flex items-center gap-1.5',
                              children: (
                                <>
                                  {item.icon}
                                  {item.label}
                                </>
                              ),
                            })}
                          </BreadcrumbLink>
                        ) : (
                          <BreadcrumbLink href={item.href} className="flex items-center gap-1.5">
                            {item.icon}
                            {item.label}
                          </BreadcrumbLink>
                        )
                      ) : (
                        <BreadcrumbPage className="flex items-center gap-1.5">
                          {item.icon}
                          {item.label}
                        </BreadcrumbPage>
                      )}
                    </BreadcrumbItem>
                    {index < breadcrumbs.length - 1 && <BreadcrumbSeparator />}
                  </React.Fragment>
                ))}
              </BreadcrumbList>
            </Breadcrumb>
          ) : title ? (
            <span className="text-foreground font-medium shrink-0">{title}</span>
          ) : (
            <Breadcrumb>
              <BreadcrumbList className="flex-nowrap whitespace-nowrap">
                <BreadcrumbItem>
                  <BreadcrumbPage className="text-foreground font-medium shrink-0">
                    Xertica.ai
                  </BreadcrumbPage>
                </BreadcrumbItem>
              </BreadcrumbList>
            </Breadcrumb>
          )}
          {/* Breadcrumb slot */}
          {breadcrumbSlot && <div className="flex items-center shrink-0">{breadcrumbSlot}</div>}
        </div>

        {/* User controls */}
        <div className="flex items-center gap-3 shrink-0 ml-4">
          {/* Language selector */}
          {showLanguageSelector && (
            <LanguageSelector variant="minimal" showIcon={false} className="hidden sm:flex" />
          )}

          {/* Theme toggle */}
          {showThemeToggle && <ThemeToggle className="hover:bg-accent" />}

          {/* Custom actions */}
          {actions?.map(action => (
            <Button
              key={action.id}
              variant="ghost"
              size={action.label ? 'sm' : 'icon'}
              onClick={action.onClick}
              className={`hover:bg-accent ${action.className || ''}`}
              aria-label={action.label || action.id}
            >
              {action.icon}
              {action.label && <span className="ml-2 hidden md:inline">{action.label}</span>}
            </Button>
          ))}

          {/* Quick settings button */}
          {showSettings && (
            <Button
              variant="ghost"
              size="icon"
              onClick={onSettingsClick}
              className="hover:bg-accent"
              aria-label="Configurações"
            >
              <SettingsIcon className="w-5 h-5" />
            </Button>
          )}

          {/* User profile dropdown */}
          {user && (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  className="relative h-8 w-8 rounded-full p-0 overflow-hidden border border-border/50 hover:border-primary/30 transition-colors"
                  aria-label="Menu do usuário"
                >
                  <Avatar className="h-8 w-8">
                    <AvatarImage src={user.avatar} alt={user.name || 'User'} />
                    <AvatarFallback className="bg-primary/10 text-primary text-xs font-medium">
                      {user.name ? user.name.charAt(0).toUpperCase() : 'U'}
                    </AvatarFallback>
                  </Avatar>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="w-56" align="end" forceMount>
                <DropdownMenuLabel className="font-normal">
                  <div className="flex flex-col space-y-1">
                    <p className="text-sm font-medium leading-none">{user.name || 'User'}</p>
                    <p className="text-xs leading-none text-muted-foreground">
                      {user.email || 'user@example.com'}
                    </p>
                  </div>
                </DropdownMenuLabel>
                <DropdownMenuSeparator />
                {user.menuItems?.map(item => (
                  <DropdownMenuItem key={item.id} onClick={item.onClick} className={item.className}>
                    {item.icon && <span className="mr-2">{item.icon}</span>}
                    {item.label}
                  </DropdownMenuItem>
                ))}
                {!user.menuItems && (
                  <>
                    <DropdownMenuItem onClick={onSettingsClick}>
                      <SettingsIcon className="mr-2 h-4 w-4" />
                      <span>Settings</span>
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      onClick={onLogout}
                      className="text-destructive focus:text-destructive"
                    >
                      <LogOut className="mr-2 h-4 w-4" />
                      <span>Logout</span>
                    </DropdownMenuItem>
                  </>
                )}
              </DropdownMenuContent>
            </DropdownMenu>
          )}

          {/* Quick logout button - always last */}
          {showLogout && (
            <Button
              variant="ghost"
              size="icon"
              onClick={onLogout}
              className="hover:bg-accent text-muted-foreground hover:text-foreground"
              aria-label="Sair"
            >
              <LogOut className="w-5 h-5" />
            </Button>
          )}
        </div>
      </div>
    </header>
  );
}
