import React, { useState, useEffect } from 'react';
import { useTheme } from '../contexts/ThemeContext';
import { useLanguage } from '../contexts/LanguageContext';
import { useTranslation } from 'react-i18next';
import { Moon, Sun, Languages, LogOut, Menu, UserCircle } from 'lucide-react';
import NotificationBell from './NotificationBell';
import { useSidebarLayout } from '../contexts/SidebarLayoutContext';
import { useNavigate } from 'react-router-dom';

interface HeaderProps {
  userEmail?: string;
}

const Header: React.FC<HeaderProps> = () => {
  const { theme, toggleTheme } = useTheme();
  const { language, changeLanguage } = useLanguage();
  const { t } = useTranslation();
  const { openMobileSidebar } = useSidebarLayout();
  const navigate = useNavigate();

  const [userFullName, setUserFullName] = useState<string>('');
  const [showTooltip, setShowTooltip] = useState(false);

  // Fetch full name — same two-call pattern as Sidebar
  useEffect(() => {
    const fetchUserFullName = async () => {
      try {
        const userResponse = await fetch('/api/method/frappe.auth.get_logged_user', {
          method: 'GET',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
        });
        const userData = await userResponse.json();
        const email = userData.message;

        if (email) {
          const fullNameResponse = await fetch(
            `/api/resource/User/${encodeURIComponent(email)}?fields=["full_name"]`,
            {
              method: 'GET',
              headers: { 'Content-Type': 'application/json' },
              credentials: 'include',
            }
          );
          const fullNameData = await fullNameResponse.json();
          if (fullNameData.data?.full_name) {
            setUserFullName(fullNameData.data.full_name);
          } else {
            setUserFullName(email);
          }
        }
      } catch (err) {
        console.error('Error fetching user full name:', err);
      }
    };

    fetchUserFullName();
  }, []);

  const handleLogout = async () => {
    localStorage.removeItem('user');
    localStorage.removeItem('sid');

    try {
      const csrfToken = document.cookie
        .split('; ')
        .find(row => row.startsWith('X-Frappe-CSRF-Token='))
        ?.split('=')[1] || '';

      // Step 1: Kill server-side session in Redis
      await fetch('/api/method/frappe.auth.logout', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Frappe-CSRF-Token': csrfToken,
        },
        credentials: 'include',
      });

      // Step 2: Clear Frappe web session cookies fully
      await fetch('/?cmd=web_logout', {
        credentials: 'include',
      });

    } catch (err) {
      console.error('Logout error:', err);
    } finally {
      window.location.href = '/asm_app/login';
    }
  };

  return (
    <header className="h-14 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 flex items-center justify-between gap-2 flex-shrink-0">
      {/* Mobile menu button */}
      <button
        type="button"
        onClick={openMobileSidebar}
        className="lg:hidden p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors text-gray-700 dark:text-gray-300 -ms-1"
        aria-label={t('common.menu', { defaultValue: 'Open menu' })}
        title={t('common.menu', { defaultValue: 'Menu' })}
      >
        <Menu size={22} />
      </button>

      <div className="flex-1 lg:flex-none" aria-hidden="true" />

      <div className="flex items-center justify-end gap-2">

        {/* User Profile Icon with tooltip */}
        {userFullName && (
          <div className="relative">
            <button
              type="button"
              onClick={() => navigate('/user-profile')}
              onMouseEnter={() => setShowTooltip(true)}
              onMouseLeave={() => setShowTooltip(false)}
              // className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors text-gray-700 dark:text-gray-300"
              // title={userFullName}
              className="p-2 rounded-lg bg-[#7911cc] hover:bg-[#6a0fb5] transition-colors text-white"
              title={userFullName}
            >
              <UserCircle size={20} />
            </button>
            {showTooltip && (
              <div className="absolute right-0 top-full mt-1 z-50 px-3 py-1.5 bg-gray-800 dark:bg-gray-700 text-white text-xs rounded-lg whitespace-nowrap shadow-lg">
                {userFullName}
                {/* Tooltip arrow */}
                <div className="absolute -top-1 right-3 w-2 h-2 bg-gray-800 dark:bg-gray-700 rotate-45" />
              </div>
            )}
          </div>
        )}

        {/* Notification Bell */}
        <div className="relative">
          <NotificationBell />
        </div>

        {/* Language Toggle */}
        <button
          onClick={() => changeLanguage(language === 'en' ? 'ar' : 'en')}
          className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors text-gray-700 dark:text-gray-300"
          title={t('common.language')}
        >
          <Languages size={20} />
        </button>

        {/* Theme Toggle */}
        <button
          onClick={toggleTheme}
          className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors text-gray-700 dark:text-gray-300"
          title={theme === 'light' ? t('common.darkMode') : t('common.lightMode')}
        >
          {theme === 'light' ? <Moon size={20} /> : <Sun size={20} />}
        </button>

        {/* Logout */}
        <button
          onClick={handleLogout}
          className="p-2 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors text-red-600 dark:text-red-400"
          title={t('common.logout')}
        >
          <LogOut size={20} />
        </button>

      </div>
    </header>
  );
};

export default Header;