import React, { useState } from 'react';
import { useCollege } from '../context/CollegeContext';
import {
  X,
  Bell,
  CheckCheck,
  AlertTriangle,
  Send,
  Volume2,
  VolumeX,
  Sparkles,
  Calendar,
  CreditCard,
  GraduationCap,
  MessageSquare,
  ShieldCheck,
  Radio,
} from 'lucide-react';
import { Role } from '../types';

interface NotificationDrawerProps {
  isOpen: boolean;
  onClose: () => void;
}

export const NotificationDrawer: React.FC<NotificationDrawerProps> = ({
  isOpen,
  onClose,
}) => {
  const {
    notifications,
    currentUser,
    markNotificationRead,
    clearAllNotifications,
    broadcastUrgentAlert,
  } = useCollege();

  const [activeFilter, setActiveFilter] = useState<'all' | 'urgent' | 'attendance' | 'fee' | 'grade'>('all');
  const [showBroadcastBox, setShowBroadcastBox] = useState(false);
  const [broadcastTitle, setBroadcastTitle] = useState('');
  const [broadcastMessage, setBroadcastMessage] = useState('');
  const [targetAudience, setTargetAudience] = useState<Role | 'all'>('all');
  const [soundEnabled, setSoundEnabled] = useState(true);

  if (!isOpen) return null;

  const userNotifications = notifications.filter(n => {
    if (n.targetRole !== 'all' && n.targetRole !== currentUser.role) {
      if (!n.targetUserId || n.targetUserId !== currentUser.id) {
        return false;
      }
    }
    if (activeFilter !== 'all' && n.type !== activeFilter) {
      return false;
    }
    return true;
  });

  const handleSendBroadcast = (e: React.FormEvent) => {
    e.preventDefault();
    if (!broadcastTitle || !broadcastMessage) return;

    broadcastUrgentAlert(broadcastTitle, broadcastMessage, targetAudience);
    setBroadcastTitle('');
    setBroadcastMessage('');
    setShowBroadcastBox(false);

    // Audio chime simulation
    if (soundEnabled) {
      try {
        const audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)();
        const osc = audioCtx.createOscillator();
        const gain = audioCtx.createGain();
        osc.connect(gain);
        gain.connect(audioCtx.destination);
        osc.frequency.setValueAtTime(587.33, audioCtx.currentTime); // D5
        gain.gain.setValueAtTime(0.1, audioCtx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.5);
        osc.start();
        osc.stop(audioCtx.currentTime + 0.5);
      } catch (err) {}
    }
  };

  const getNotifIcon = (type: string) => {
    switch (type) {
      case 'urgent':
        return <AlertTriangle className="w-4 h-4 text-rose-600" />;
      case 'attendance':
        return <Radio className="w-4 h-4 text-amber-600" />;
      case 'fee':
        return <CreditCard className="w-4 h-4 text-emerald-600" />;
      case 'grade':
        return <GraduationCap className="w-4 h-4 text-blue-600" />;
      case 'message':
        return <MessageSquare className="w-4 h-4 text-purple-600" />;
      default:
        return <Bell className="w-4 h-4 text-slate-600" />;
    }
  };

  return (
    <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex justify-end animate-in fade-in">
      <div className="bg-white w-full max-w-md h-full shadow-2xl flex flex-col border-l border-slate-200 animate-in slide-in-from-right duration-200">
        
        {/* Drawer Header */}
        <div className="bg-slate-900 text-white px-5 py-4 flex items-center justify-between border-b border-slate-800 shrink-0">
          <div className="flex items-center gap-2.5">
            <div className="w-8 h-8 rounded-lg bg-emerald-600 flex items-center justify-center text-white">
              <Bell className="w-4 h-4" />
            </div>
            <div>
              <h2 className="text-sm font-bold text-white">Notifications & Alerts</h2>
              <p className="text-[11px] text-emerald-400 font-mono">
                Push Alert Subsystem • Real-time Feeds
              </p>
            </div>
          </div>

          <div className="flex items-center gap-1">
            <button
              onClick={() => setSoundEnabled(!soundEnabled)}
              title={soundEnabled ? 'Push chime enabled' : 'Muted'}
              className="p-1.5 text-slate-400 hover:text-white rounded-lg"
            >
              {soundEnabled ? <Volume2 className="w-4 h-4 text-emerald-400" /> : <VolumeX className="w-4 h-4" />}
            </button>
            <button
              onClick={onClose}
              className="p-1.5 text-slate-400 hover:text-white rounded-lg"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Action / Filter Bar */}
        <div className="p-3 bg-slate-50 border-b border-slate-200 space-y-2 shrink-0">
          <div className="flex items-center justify-between">
            <div className="flex gap-1 overflow-x-auto no-scrollbar text-xs">
              {(['all', 'urgent', 'attendance', 'fee', 'grade'] as const).map(tab => (
                <button
                  key={tab}
                  onClick={() => setActiveFilter(tab)}
                  className={`px-2 py-1 rounded-md text-[11px] font-semibold capitalize transition ${
                    activeFilter === tab
                      ? 'bg-slate-900 text-white'
                      : 'bg-white text-slate-600 hover:bg-slate-200 border border-slate-200'
                  }`}
                >
                  {tab}
                </button>
              ))}
            </div>

            <button
              onClick={clearAllNotifications}
              className="text-[11px] text-emerald-700 hover:text-emerald-900 font-semibold flex items-center gap-1 shrink-0"
            >
              <CheckCheck className="w-3.5 h-3.5" />
              Mark Read
            </button>
          </div>

          {/* Admin Broadcast Button */}
          {currentUser.role === 'admin' && (
            <button
              onClick={() => setShowBroadcastBox(!showBroadcastBox)}
              className="w-full py-1.5 bg-rose-600 hover:bg-rose-700 text-white text-xs font-bold rounded-lg transition shadow-xs flex items-center justify-center gap-1.5"
            >
              <AlertTriangle className="w-3.5 h-3.5" />
              {showBroadcastBox ? 'Close Broadcast Composer' : 'Broadcast Urgent Push Alert'}
            </button>
          )}
        </div>

        {/* Broadcast Composer (Admin) */}
        {showBroadcastBox && (
          <form onSubmit={handleSendBroadcast} className="p-4 bg-rose-50 border-b border-rose-200 space-y-2 text-xs animate-in fade-in shrink-0">
            <h3 className="font-bold text-rose-950 flex items-center gap-1.5 text-xs">
              <Radio className="w-3.5 h-3.5 text-rose-600" />
              Broadcast Urgent Push Notification to College
            </h3>

            <div>
              <label className="block font-semibold text-slate-700 mb-0.5 text-[11px]">ALERT TITLE</label>
              <input
                type="text"
                required
                placeholder="e.g. Examination Hall Allocation Update"
                value={broadcastTitle}
                onChange={e => setBroadcastTitle(e.target.value)}
                className="w-full px-2.5 py-1.5 bg-white border border-rose-300 rounded-md text-xs focus:outline-none"
              />
            </div>

            <div>
              <label className="block font-semibold text-slate-700 mb-0.5 text-[11px]">MESSAGE BODY</label>
              <textarea
                rows={2}
                required
                placeholder="Details of the announcement for SMS & push notification..."
                value={broadcastMessage}
                onChange={e => setBroadcastMessage(e.target.value)}
                className="w-full px-2.5 py-1.5 bg-white border border-rose-300 rounded-md text-xs focus:outline-none"
              />
            </div>

            <div className="flex items-center justify-between pt-1">
              <select
                value={targetAudience}
                onChange={e => setTargetAudience(e.target.value as any)}
                className="text-[11px] p-1 border border-slate-300 rounded bg-white"
              >
                <option value="all">Send to All Roles</option>
                <option value="student">Students Only</option>
                <option value="parent">Parents Only</option>
                <option value="teacher">Lecturers Only</option>
              </select>

              <button
                type="submit"
                className="px-3 py-1 bg-rose-600 hover:bg-rose-700 text-white font-bold rounded text-xs flex items-center gap-1 shadow-sm"
              >
                <Send className="w-3 h-3" />
                Dispatch Alert
              </button>
            </div>
          </form>
        )}

        {/* Notifications List */}
        <div className="flex-1 overflow-y-auto p-4 space-y-3">
          {userNotifications.length === 0 ? (
            <div className="py-12 text-center text-slate-400 space-y-2">
              <Bell className="w-8 h-8 mx-auto text-slate-300" />
              <p className="text-xs">No notifications in this filter.</p>
            </div>
          ) : (
            userNotifications.map(notif => (
              <div
                key={notif.id}
                onClick={() => markNotificationRead(notif.id)}
                className={`p-3.5 rounded-xl border text-xs cursor-pointer transition relative space-y-1.5 ${
                  notif.read
                    ? 'bg-white border-slate-200 opacity-80'
                    : notif.type === 'urgent'
                    ? 'bg-rose-50/70 border-rose-300 shadow-xs'
                    : notif.type === 'attendance'
                    ? 'bg-amber-50/70 border-amber-300 shadow-xs'
                    : 'bg-emerald-50/50 border-emerald-300 shadow-xs'
                }`}
              >
                {!notif.read && (
                  <span className="absolute top-3 right-3 w-2 h-2 rounded-full bg-emerald-600 animate-pulse"></span>
                )}

                <div className="flex items-center gap-2">
                  <div className="p-1 rounded-md bg-white border border-slate-200">
                    {getNotifIcon(notif.type)}
                  </div>
                  <h4 className="font-bold text-slate-900 text-xs pr-4">{notif.title}</h4>
                </div>

                <p className="text-slate-700 leading-relaxed text-[11px]">{notif.message}</p>

                <div className="flex items-center justify-between text-[10px] text-slate-400 pt-1">
                  <span>{notif.timestamp}</span>
                  <span className="capitalize font-semibold text-slate-500">{notif.type}</span>
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
};
