import { useState } from 'react';
import { BookOpenText, Bot, KeyRound, LogOut, Shield, User, UserCog } from 'lucide-react';
import { ModelOverrideDictDialog } from '@/components/auth/ModelOverrideDictDialog';
import { ProcurementAccountDialog } from '@/components/auth/ProcurementAccountDialog';
import { useLocation, useNavigate } from 'react-router-dom';
import { ChangePasswordDialog } from '@/components/auth/ChangePasswordDialog';
import { ModelConfigDialog } from '@/components/auth/ModelConfigDialog';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useAuth } from '@/hooks/useAuth';
import { toast } from 'sonner';
import { appRouteLabels } from './navigation';
import { AutomationServiceIndicator } from './AutomationServiceIndicator';
import { SearchManualInterventionBell } from './SearchManualInterventionBell';

export function AppHeader() {
  const location = useLocation();
  const navigate = useNavigate();
  const { user, logout, isAdmin } = useAuth();
  const [changePasswordOpen, setChangePasswordOpen] = useState(false);
  const [modelConfigOpen, setModelConfigOpen] = useState(false);
  const [procurementAccountOpen, setProcurementAccountOpen] = useState(false);
  const [modelOverrideDictOpen, setModelOverrideDictOpen] = useState(false);

  const pageLabel = appRouteLabels[location.pathname] ?? '';

  async function handleLogout() {
    await logout();
    toast.success('已退出登录');
    navigate('/login', { replace: true });
  }

  const roleLabel = user?.role === 'admin' ? 'Admin' : 'User';
  const userLabel = user?.displayName ?? user?.username ?? 'Guest';

  return (
    <>
      <header className="light-panel shrink-0 rounded-[24px] border border-slate-200/80 bg-white/95 px-6 shadow-sm backdrop-blur-md dark:border-slate-200/80 dark:bg-white/95 dark:shadow-sm">
        <div className="flex h-14 items-center justify-between">
          <div className="flex items-center gap-1.5 text-sm">
            <span className="text-slate-400">首页</span>
            {pageLabel && (
              <>
                <span className="text-slate-400">/</span>
                <span className="font-medium text-foreground">{pageLabel}</span>
              </>
            )}
          </div>

          <div className="flex items-center gap-2">
            <AutomationServiceIndicator />

            <div className="mx-1 h-5 w-px bg-border" />

            <SearchManualInterventionBell />

            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <button className="flex items-center gap-2 rounded-xl px-2 py-1.5 transition-colors hover:bg-muted">
                  <div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary shadow-[0_8px_20px_-12px_rgba(37,99,235,0.8)] dark:bg-blue-500">
                    <User className="h-4 w-4 text-primary-foreground" />
                  </div>
                  <span className="text-sm font-medium text-foreground transition-colors hover:text-primary">
                    {userLabel}
                  </span>
                </button>
              </DropdownMenuTrigger>

              <DropdownMenuContent align="end" className="w-56">
                <DropdownMenuLabel>
                  <div className="space-y-1">
                    <p className="text-sm font-medium text-slate-900">{userLabel}</p>
                    <p className="text-xs text-slate-500">{isAdmin ? '管理员' : '普通用户'}</p>
                  </div>
                </DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem onSelect={() => setChangePasswordOpen(true)}>
                  <KeyRound className="mr-2 h-4 w-4" />
                  修改密码
                </DropdownMenuItem>
                {isAdmin && (
                  <DropdownMenuItem onSelect={() => setModelConfigOpen(true)}>
                    <Bot className="mr-2 h-4 w-4" />
                    模型管理
                  </DropdownMenuItem>
                )}
                <DropdownMenuItem onSelect={() => setProcurementAccountOpen(true)}>
                  <UserCog className="mr-2 h-4 w-4" />
                  采购账户管理
                </DropdownMenuItem>
                <DropdownMenuItem onSelect={() => setModelOverrideDictOpen(true)}>
                  <BookOpenText className="mr-2 h-4 w-4" />
                  采购字典管理
                </DropdownMenuItem>
                <DropdownMenuItem disabled>
                  <Shield className="mr-2 h-4 w-4" />
                  Role: {roleLabel}
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onSelect={handleLogout} className="text-red-600 focus:text-red-600">
                  <LogOut className="mr-2 h-4 w-4" />
                  退出登录
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </header>

      <ChangePasswordDialog open={changePasswordOpen} onOpenChange={setChangePasswordOpen} />
      <ModelConfigDialog open={modelConfigOpen} onOpenChange={setModelConfigOpen} />
      <ProcurementAccountDialog open={procurementAccountOpen} onOpenChange={setProcurementAccountOpen} />
      <ModelOverrideDictDialog open={modelOverrideDictOpen} onOpenChange={setModelOverrideDictOpen} />
    </>
  );
}
