import { Link, useNavigate } from 'react-router-dom';
import { LogOut, Moon, Sun, MonitorSmartphone, ChevronDown } from 'lucide-react';
import { useAuth } from '@/lib/auth-context';
import { Button } from '@/components/ui/button';
import { useTheme } from './use-theme';
import { isSuperAdmin } from '@/lib/scope';
import { useState } from 'react';
import { cn } from '@/lib/utils';

export function TopBar() {
  const { user, logout } = useAuth();
  const { theme, setTheme } = useTheme();
  const navigate = useNavigate();
  const [menuOpen, setMenuOpen] = useState(false);

  if (!user) return null;

  const handleLogout = async () => {
    await logout();
    navigate('/login', { replace: true });
  };

  return (
    <header className="flex h-14 items-center justify-between border-b bg-card px-4">
      <Link to="/" className="flex items-center gap-2">
        <span className="inline-block h-6 w-6 rounded bg-primary" aria-hidden />
        <span className="text-sm font-semibold">broad-announce</span>
      </Link>

      <div className="flex items-center gap-3">
        {isSuperAdmin(user.role) ? (
          <span className="hidden text-xs text-muted-foreground sm:inline">
            all companies
          </span>
        ) : user.tenant_slug ? (
          <span className="hidden rounded-md bg-muted px-2 py-1 text-xs sm:inline">
            {user.tenant_slug}
          </span>
        ) : null}

        <Button
          variant="ghost"
          size="icon"
          aria-label="Toggle theme"
          onClick={() => {
            const next = theme === 'light' ? 'dark' : theme === 'dark' ? 'system' : 'light';
            setTheme(next);
          }}
        >
          {theme === 'light' && <Sun className="h-4 w-4" />}
          {theme === 'dark' && <Moon className="h-4 w-4" />}
          {theme === 'system' && <MonitorSmartphone className="h-4 w-4" />}
        </Button>

        <div className="relative">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setMenuOpen((v) => !v)}
            aria-haspopup="menu"
            aria-expanded={menuOpen}
          >
            <span className="hidden text-right sm:block">
              <span className="block text-xs font-medium">{user.email}</span>
              <span className="block text-[10px] uppercase tracking-wider text-muted-foreground">
                {user.role.replace('_', ' ')}
              </span>
            </span>
            <ChevronDown className="h-4 w-4 opacity-60" />
          </Button>
          {menuOpen ? (
            <div
              role="menu"
              className={cn(
                'absolute right-0 top-full z-50 mt-1 w-48 rounded-md border bg-card p-1 shadow-md',
              )}
              onMouseLeave={() => setMenuOpen(false)}
            >
              <button
                type="button"
                onClick={handleLogout}
                className="flex w-full items-center gap-2 rounded px-3 py-2 text-left text-sm hover:bg-accent"
              >
                <LogOut className="h-4 w-4" />
                Sign out
              </button>
            </div>
          ) : null}
        </div>
      </div>
    </header>
  );
}
