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

interface HeaderProps {
  userEmail?: string;
}

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

  // const handleLogout = () => {
  //   localStorage.removeItem('user');
  //   localStorage.removeItem('sid');
  //   navigate('/login');
  // };

  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-end gap-2 flex-shrink-0">
      {/* User Email (optional, can be shown on hover or always) */}
      {/* {userEmail && (
        <div className="hidden md:block text-sm text-gray-600 dark:text-gray-400 mr-2">
          {userEmail}
        </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>
    </header>
  );
};

export default Header;


