import React, { forwardRef } from 'react';
import { clsx } from 'clsx';
import { useTranslation } from 'react-i18next';
import { useAuthUser, useIsAuthenticated } from '../../../stores';
import { useTheme } from '../../../contexts/ThemeContext';
import { useHasAccess } from '../../../hooks/useAccessControl';
import { Button } from '../../ui';
import { TenantSwitcher } from '../../ui/TenantSwitcher';
import { ThemeToggle } from '../../ui/ThemeToggle';
import { CompactLanguageSelector } from '../../ui/LanguageSelector';
import {
  Menu,
  TrendingUp
} from 'lucide-react';

export interface HeaderProps {
  className?: string;
  /**
   * Callback when menu button is clicked (for mobile sidebar toggle)
   */
  onMenuClick?: () => void;
  /**
   * Whether the sidebar is currently collapsed (affects logo display)
   */
  sidebarCollapsed?: boolean;
  /**
   * Show/hide search functionality
   */
  showSearch?: boolean;
  /**
   * Show/hide theme toggle
   */
  showThemeToggle?: boolean;
  /**
   * Custom logo component
   */
  logo?: React.ReactNode;
  /**
   * Custom search placeholder
   */
  searchPlaceholder?: string;
}

export interface HeaderRef {
  // No search-related methods anymore
}

/**
 * Header - Top navigation header with logo and theme toggle
 *
 * Features:
 * - Logo/brand area with responsive sizing
 * - Theme toggle button (light/dark/system)
 * - Mobile hamburger menu integration
 * - Keyboard navigation support
 */
export const Header = forwardRef<HeaderRef, HeaderProps>(({
  className,
  onMenuClick,
  sidebarCollapsed = false,
  showSearch = true,
  showThemeToggle = true,
  logo,
  searchPlaceholder,
}, ref) => {
  const { t } = useTranslation();
  const user = useAuthUser();
  const hasAccess = useHasAccess(); // Check both authentication and demo mode
  const { theme, resolvedTheme, setTheme } = useTheme();

  const defaultSearchPlaceholder = searchPlaceholder || t('common:forms.search_placeholder', 'Search...');

  // Expose ref methods
  React.useImperativeHandle(ref, () => ({
    // No search functions available anymore
  }), []);


  // Removed notification panel effects as part of new alert system integration


  return (
    <header
      className={clsx(
        'fixed top-0 left-0 right-0 h-[var(--header-height)]',
        'bg-[var(--bg-primary)] border-b border-[var(--border-primary)]',
        'flex items-center justify-between px-4 lg:px-6',
        'transition-all duration-300 ease-in-out',
        'backdrop-blur-sm bg-[var(--bg-primary)]/95',
        'z-[var(--z-fixed)]',
        className
      )}
      role="banner"
      aria-label={t('common:header.main_navigation', 'Navegación principal')}
    >
      {/* Left section */}
      <div className="flex items-center gap-2 sm:gap-4 flex-1 min-w-0 h-full">
        {/* Mobile menu button */}
        <div data-tour="sidebar-menu-toggle">
          <Button
            variant="ghost"
            size="sm"
            onClick={onMenuClick}
            className="lg:hidden w-10 h-10 p-0 flex items-center justify-center hover:bg-[var(--bg-secondary)] active:scale-95 transition-all duration-150"
            aria-label={t('common:header.open_menu', 'Abrir menú de navegación')}
          >
            <Menu className="h-5 w-5 text-[var(--text-primary)]" />
          </Button>
        </div>

        {/* Logo */}
        <div className="flex items-center gap-2 sm:gap-3 min-w-0 flex-shrink-0 h-full">
          {logo || (
            <>
              <div className="w-8 h-8 bg-gradient-to-br from-[var(--color-primary)] to-[var(--color-primary-dark)] rounded-lg flex items-center justify-center flex-shrink-0 shadow-sm">
                <TrendingUp className="w-5 h-5 text-white" strokeWidth={2.5} />
              </div>
              <h1 className={clsx(
                'font-semibold text-[var(--text-primary)] transition-opacity duration-300',
                'hidden md:block text-lg whitespace-nowrap',
                'leading-[32px]', // Match icon height for perfect alignment
                sidebarCollapsed ? 'lg:block' : 'lg:hidden xl:block'
              )}>
                {t('common:app.name', 'BakeWise')}
              </h1>
            </>
          )}
        </div>

        {/* Tenant Switcher - Desktop */}
        {hasAccess && (
          <div className="hidden md:block mx-2 lg:mx-4 flex-shrink-0" data-tour="header-tenant-selector">
            <TenantSwitcher
              showLabel={true}
              className="min-w-[160px] max-w-[220px] lg:min-w-[200px] lg:max-w-[280px]"
            />
          </div>
        )}

        {/* Tenant Switcher - Mobile (in title area) */}
        {hasAccess && (
          <div className="md:hidden flex-1 min-w-0 ml-3">
            <TenantSwitcher
              showLabel={false}
              className="w-full max-w-none"
            />
          </div>
        )}

        {/* Space for potential future content */ }
        {hasAccess && (
          <div className="hidden md:flex items-center flex-1 max-w-md mx-4">
            &nbsp; {/* Empty space to maintain layout consistency */}
          </div>
        )}
      </div>

      {/* Right section */}
      {hasAccess && (
        <div className="flex items-center gap-1">
          {/* Language selector */}
          <CompactLanguageSelector className="w-auto min-w-[50px]" />

          {/* Theme toggle */}
          {showThemeToggle && (
            <ThemeToggle variant="button" size="md" />
          )}
        </div>
      )}
    </header>
  );
});

Header.displayName = 'Header';