import { useState } from 'react';
import { Link, useLocation } from 'wouter';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { useAuth } from '@/contexts/AuthContext';
import { 
  Home, 
  User, 
  Store, 
  Truck, 
  Settings, 
  MapPin,
  Menu,
  X,
  LogIn,
  UserPlus,
  LogOut,
  Heart,
  Cross
} from 'lucide-react';
import { HeaderNotifications } from './HeaderNotifications';

interface NavigationProps {
  userRole?: 'client' | 'pharmacy' | 'courier' | 'admin' | 'guest';
}

const navigationItems = [
  { id: 'landing', label: 'Accueil', icon: Home, path: '/', roles: ['guest', 'client', 'pharmacy', 'courier', 'admin'] },
  { id: 'client-dashboard', label: 'Client', icon: User, path: '/client', roles: ['client'] },
  { id: 'pharmacy-dashboard', label: 'Pharmacie', icon: Store, path: '/pharmacy', roles: ['pharmacy'] },
  { id: 'courier-dashboard', label: 'Livreur', icon: Truck, path: '/courier', roles: ['courier'] },
  { id: 'admin-dashboard', label: 'Admin', icon: Settings, path: '/admin', roles: ['admin'] },
  { id: 'tracking', label: 'Suivi', icon: MapPin, path: '/tracking', roles: ['client', 'pharmacy', 'courier', 'admin'] },
];

export function Navigation({ userRole = 'guest' }: NavigationProps) {
  const { user, isAuthenticated, logout } = useAuth();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [location] = useLocation();

  const visibleItems = navigationItems.filter(item => 
    item.roles.includes(userRole) || item.roles.includes('guest')
  );

  const toggleMobileMenu = () => {
    setIsMobileMenuOpen(!isMobileMenuOpen);
  };

  return (
    <>
      {/* Mobile Menu Button */}
      <div className="lg:hidden fixed top-4 left-4 z-50">
        <Button
          variant="outline"
          size="sm"
          onClick={toggleMobileMenu}
          className="bg-white shadow-md"
        >
          {isMobileMenuOpen ? <X className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
        </Button>
      </div>

      {/* Navigation Tabs - Desktop */}
      <nav className="hidden lg:block sticky top-0 z-40 bg-white shadow-sm border-b">
        <div className="container mx-auto px-4">
          <div className="flex items-center justify-between">
            {/* Brand */}
            <Link href="/" className="flex items-center gap-2 py-4 hover:opacity-80 transition-opacity">
              <Cross className="h-8 w-8 text-blue-600" />
              <span className="font-bold text-gray-900 text-xl">MediFlash</span>
            </Link>
            
            {/* Navigation Items */}
            <div className="flex items-center space-x-8">
              {!isAuthenticated ? (
                <>
                  <Link href="/register" className="text-gray-700 hover:text-blue-600 font-medium transition-colors">
                    Demander un SOS
                  </Link>
                  <Link href="/tracking" className="text-gray-700 hover:text-blue-600 font-medium transition-colors">
                    Suivi de commande
                  </Link>
                </>
              ) : (
                <>
                  {userRole === 'client' && (
                    <Link href="/client" className="text-gray-700 hover:text-blue-600 font-medium transition-colors">
                      Dashboard
                    </Link>
                  )}
                  {userRole === 'pharmacy' && (
                    <Link href="/pharmacy" className="text-gray-700 hover:text-blue-600 font-medium transition-colors">
                      Pharmacie
                    </Link>
                  )}
                  {userRole === 'courier' && (
                    <Link href="/courier" className="text-gray-700 hover:text-blue-600 font-medium transition-colors">
                      Livreur
                    </Link>
                  )}
                  {userRole === 'admin' && (
                    <Link href="/admin" className="text-gray-700 hover:text-blue-600 font-medium transition-colors">
                      Admin
                    </Link>
                  )}
                  <Link href="/tracking" className="text-gray-700 hover:text-blue-600 font-medium transition-colors">
                    Suivi
                  </Link>
                </>
              )}
            </div>

            {/* Auth Actions */}
            <div className="flex items-center">
              {!isAuthenticated ? (
                <Link href="/login">
                  <Button className="bg-blue-600 hover:bg-blue-700 text-white" data-testid="nav-login">
                    Se connecter
                  </Button>
                </Link>
              ) : (
                <div className="flex items-center gap-4">
                  {/* Notifications */}
                  {isAuthenticated && (
                    <div className="hidden md:block">
                      <HeaderNotifications />
                    </div>
                  )}
                  
                  <span className="text-sm text-gray-600">
                    Bonjour, <span className="font-medium text-gray-900">{user?.name}</span>
                  </span>
                  <Button 
                    variant="outline" 
                    size="sm" 
                    onClick={() => logout()}
                    data-testid="nav-logout"
                  >
                    <LogOut className="h-4 w-4 mr-2" />
                    Déconnexion
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </nav>

      {/* Mobile Navigation Overlay */}
      {isMobileMenuOpen && (
        <div className="lg:hidden fixed inset-0 z-40 bg-black bg-opacity-50" onClick={toggleMobileMenu}>
          <div className="fixed left-0 top-0 h-full w-64 bg-white shadow-xl" onClick={e => e.stopPropagation()}>
            <div className="p-4 border-b">
              <div className="flex items-center gap-2">
                <Cross className="h-6 w-6 text-blue-600" />
                <h2 className="text-lg font-bold text-gray-900">MediFlash</h2>
              </div>
              {isAuthenticated && (
                <p className="text-sm text-muted-foreground mt-1">
                  Bonjour, {user?.name}
                </p>
              )}
            </div>
            <nav className="p-4 space-y-2">
              {visibleItems.map((item) => {
                const Icon = item.icon;
                const isActive = location === item.path;
                
                return (
                  <Link key={item.id} href={item.path}>
                    <button
                      className={cn(
                        "w-full flex items-center gap-3 px-4 py-3 text-left rounded-lg",
                        "transition-colors duration-200 hover:bg-primary/10",
                        isActive && "bg-primary text-primary-foreground"
                      )}
                      onClick={toggleMobileMenu}
                      data-testid={`mobile-nav-${item.id}`}
                    >
                      <Icon className="h-5 w-5" />
                      <span className="font-medium">{item.label}</span>
                      {item.id === 'pharmacy-dashboard' && userRole === 'pharmacy' && (
                        <Badge variant="secondary" className="ml-auto">
                          2
                        </Badge>
                      )}
                    </button>
                  </Link>
                );
              })}
              
              {/* Mobile Auth Actions */}
              <div className="border-t pt-4 mt-4">
                {!isAuthenticated ? (
                  <div className="space-y-2">
                    <Link href="/login">
                      <button
                        className="w-full flex items-center gap-3 px-4 py-3 text-left rounded-lg hover:bg-primary/10"
                        onClick={toggleMobileMenu}
                        data-testid="mobile-nav-login"
                      >
                        <LogIn className="h-5 w-5" />
                        <span className="font-medium">Connexion</span>
                      </button>
                    </Link>
                    <Link href="/register">
                      <button
                        className="w-full flex items-center gap-3 px-4 py-3 text-left rounded-lg bg-primary text-primary-foreground"
                        onClick={toggleMobileMenu}
                        data-testid="mobile-nav-register"
                      >
                        <UserPlus className="h-5 w-5" />
                        <span className="font-medium">Inscription</span>
                      </button>
                    </Link>
                  </div>
                ) : (
                  <button
                    className="w-full flex items-center gap-3 px-4 py-3 text-left rounded-lg hover:bg-red-50 text-red-600"
                    onClick={() => {
                      toggleMobileMenu();
                      logout();
                    }}
                    data-testid="mobile-nav-logout"
                  >
                    <LogOut className="h-5 w-5" />
                    <span className="font-medium">Déconnexion</span>
                  </button>
                )}
              </div>
            </nav>
          </div>
        </div>
      )}
    </>
  );
}
