import { useState, useEffect, useRef } from 'react';
import { Bell, Menu, Search, LogOut, User, CheckCircle, AlertCircle } from 'lucide-react';

interface TopbarProps {
  title: string;
  subtitle: string;
  onMenuClick: () => void;
  onNavigate?: (page: string) => void;
}

const mockNotifications = [
  { id: 1, title: 'Novo Agendamento', message: 'João Silva marcou Cabelo às 14:00', type: 'info', time: '10 min atrás', read: false },
  { id: 2, title: 'Pagamento Recebido', message: 'Assinatura renovada com sucesso', type: 'success', time: '2 horas atrás', read: true },
  { id: 3, title: 'Estoque Baixo', message: 'Pomada modeladora abaixo de 5 unidades', type: 'warning', time: '1 dia atrás', read: true },
];

export default function Topbar({ title, subtitle, onMenuClick, onNavigate }: TopbarProps) {
  const [avatarInitials, setAvatarInitials] = useState('AD');
  const [tenantName, setTenantName] = useState('Administrador');
  const [email, setEmail] = useState('admin@agendapro.com');
  
  const [showNotifications, setShowNotifications] = useState(false);
  const [showProfile, setShowProfile] = useState(false);
  const [notifications, setNotifications] = useState<any[]>([]);
  
  const notifRef = useRef<HTMLDivElement>(null);
  const profileRef = useRef<HTMLDivElement>(null);

  const fetchNotifications = async () => {
    const slug = localStorage.getItem('agendapro_tenant_slug') || 'barbearia-premium';
    try {
      const res = await fetch(`/api/tenant/notifications?slug=${slug}`);
      if (res.ok) {
        const data = await res.json();
        setNotifications(data);
      }
    } catch (err) {
      console.error('Error fetching notifications:', err);
    }
  };

  useEffect(() => {
    const savedName = localStorage.getItem('agendapro_tenant_name');
    if (savedName) {
      setTenantName(savedName);
      const initials = savedName.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase();
      setAvatarInitials(initials || 'BJ');
    }
    const savedEmail = localStorage.getItem('agendapro_email');
    if (savedEmail) setEmail(savedEmail);

    fetchNotifications();

    const interval = setInterval(fetchNotifications, 15000); // Auto-refresh every 15s

    const handleClickOutside = (e: MouseEvent) => {
      if (notifRef.current && !notifRef.current.contains(e.target as Node)) setShowNotifications(false);
      if (profileRef.current && !profileRef.current.contains(e.target as Node)) setShowProfile(false);
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      clearInterval(interval);
    };
  }, []);

  const playNotificationSound = () => {
    try {
      const audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)();
      const oscillator = audioCtx.createOscillator();
      const gainNode = audioCtx.createGain();
      
      oscillator.type = 'sine';
      oscillator.frequency.setValueAtTime(880, audioCtx.currentTime); // A5
      oscillator.frequency.exponentialRampToValueAtTime(1760, audioCtx.currentTime + 0.1); // A6
      
      gainNode.gain.setValueAtTime(0.1, audioCtx.currentTime);
      gainNode.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.3);
      
      oscillator.connect(gainNode);
      gainNode.connect(audioCtx.destination);
      
      oscillator.start();
      oscillator.stop(audioCtx.currentTime + 0.3);
    } catch (e) {
      console.log('Audio not supported or blocked');
    }
  };

  const handleNotificationClick = () => {
    if (!showNotifications) {
      const unreadCount = notifications.filter(n => !n.read).length;
      if (unreadCount > 0) {
        playNotificationSound();
      }
    }
    setShowNotifications(!showNotifications);
    setShowProfile(false);
  };

  const handleProfileClick = () => {
    setShowProfile(!showProfile);
    setShowNotifications(false);
  };

  const markAllAsRead = async () => {
    const slug = localStorage.getItem('agendapro_tenant_slug') || 'barbearia-premium';
    setNotifications(notifications.map(n => ({ ...n, read: true })));
    try {
      await fetch('/api/tenant/notifications', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ slug }),
      });
    } catch (err) {
      console.error(err);
    }
  };

  const clearAllNotifications = async () => {
    const slug = localStorage.getItem('agendapro_tenant_slug') || 'barbearia-premium';
    setNotifications([]);
    try {
      await fetch(`/api/tenant/notifications?slug=${slug}`, {
        method: 'DELETE',
      });
    } catch (err) {
      console.error(err);
    }
  };

  const logout = () => {
    localStorage.removeItem('agendapro_token');
    localStorage.removeItem('agendapro_tenant_slug');
    localStorage.removeItem('agendapro_tenant_name');
    localStorage.removeItem('agendapro_email');
    localStorage.removeItem('agendapro_role');
    window.location.href = '/login';
  };

  const unreadCount = notifications.filter(n => !n.read).length;

  return (
    <header className="topbar">
      <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
        <button className="btn-ghost btn-icon" onClick={onMenuClick} style={{ display: 'none' }} id="menu-toggle">
          <Menu size={22} />
        </button>
        <div className="topbar-left">
          <h1>{title}</h1>
          <p>{subtitle}</p>
        </div>
      </div>
      
      <div className="topbar-right">
        <div className="search-box">
          <Search size={16} />
          <input className="form-input" placeholder="Buscar..." style={{ width: '240px', paddingLeft: '36px' }} />
        </div>
        
        <div style={{ position: 'relative' }} ref={notifRef}>
          <button className="btn-ghost btn-icon" style={{ position: 'relative' }} onClick={handleNotificationClick}>
            <Bell size={20} />
            {unreadCount > 0 && (
              <span style={{
                position: 'absolute', top: '4px', right: '4px',
                width: '10px', height: '10px', borderRadius: '50%',
                background: 'var(--danger)', border: '2px solid var(--bg-card)'
              }} />
            )}
          </button>
          
          {showNotifications && (
            <div className="card" style={{ 
              position: 'absolute', top: '100%', right: 0, marginTop: '8px', width: '320px', 
              padding: 0, zIndex: 100, boxShadow: 'var(--shadow-lg)', border: '1px solid var(--border-color)',
              animation: 'slideUp 0.2s ease-out forwards'
            }}>
              <div className="flex-between" style={{ padding: '12px 16px', borderBottom: '1px solid var(--border-color)' }}>
                <h3 style={{ fontSize: '14px', fontWeight: 600 }}>Notificações</h3>
                <div style={{ display: 'flex', gap: '8px' }}>
                  {unreadCount > 0 && (
                    <button className="btn-ghost" style={{ fontSize: '12px', padding: '4px 8px' }} onClick={markAllAsRead}>
                      Marcar lidas
                    </button>
                  )}
                  {notifications.length > 0 && (
                    <button className="btn-ghost" style={{ fontSize: '12px', padding: '4px 8px', color: 'var(--danger)' }} onClick={clearAllNotifications}>
                      Limpar
                    </button>
                  )}
                </div>
              </div>
              <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
                {notifications.map(n => (
                  <div key={n.id} style={{ 
                    padding: '12px 16px', borderBottom: '1px solid var(--border-color)',
                    background: n.read ? 'transparent' : 'rgba(59, 130, 246, 0.05)',
                    display: 'flex', gap: '12px', alignItems: 'flex-start'
                  }}>
                    <div style={{ 
                      width: '32px', height: '32px', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                      background: n.type === 'success' ? 'rgba(34, 197, 94, 0.1)' : n.type === 'warning' ? 'rgba(245, 158, 11, 0.1)' : 'rgba(59, 130, 246, 0.1)',
                      color: n.type === 'success' ? 'var(--success)' : n.type === 'warning' ? 'var(--warning)' : 'var(--primary)'
                    }}>
                      {n.type === 'success' ? <CheckCircle size={16} /> : n.type === 'warning' ? <AlertCircle size={16} /> : <Bell size={16} />}
                    </div>
                    <div>
                      <div style={{ fontSize: '13px', fontWeight: n.read ? 500 : 600, color: 'var(--text-primary)' }}>{n.title}</div>
                      <div style={{ fontSize: '12px', color: 'var(--text-secondary)', marginTop: '2px', lineHeight: 1.4 }}>{n.message}</div>
                      <div style={{ fontSize: '11px', color: 'var(--text-muted)', marginTop: '4px' }}>{n.time}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
        
        <div style={{ position: 'relative' }} ref={profileRef}>
          <div className="avatar" style={{ cursor: 'pointer', transition: 'transform 0.2s' }} onClick={handleProfileClick}>
            {avatarInitials}
          </div>
          
          {showProfile && (
            <div className="card" style={{ 
              position: 'absolute', top: '100%', right: 0, marginTop: '8px', width: '240px', 
              padding: '8px', zIndex: 100, boxShadow: 'var(--shadow-lg)', border: '1px solid var(--border-color)',
              animation: 'slideUp 0.2s ease-out forwards'
            }}>
              <div style={{ padding: '12px', borderBottom: '1px solid var(--border-color)', marginBottom: '8px' }}>
                <div style={{ fontWeight: 600, fontSize: '14px' }}>{tenantName}</div>
                <div style={{ color: 'var(--text-muted)', fontSize: '12px', marginTop: '2px' }}>{email}</div>
              </div>
              
              <button className="btn-ghost" onClick={() => { if(onNavigate) onNavigate('settings'); setShowProfile(false); }} style={{ width: '100%', justifyContent: 'flex-start', padding: '10px 12px', fontSize: '13px' }}>
                <User size={16} style={{ marginRight: '8px' }} /> Meu Perfil
              </button>
              <button className="btn-ghost" onClick={logout} style={{ width: '100%', justifyContent: 'flex-start', padding: '10px 12px', fontSize: '13px', color: 'var(--danger)' }}>
                <LogOut size={16} style={{ marginRight: '8px' }} /> Sair da conta
              </button>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}
