'use client';

import { useState, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { useTranslation } from 'react-i18next';
import { useTenantStore } from '@/stores/zustand/tenant-store';
import { Search, Bell, LogOut, User, Settings } from 'lucide-react';

interface StoredUser {
  id: string;
  email: string;
  name: string;
  roles: string[];
}

export function TopBar() {
  const router = useRouter();
  const { t } = useTranslation('topbar');
  const { currentTenant } = useTenantStore();
  const [menuOpen, setMenuOpen] = useState(false);
  const [user, setUser] = useState<StoredUser | null>(null);
  const menuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    try {
      const raw = localStorage.getItem('user');
      if (raw) setUser(JSON.parse(raw));
    } catch { /* ignore */ }
  }, []);

  // Close menu on outside click
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        setMenuOpen(false);
      }
    }
    if (menuOpen) document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [menuOpen]);

  const handleLogout = () => {
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    localStorage.removeItem('user');
    localStorage.removeItem('current_tenant');
    router.replace('/login');
  };

  const initials = user?.name
    ? user.name.split(' ').map((w) => w[0]).join('').toUpperCase().slice(0, 2)
    : 'U';

  return (
    <header className="h-12 border-b bg-card/50 backdrop-blur-sm flex items-center justify-between px-4 shrink-0">
      {/* Left: search / command palette */}
      <button
        className="flex items-center gap-2 px-3 py-1.5 rounded-md border border-border/60
                   text-muted-foreground hover:text-foreground hover:border-border
                   transition-colors text-xs w-56"
        onClick={() => {
          /* TODO: open command palette */
        }}
      >
        <Search className="h-3.5 w-3.5 shrink-0" />
        <span className="flex-1 text-left">{t('search')}</span>
        <kbd className="text-[10px] bg-muted/60 px-1.5 py-0.5 rounded border border-border/40 font-mono">
          {t('shortcutKey')}
        </kbd>
      </button>

      {/* Right: tenant + user */}
      <div className="flex items-center gap-3">
        {/* Notification bell */}
        <button className="relative p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent transition-colors">
          <Bell className="h-4 w-4" />
        </button>

        {/* Divider */}
        <div className="h-5 w-px bg-border" />

        {/* Tenant indicator — hidden for platform admins */}
        {!user?.roles?.some((r) => r === 'platform_admin' || r === 'platform_super_admin') && (
          <div className="text-xs">
            <span className="text-muted-foreground">{t('tenant')} </span>
            <span className="font-medium">{currentTenant?.name || currentTenant?.id || t('notSelected')}</span>
          </div>
        )}

        {/* User avatar + dropdown */}
        <div className="relative" ref={menuRef}>
          <button
            onClick={() => setMenuOpen(!menuOpen)}
            className="w-7 h-7 rounded-full bg-primary/15 border border-primary/20 flex items-center justify-center text-xs font-semibold text-primary hover:bg-primary/25 transition-colors"
          >
            {initials}
          </button>

          {menuOpen && (
            <div className="absolute right-0 top-full mt-1.5 w-56 bg-card border rounded-lg shadow-lg py-1 z-50">
              {/* User info */}
              <div className="px-3 py-2 border-b">
                <p className="text-sm font-medium truncate">{user?.name || t('defaultUser')}</p>
                <p className="text-xs text-muted-foreground truncate">{user?.email}</p>
              </div>

              {/* Menu items */}
              <button
                onClick={() => { setMenuOpen(false); router.push('/settings'); }}
                className="w-full flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
              >
                <Settings className="h-3.5 w-3.5" />
                {t('settings')}
              </button>
              <button
                onClick={() => { setMenuOpen(false); router.push('/users'); }}
                className="w-full flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
              >
                <User className="h-3.5 w-3.5" />
                {t('users')}
              </button>

              <div className="border-t my-1" />

              <button
                onClick={handleLogout}
                className="w-full flex items-center gap-2 px-3 py-2 text-sm text-red-500 hover:bg-red-500/10 transition-colors"
              >
                <LogOut className="h-3.5 w-3.5" />
                {t('signOut')}
              </button>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}
