import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Bell, User, Settings, HelpCircle, Sparkles, ShoppingCart, Headphones, Package, Menu, Store, Ticket } from "lucide-react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { CartSidebar } from "@/components/cart/CartSidebar";
import { useCart } from "@/contexts/CartContext";
import { useAuth } from "@/contexts/AuthContext";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useNavigate } from "react-router-dom";
import { NotificationDialog } from "./NotificationDialog";
import { ProfileDialog } from "./ProfileDialog";
import { useState } from "react";
import { ThemeToggle } from "@/components/theme/ThemeToggle";

interface HeaderProps {
  onToggleSidebar?: () => void;
  showSidebarToggle?: boolean;
}

export function Header({ onToggleSidebar, showSidebarToggle = false }: HeaderProps) {
  const { itemCount } = useCart();
  const { user, profile, signOut } = useAuth();
  const navigate = useNavigate();
  const [notificationOpen, setNotificationOpen] = useState(false);
  const [profileOpen, setProfileOpen] = useState(false);
  const [profileTab, setProfileTab] = useState("profile");

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

  const openProfileDialog = (tab: string = "profile") => {
    setProfileTab(tab);
    setProfileOpen(true);
  };

  return (
    <header className="h-14 sm:h-16 border-b border-border bg-background/80 backdrop-blur-sm sticky top-0 z-50">
      <div className="flex h-full items-center justify-between px-3 sm:px-6">
        {/* Left Section - Sidebar Toggle */}
        <div className="flex items-center">
          {showSidebarToggle && (
            <Button
              variant="ghost"
              size="icon"
              onClick={onToggleSidebar}
              className="text-muted-foreground hover:text-foreground hover:bg-surface"
            >
              <Menu className="h-5 w-5" />
            </Button>
          )}
        </div>

        {/* Center Section */}
        <div className="flex items-center space-x-2" />


        {/* Right Section - User Actions */}
        <div className="flex items-center gap-1 sm:gap-3">
          <CartSidebar>
            <Button
              variant="ghost"
              size="icon"
              className="relative text-muted-foreground hover:text-foreground hover:bg-surface"
            >
              <ShoppingCart className="h-5 w-5" />
              {itemCount > 0 && (
                <Badge 
                  variant="destructive" 
                  className="absolute -top-1 -right-1 h-4 w-4 rounded-full p-0 flex items-center justify-center text-xs"
                >
                  {itemCount}
                </Badge>
              )}
            </Button>
          </CartSidebar>

          <Button
            variant="ghost"
            size="icon"
            className="relative text-muted-foreground hover:text-foreground hover:bg-surface"
            onClick={() => setNotificationOpen(true)}
          >
            <Bell className="h-5 w-5" />
            <div className="absolute -top-1 -right-1 h-3 w-3 bg-primary rounded-full flex items-center justify-center">
              <span className="text-xs text-primary-foreground font-medium">2</span>
            </div>
          </Button>

          <NotificationDialog 
            open={notificationOpen} 
            onOpenChange={setNotificationOpen} 
          />



          <ThemeToggle className="text-muted-foreground hover:text-foreground hover:bg-surface" />

          <div className="hidden sm:block h-6 w-px bg-border"></div>

          {/* User Authentication Section */}
          {!user ? (
            // Not logged in - show login/register links
            <div className="flex items-center gap-1 sm:gap-2">
              <span className="hidden sm:inline text-sm text-muted-foreground">你好，请</span>
              <Button
                variant="link"
                className="text-primary hover:text-primary/80 p-0 h-auto font-normal text-sm"
                onClick={() => navigate('/auth')}
              >
                登录
              </Button>
              <Button
                variant="link"
                className="hidden sm:inline-flex text-destructive hover:text-destructive/80 p-0 h-auto font-normal"
                onClick={() => navigate('/auth')}
              >
                免费注册
              </Button>
            </div>
          ) : (
            // Logged in - show user profile dropdown
            <div className="flex items-center space-x-2">
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" className="relative h-10 w-10 rounded-full hover:bg-accent">
                    <Avatar className="h-9 w-9 cursor-pointer">
                      <AvatarFallback className="bg-primary text-primary-foreground text-sm font-medium">
                        {profile?.display_name?.[0]?.toUpperCase() || user?.email?.[0]?.toUpperCase() || "U"}
                      </AvatarFallback>
                    </Avatar>
                  </Button>
                </DropdownMenuTrigger>
                
                <DropdownMenuContent className="w-72 bg-background border border-border shadow-lg z-[100]" align="end" forceMount>
                  <DropdownMenuLabel className="font-normal p-4 bg-muted/50">
                    <div className="flex items-center space-x-3">
                      <Avatar className="h-12 w-12">
                        <AvatarFallback className="bg-primary text-primary-foreground text-lg font-medium">
                          {profile?.display_name?.[0]?.toUpperCase() || user?.email?.[0]?.toUpperCase() || "U"}
                        </AvatarFallback>
                      </Avatar>
                      <div className="flex flex-col space-y-1">
                        <p className="text-sm font-medium leading-none text-foreground">
                          {profile?.display_name || "用户"}
                        </p>
                        <p className="text-xs leading-none text-muted-foreground">
                          {user?.email}
                        </p>
                        <div className="flex items-center mt-2">
                          <div className="w-2 h-2 bg-success rounded-full mr-2"></div>
                          <span className="text-xs text-success font-medium">在线</span>
                        </div>
                      </div>
                    </div>
                  </DropdownMenuLabel>
                  
                  <DropdownMenuSeparator />
                  
                  <div className="p-2 space-y-1">
                    <DropdownMenuItem 
                      onClick={() => openProfileDialog('profile')}
                      className="cursor-pointer rounded-md p-3 hover:bg-accent focus:bg-accent"
                    >
                      <User className="mr-3 h-4 w-4" />
                      <span>个人信息</span>
                    </DropdownMenuItem>
                    
                    <DropdownMenuItem 
                      onClick={() => openProfileDialog('security')}
                      className="cursor-pointer rounded-md p-3 hover:bg-accent focus:bg-accent"
                    >
                      <Settings className="mr-3 h-4 w-4" />
                      <span>安全设置</span>
                    </DropdownMenuItem>
                    
                    <DropdownMenuItem 
                      onClick={() => openProfileDialog('preferences')}
                      className="cursor-pointer rounded-md p-3 hover:bg-accent focus:bg-accent"
                    >
                      <HelpCircle className="mr-3 h-4 w-4" />
                      <span>偏好设置</span>
                    </DropdownMenuItem>
                    
                    <DropdownMenuItem 
                      onClick={() => navigate('/shop')}
                      className="cursor-pointer rounded-md p-3 hover:bg-accent focus:bg-accent"
                    >
                      <Store className="mr-3 h-4 w-4" />
                      <span>智能商城</span>
                    </DropdownMenuItem>
                    
                    <DropdownMenuItem 
                      onClick={() => openProfileDialog('orders')}
                      className="cursor-pointer rounded-md p-3 hover:bg-accent focus:bg-accent"
                    >
                      <Package className="mr-3 h-4 w-4" />
                      <span>我的订单</span>
                    </DropdownMenuItem>
                    
                    <DropdownMenuItem 
                      onClick={() => openProfileDialog('after-sales')}
                      className="cursor-pointer rounded-md p-3 hover:bg-accent focus:bg-accent"
                    >
                      <Headphones className="mr-3 h-4 w-4" />
                      <span>售后服务</span>
                    </DropdownMenuItem>
                    
                    <DropdownMenuItem 
                      onClick={() => openProfileDialog('coupons')}
                      className="cursor-pointer rounded-md p-3 hover:bg-accent focus:bg-accent"
                    >
                      <Ticket className="mr-3 h-4 w-4" />
                      <span>我的优惠券</span>
                    </DropdownMenuItem>
                  </div>
                  
                  <DropdownMenuSeparator />
                  
                  <div className="p-2">
                    <DropdownMenuItem 
                      onClick={handleSignOut}
                      className="cursor-pointer rounded-md p-3 hover:bg-destructive hover:text-destructive-foreground text-destructive focus:bg-destructive focus:text-destructive-foreground"
                    >
                      <span>退出登录</span>
                    </DropdownMenuItem>
                  </div>
                </DropdownMenuContent>
              </DropdownMenu>
              
              <div className="hidden md:block ml-2">
                <p className="text-sm font-medium text-foreground">
                  {profile?.display_name || "用户"}
                </p>
                <p className="text-xs text-muted-foreground">在线</p>
              </div>
            </div>
          )}
        </div>
      </div>

      <NotificationDialog 
        open={notificationOpen} 
        onOpenChange={setNotificationOpen} 
      />
      
      <ProfileDialog 
        open={profileOpen} 
        onOpenChange={setProfileOpen}
        defaultTab={profileTab}
      />
    </header>
  );
}