import { useState, useEffect } from 'react';
import { AlertTriangle, Info, Bell, X, Check, ChevronDown, ChevronUp } from 'lucide-react';
import { messagingApi, Announcement } from '../lib/messagingApi';

export default function AnnouncementBanner() {
    const [announcements, setAnnouncements] = useState<Announcement[]>([]);
    const [expanded, setExpanded] = useState(false);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        loadAnnouncements();
        // Poll for new announcements every 5 minutes
        const interval = setInterval(loadAnnouncements, 5 * 60 * 1000);
        return () => clearInterval(interval);
    }, []);

    const loadAnnouncements = async () => {
        try {
            const data = await messagingApi.getAnnouncements();
            // Only show unread or critical announcements
            const relevant = data.filter(a =>
                !a.isRead || a.priority === 'CRITICAL' || (a.requiresAck && !a.isAcknowledged)
            );
            setAnnouncements(relevant);
        } catch (error) {
            console.error('Failed to load announcements:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleDismiss = async (id: string) => {
        try {
            await messagingApi.markRead(id);
            setAnnouncements(prev => prev.filter(a => a.id !== id || a.requiresAck));
        } catch (error) {
            console.error('Failed to dismiss:', error);
        }
    };

    const handleAcknowledge = async (id: string) => {
        try {
            await messagingApi.acknowledge(id);
            setAnnouncements(prev => prev.map(a =>
                a.id === id ? { ...a, isAcknowledged: true } : a
            ));
        } catch (error) {
            console.error('Failed to acknowledge:', error);
        }
    };

    // Don't render if no announcements
    if (loading || announcements.length === 0) return null;

    const criticalAnnouncements = announcements.filter(a => a.priority === 'CRITICAL');
    const hasCritical = criticalAnnouncements.length > 0;
    const pendingAck = announcements.filter(a => a.requiresAck && !a.isAcknowledged);

    const getPriorityIcon = (priority: string) => {
        switch (priority) {
            case 'CRITICAL': return <AlertTriangle className="text-red-400" size={18} />;
            case 'WARNING': return <AlertTriangle className="text-amber-400" size={18} />;
            default: return <Info className="text-blue-400" size={18} />;
        }
    };

    const getPriorityStyles = (priority: string) => {
        switch (priority) {
            case 'CRITICAL': return 'bg-red-500/10 border-red-500/30';
            case 'WARNING': return 'bg-[var(--color-warning)]/10 border-amber-500/30';
            default: return 'bg-[var(--color-accent)]/10 border-blue-500/30';
        }
    };

    // Show first/critical announcement in collapsed view
    const topAnnouncement = hasCritical ? criticalAnnouncements[0] : announcements[0];

    return (
        <div className="px-4 py-2 space-y-2">
            {/* Main Banner */}
            <div
                className={`rounded-lg border p-3 flex items-center gap-3 cursor-pointer transition-colors
                    ${getPriorityStyles(topAnnouncement.priority)}`}
                onClick={() => setExpanded(!expanded)}
            >
                {getPriorityIcon(topAnnouncement.priority)}

                <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                        <span className="font-medium text-white truncate">{topAnnouncement.title}</span>
                        {announcements.length > 1 && (
                            <span className="text-xs bg-slate-700 px-2 py-0.5 rounded text-slate-300">
                                +{announcements.length - 1} more
                            </span>
                        )}
                        {pendingAck.length > 0 && (
                            <span className="text-xs bg-red-500/20 text-red-400 px-2 py-0.5 rounded flex items-center gap-1">
                                <Bell size={12} />
                                {pendingAck.length} requires acknowledgement
                            </span>
                        )}
                    </div>
                    {!expanded && (
                        <p className="text-sm text-[var(--color-text-tertiary)] truncate">{topAnnouncement.body}</p>
                    )}
                </div>

                <div className="flex items-center gap-2">
                    {topAnnouncement.requiresAck && !topAnnouncement.isAcknowledged && (
                        <button
                            onClick={(e) => { e.stopPropagation(); handleAcknowledge(topAnnouncement.id); }}
                            className="bg-[var(--color-primary)] hover:bg-[var(--color-primary)] text-white text-xs px-3 py-1.5 rounded flex items-center gap-1"
                        >
                            <Check size={14} />
                            Acknowledge
                        </button>
                    )}
                    {!topAnnouncement.requiresAck && (
                        <button
                            onClick={(e) => { e.stopPropagation(); handleDismiss(topAnnouncement.id); }}
                            className="text-[var(--color-text-tertiary)] hover:text-white p-1"
                        >
                            <X size={16} />
                        </button>
                    )}
                    {expanded ? <ChevronUp size={18} className="text-[var(--color-text-tertiary)]" /> : <ChevronDown size={18} className="text-[var(--color-text-tertiary)]" />}
                </div>
            </div>

            {/* Expanded List */}
            {expanded && announcements.length > 0 && (
                <div className="space-y-2 pl-4 border-l-2 border-slate-700">
                    {announcements.map(a => (
                        <div
                            key={a.id}
                            className={`rounded-lg border p-3 ${getPriorityStyles(a.priority)}`}
                        >
                            <div className="flex items-start gap-3">
                                {getPriorityIcon(a.priority)}
                                <div className="flex-1">
                                    <div className="flex items-center gap-2 mb-1">
                                        <span className="font-medium text-white">{a.title}</span>
                                        {a.isAcknowledged && (
                                            <span className="text-xs bg-[var(--color-primary)]/20 text-emerald-400 px-2 py-0.5 rounded">
                                                Acknowledged
                                            </span>
                                        )}
                                    </div>
                                    <p className="text-sm text-slate-300">{a.body}</p>
                                    <p className="text-xs text-[var(--color-text-tertiary)] mt-1">
                                        By {a.createdBy.name} • {new Date(a.createdAt).toLocaleString()}
                                    </p>
                                </div>
                                <div className="flex items-center gap-2">
                                    {a.requiresAck && !a.isAcknowledged && (
                                        <button
                                            onClick={() => handleAcknowledge(a.id)}
                                            className="bg-[var(--color-primary)] hover:bg-[var(--color-primary)] text-white text-xs px-3 py-1.5 rounded flex items-center gap-1"
                                        >
                                            <Check size={14} />
                                            Acknowledge
                                        </button>
                                    )}
                                    {!a.requiresAck && !a.isRead && (
                                        <button
                                            onClick={() => handleDismiss(a.id)}
                                            className="text-[var(--color-text-tertiary)] hover:text-white p-1"
                                        >
                                            <X size={16} />
                                        </button>
                                    )}
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}
