'use client';

import { Vote, LogOut, User, Building2, LayoutDashboard, BarChart3 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { Badge } from '@/components/ui/badge';
import { useAuthStore, type ViewType } from '@/store/auth-store';

interface NavItem {
  key: ViewType;
  label: string;
  icon: React.ReactNode;
}

export function AppHeader() {
  const user = useAuthStore((s) => s.user);
  const currentView = useAuthStore((s) => s.currentView);
  const setCurrentView = useAuthStore((s) => s.setCurrentView);
  const logout = useAuthStore((s) => s.logout);

  if (!user) return null;

  const employeeNavItems: NavItem[] = [
    { key: 'voting', label: 'ลงคะแนน', icon: <Vote className="w-4 h-4" /> },
    { key: 'results', label: 'ผลการเลือกตั้ง', icon: <BarChart3 className="w-4 h-4" /> },
  ];

  const adminNavItems: NavItem[] = [
    { key: 'admin', label: 'แผงควบคุม', icon: <LayoutDashboard className="w-4 h-4" /> },
    { key: 'results', label: 'ผลการเลือกตั้ง', icon: <BarChart3 className="w-4 h-4" /> },
  ];

  const navItems = user.isAdmin ? adminNavItems : employeeNavItems;

  const handleLogout = async () => {
    try {
      await fetch('/api/auth/logout', { method: 'POST' });
    } catch {
      // Continue with local logout even if API call fails
    }
    logout();
  };

  return (
    <header className="sticky top-0 z-50 w-full bg-white border-b border-gray-200 shadow-sm">
      <div className="max-w-7xl mx-auto px-4 sm:px-6">
        <div className="flex items-center justify-between h-16">
          {/* Left: Logo & Title */}
          <div className="flex items-center gap-3 shrink-0">
            <div className="flex items-center justify-center w-9 h-9 rounded-xl bg-gradient-to-br from-emerald-500 to-teal-600 shadow-sm">
              <Vote className="w-5 h-5 text-white" />
            </div>
            <h1 className="text-sm sm:text-base font-bold text-gray-900 tracking-tight hidden sm:block">
              ระบบเลือกตั้งตัวแทนพนักงาน
            </h1>
            <h1 className="text-sm font-bold text-gray-900 tracking-tight sm:hidden">
              เลือกตั้งตัวแทน
            </h1>
          </div>

          {/* Center: Navigation Tabs */}
          <nav className="flex items-center gap-1 mx-4" role="tablist">
            {navItems.map((item) => {
              const isActive = currentView === item.key;
              return (
                <button
                  key={item.key}
                  role="tab"
                  aria-selected={isActive}
                  onClick={() => setCurrentView(item.key)}
                  className={`
                    relative flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium
                    transition-all duration-200 cursor-pointer whitespace-nowrap
                    ${
                      isActive
                        ? 'text-emerald-700 bg-emerald-50 shadow-sm'
                        : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                    }
                  `}
                >
                  {item.icon}
                  <span className="hidden sm:inline">{item.label}</span>
                  {isActive && (
                    <span className="absolute bottom-0 left-1/2 -translate-x-1/2 w-6 h-0.5 rounded-full bg-emerald-500" />
                  )}
                </button>
              );
            })}
          </nav>

          {/* Right: User Info & Logout */}
          <div className="flex items-center gap-3 shrink-0">
            <div className="hidden md:flex flex-col items-end gap-0.5">
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium text-gray-900">{user.name}</span>
                {user.isAdmin && (
                  <Badge
                    variant="outline"
                    className="text-[10px] px-1.5 py-0 h-4 border-amber-300 bg-amber-50 text-amber-700 font-semibold"
                  >
                    Admin
                  </Badge>
                )}
              </div>
              <div className="flex items-center gap-1 text-xs text-gray-400">
                <Building2 className="w-3 h-3" />
                <span>{user.branchName || user.branchId}</span>
              </div>
            </div>

            <Separator orientation="vertical" className="h-8 hidden md:block" />

            {/* Mobile user avatar */}
            <div className="md:hidden flex items-center justify-center w-8 h-8 rounded-full bg-emerald-100 text-emerald-700">
              <User className="w-4 h-4" />
            </div>

            <Button
              variant="ghost"
              size="sm"
              onClick={handleLogout}
              className="text-gray-500 hover:text-red-600 hover:bg-red-50 gap-2 cursor-pointer"
            >
              <LogOut className="w-4 h-4" />
              <span className="hidden sm:inline">ออกจากระบบ</span>
            </Button>
          </div>
        </div>
      </div>
    </header>
  );
}
