import React, { useState, useEffect, useRef } from 'react';
import { User, Post, Notification } from '../types';
import { TagIcon } from './icons/TagIcon';
import { PlusCircleIcon } from './icons/PlusCircleIcon';
import { TAG_REPOSITORY } from '../constants';
import { LogoutIcon } from './icons/LogoutIcon';
import { UserCircleIcon } from './icons/UserCircleIcon';
import { BellIcon } from './icons/BellIcon';
import { ShieldExclamationIcon } from './icons/ShieldExclamationIcon';

interface HeaderProps {
  currentUser: User;
  users: User[];
  posts: Post[];
  notifications: Notification[];
  onNavigate: (view: 'feed' | 'profile' | 'admin', userId: string) => void;
  onOpenCreateModal: () => void;
  onSearch: (tag: string) => void;
  onLogout: () => void;
  onMarkNotificationsAsRead: () => void;
}

type Suggestion = {
  type: 'tag' | 'user';
  value: string;
  data?: User;
};

const Header: React.FC<HeaderProps> = (props) => {
  const { currentUser, users, posts, notifications, onNavigate, onOpenCreateModal, onSearch, onLogout, onMarkNotificationsAsRead } = props;
  const [query, setQuery] = useState('');
  const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
  const searchRef = useRef<HTMLDivElement>(null);
  const [isMenuOpen, setMenuOpen] = useState(false);
  const [isNotificationsOpen, setNotificationsOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);
  const notificationsRef = useRef<HTMLDivElement>(null);
  
  const hasPendingReports = posts.some(p => p.reports && p.reports.length > 0);
  const hasUnreadNotifications = notifications.some(n => !n.read);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (searchRef.current && !searchRef.current.contains(event.target as Node)) {
        setSuggestions([]);
      }
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setMenuOpen(false);
      }
      if (notificationsRef.current && !notificationsRef.current.contains(event.target as Node)) {
        setNotificationsOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setQuery(value);
    onSearch(''); // Clear tag filter when typing a new query

    if (value.length > 1) {
      const lowercasedValue = value.toLowerCase();
      const tagSuggestions = TAG_REPOSITORY.filter(tag =>
        tag.includes(lowercasedValue)
      ).slice(0, 3).map(tag => ({ type: 'tag' as const, value: tag }));

      const userSuggestions = users.filter(user =>
        user.username.toLowerCase().includes(lowercasedValue)
      ).slice(0, 3).map(user => ({ type: 'user' as const, value: user.username, data: user }));
      
      setSuggestions([...userSuggestions, ...tagSuggestions]);
    } else {
      setSuggestions([]);
    }
  };
  
  const handleSuggestionClick = (suggestion: Suggestion) => {
    if (suggestion.type === 'tag') {
      onSearch(suggestion.value);
      setQuery(suggestion.value);
    } else if (suggestion.type === 'user' && suggestion.data) {
      onNavigate('profile', suggestion.data.id);
      setQuery('');
    }
    setSuggestions([]);
  };

  const handleNotificationsToggle = () => {
    setNotificationsOpen(!isNotificationsOpen);
    if (!isNotificationsOpen && hasUnreadNotifications) {
      onMarkNotificationsAsRead();
    }
  };

  const dashboardText = currentUser.role === 'admin' ? 'Admin Dashboard' : 'Moderator Dashboard';
  
  const SearchComponent = () => (
    <>
      <input
        type="text"
        placeholder="Search tags or users..."
        value={query}
        className="w-full px-4 py-2 bg-muted border border-accent rounded-full focus:outline-none focus:ring-2 focus:ring-primary"
        onChange={handleSearchChange}
        onFocus={handleSearchChange}
      />
      {suggestions.length > 0 && (
        <ul className="absolute z-20 w-full bg-background border border-accent mt-1 rounded-md shadow-lg">
          {suggestions.map((s, i) => (
            <li 
              key={`${s.type}-${s.value}-${i}`}
              onClick={() => handleSuggestionClick(s)}
              className="px-4 py-2 cursor-pointer hover:bg-muted flex items-center gap-3"
            >
              {s.type === 'user' && s.data && (
                <img src={s.data.avatar} alt={s.data.username} className="w-6 h-6 rounded-full" />
              )}
              {s.type === 'tag' && <TagIcon className="w-5 h-5 text-muted-foreground" />}
              <span>{s.value}</span>
              <span className="text-xs text-muted-foreground ml-auto capitalize">{s.type}</span>
            </li>
          ))}
        </ul>
      )}
    </>
  );

  return (
    <header className="bg-background/80 backdrop-blur-md fixed top-0 left-0 right-0 z-50 border-b border-muted">
      <div className="container mx-auto px-4 py-2 md:h-16 flex flex-wrap justify-between items-center" ref={searchRef}>
        <div 
          className="order-1 flex items-center gap-2 cursor-pointer text-foreground hover:text-secondary transition-colors"
          onClick={() => onNavigate('feed', currentUser.id)}
        >
          <TagIcon className="w-8 h-8"/>
          <h1 className="text-2xl font-bold">TagCraze</h1>
        </div>

        <div className="order-2 md:order-3 flex items-center gap-2">
          <button
            onClick={onOpenCreateModal}
            className="text-foreground hover:text-secondary transition-colors"
            aria-label="Create Post"
          >
            <PlusCircleIcon className="w-8 h-8" />
          </button>
          <div className="relative" ref={notificationsRef}>
            <button onClick={handleNotificationsToggle} className="text-foreground hover:text-secondary transition-colors relative" aria-label="Notifications">
              <BellIcon className="w-7 h-7" />
              {hasUnreadNotifications && <span className="absolute top-0 right-0 block h-2.5 w-2.5 rounded-full bg-destructive ring-2 ring-background" />}
            </button>
            {isNotificationsOpen && (
              <div className="absolute right-0 mt-3 w-80 bg-background rounded-lg shadow-lg z-20 border border-muted py-1">
                <div className="p-3 border-b border-muted">
                  <h3 className="font-semibold text-foreground">Notifications</h3>
                </div>
                <div className="max-h-80 overflow-y-auto">
                  {notifications.length > 0 ? (
                    notifications.map(n => (
                      <div key={n.id} className={`p-3 text-sm border-l-4 ${n.read ? 'border-transparent' : 'border-primary bg-muted'}`}>
                          <p>{n.message}</p>
                          <p className="text-xs text-muted-foreground mt-1">{new Date(n.createdAt).toLocaleString()}</p>
                      </div>
                    ))
                  ) : (
                    <p className="text-center text-muted-foreground py-4">No notifications yet.</p>
                  )}
                </div>
              </div>
            )}
          </div>
          <div className="relative" ref={menuRef}>
            <button onClick={() => setMenuOpen(!isMenuOpen)} aria-label="Open user menu">
                <img
                    src={currentUser.avatar}
                    alt={currentUser.username}
                    className="w-10 h-10 rounded-full cursor-pointer border-2 border-accent hover:border-primary transition-all"
                />
            </button>
            {isMenuOpen && (
                 <div className="absolute right-0 mt-2 w-56 bg-background rounded-md shadow-lg z-20 border border-muted py-1">
                     <button
                        onClick={() => { onNavigate('profile', currentUser.id); setMenuOpen(false); }}
                        className="flex items-center gap-2 w-full text-left px-4 py-2 text-sm text-foreground hover:bg-muted"
                     >
                        <UserCircleIcon className="w-5 h-5" /> Profile
                     </button>
                      {(currentUser.role === 'admin' || currentUser.role === 'moderator') && (
                        <button
                            onClick={() => { onNavigate('admin', currentUser.id); setMenuOpen(false); }}
                            className="flex items-center gap-2 w-full text-left px-4 py-2 text-sm text-foreground hover:bg-muted"
                        >
                            <ShieldExclamationIcon className={`w-5 h-5 ${hasPendingReports ? 'text-destructive' : 'text-secondary'}`} />
                            <span className={hasPendingReports ? 'text-destructive font-semibold' : 'text-foreground'}>{dashboardText}</span>
                        </button>
                      )}
                     <button
                        onClick={() => { onLogout(); setMenuOpen(false); }}
                        className="flex items-center gap-2 w-full text-left px-4 py-2 text-sm text-destructive hover:bg-muted"
                     >
                        <LogoutIcon className="w-5 h-5" /> Sign Out
                     </button>
                 </div>
            )}
          </div>
        </div>
        
        <div className="order-3 md:order-2 w-full md:w-auto md:flex-1 md:max-w-md md:mx-4 mt-2 md:mt-0 relative">
          <SearchComponent />
        </div>

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

export default Header;