import { ReactNode } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '@/hooks/useAuth';
import { useCart } from '@/contexts/CartContext';
import { Button } from '@/components/ui/button';
import { ShoppingCart, User, LogOut, Settings } from 'lucide-react';

export function Layout({ children }: { children: ReactNode }) {
  const { user, isAdmin, signOut } = useAuth();
  const { items } = useCart();
  const navigate = useNavigate();

  const handleSignOut = async () => {
    await signOut();
    navigate('/');
  };

  return (
    <div className="min-h-screen bg-background">
      <header className="border-b-2 border-border bg-background">
        <div className="container mx-auto px-4 py-4 flex items-center justify-between">
          <Link to="/" className="text-2xl font-bold">
            LearnHub
          </Link>
          
          <nav className="flex items-center gap-4">
            <Link to="/products" className="hover:underline font-medium">
              Products
            </Link>
            
            {user ? (
              <>
                <Link to="/dashboard" className="hover:underline font-medium">
                  Dashboard
                </Link>
                {isAdmin && (
                  <Link to="/admin" className="hover:underline font-medium flex items-center gap-1">
                    <Settings className="w-4 h-4" />
                    Admin
                  </Link>
                )}
                <Button variant="ghost" size="sm" onClick={handleSignOut}>
                  <LogOut className="w-4 h-4" />
                </Button>
              </>
            ) : (
              <Link to="/auth">
                <Button variant="outline" size="sm">
                  <User className="w-4 h-4 mr-2" />
                  Login
                </Button>
              </Link>
            )}
            
            <Link to="/checkout">
              <Button variant="outline" size="sm" className="relative">
                <ShoppingCart className="w-4 h-4" />
                {items.length > 0 && (
                  <span className="absolute -top-2 -right-2 bg-primary text-primary-foreground text-xs w-5 h-5 flex items-center justify-center border border-border">
                    {items.length}
                  </span>
                )}
              </Button>
            </Link>
          </nav>
        </div>
      </header>
      
      <main>{children}</main>
    </div>
  );
}
