import { useCallback, useEffect, useRef, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Bell, CalendarDays, LogOut, Menu, Search, Settings } from 'lucide-react';
import { useAuth } from '../context/AuthContext';
import api from '../services/api';
import ThemeModeToggle from './ThemeModeToggle';
import CalendarPopover from './CalendarPopover';
import NotificationCenter from './NotificationCenter';
import EntityPreviewModal from './EntityPreviewModal';
import useDismissibleLayer from '../hooks/useDismissibleLayer';
import Modal from './Modal';
import Profile from '../pages/Profile';

export default function Header({ title, collapsed = false, mobileNavOpen = false, onToggleMobileNav }) {
  const { user, logout } = useAuth();
  const navigate = useNavigate();
  const [activeLayer, setActiveLayer] = useState(null);
  const [previewItem, setPreviewItem] = useState(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [searching, setSearching] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);
  const calendarButtonRef = useRef(null);
  const calendarPanelRef = useRef(null);
  const notificationButtonRef = useRef(null);
  const notificationPanelRef = useRef(null);
  const profileButtonRef = useRef(null);

  const closeLayer = useCallback(() => setActiveLayer(null), []);
  const layerRefs = activeLayer === 'calendar'
    ? [calendarButtonRef, calendarPanelRef]
    : [notificationButtonRef, notificationPanelRef];
  useDismissibleLayer(activeLayer === 'calendar' || activeLayer === 'notifications', layerRefs, closeLayer);

  const fetchUnreadCount = useCallback(async () => {
    try {
      const { data } = await api.get('/notifications', { params: { per_page: 1, unread: 1 } });
      setUnreadCount(data.meta?.unread_count || 0);
    } catch {
      setUnreadCount(0);
    }
  }, []);

  useEffect(() => {
    fetchUnreadCount();
    const timer = window.setInterval(fetchUnreadCount, 60000);
    return () => window.clearInterval(timer);
  }, [fetchUnreadCount]);

  const handleSearch = async (event) => {
    const query = event.target.value;
    setSearchQuery(query);
    if (query.length < 2) { setSearchResults([]); return; }
    setSearching(true);
    try {
      const { data } = await api.get('/search', { params: { q: query } });
      setSearchResults(data.data || []);
    } catch {
      setSearchResults([]);
    } finally {
      setSearching(false);
    }
  };

  const toggleLayer = (name) => setActiveLayer((current) => current === name ? null : name);

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

  const openPreview = (item) => {
    closeLayer();
    setPreviewItem(item);
  };

  return (
    <>
      <header className="app-header" style={{ right: collapsed ? 72 : 'var(--sidebar-width)' }}>
        <h1>{title}</h1>
        <div className="header-search">
          <input value={searchQuery} onChange={handleSearch} placeholder="جستجوی پروژه، تسک، کاربر..." className="form-input" />
          <Search size={18} />
          {searching && <span className="header-searching">...</span>}
          {searchResults.length > 0 && (
            <div className="header-search-results">
              {searchResults.slice(0, 5).map((item, index) => (
                <Link key={`${item.url}-${index}`} to={item.url || '#'} onClick={() => { setSearchResults([]); setSearchQuery(''); }}>
                  <strong>{item.title || item.name}</strong>
                  {item.type && <small>{item.type}</small>}
                </Link>
              ))}
            </div>
          )}
        </div>

        <div className="header-actions">
          <button
            type="button"
            className={`header-icon-button mobile-nav-toggle ${mobileNavOpen ? 'active' : ''}`}
            onClick={onToggleMobileNav}
            aria-label={mobileNavOpen ? 'بستن منوی اصلی' : 'باز کردن منوی اصلی'}
            aria-controls="main-navigation-drawer"
            aria-expanded={mobileNavOpen}
          >
            <Menu size={20} />
          </button>
          <div className="header-layer">
            <button ref={calendarButtonRef} type="button" className={`header-icon-button ${activeLayer === 'calendar' ? 'active' : ''}`} onClick={() => toggleLayer('calendar')} aria-label="تقویم رویدادها" aria-expanded={activeLayer === 'calendar'}>
              <CalendarDays size={20} />
            </button>
            {activeLayer === 'calendar' && <div ref={calendarPanelRef} className="header-popover calendar-layer"><CalendarPopover onSelectEvent={openPreview} /></div>}
          </div>

          <ThemeModeToggle compact />

          <div className="header-layer">
            <button ref={notificationButtonRef} type="button" className={`header-icon-button ${activeLayer === 'notifications' ? 'active' : ''}`} onClick={() => toggleLayer('notifications')} aria-label="اعلان‌ها" aria-expanded={activeLayer === 'notifications'}>
              <Bell size={20} />
              {unreadCount > 0 && <span className="header-badge">{unreadCount > 99 ? '۹۹+' : unreadCount}</span>}
            </button>
            {activeLayer === 'notifications' && (
              <div ref={notificationPanelRef} className="header-popover notification-layer">
                <NotificationCenter onOpenNotification={openPreview} onCountChange={setUnreadCount} />
              </div>
            )}
          </div>

          <div className="header-layer">
            <button ref={profileButtonRef} type="button" className={`header-profile ${activeLayer === 'profile' ? 'active' : ''}`} onClick={() => toggleLayer('profile')} aria-label="باز کردن پروفایل کاربری" aria-haspopup="dialog" aria-expanded={activeLayer === 'profile'}>
              {user?.avatar_url ? <img className="avatar avatar-sm avatar-img" src={user.avatar_url} alt="" /> : <span className="avatar avatar-sm">{user?.name?.[0] || '?'}</span>}
              <span>{user?.name}</span>
            </button>
          </div>
        </div>
      </header>
      {activeLayer === 'profile' && (
        <Modal
          title="پروفایل کاربری"
          size="xl"
          onClose={closeLayer}
          footer={(
            <div className="profile-modal-actions">
              <button type="button" className="btn btn-secondary" onClick={() => { closeLayer(); navigate('/settings'); }}>
                <Settings size={17} />
                تنظیمات
              </button>
              <button type="button" className="btn btn-danger profile-logout-button" onClick={handleLogout}>
                <LogOut size={17} />
                خروج از حساب
              </button>
            </div>
          )}
        >
          <Profile embedded />
        </Modal>
      )}
      <EntityPreviewModal item={previewItem} onClose={() => setPreviewItem(null)} />
    </>
  );
}
