import React, { useState } from 'react';
import { useCollege } from '../context/CollegeContext';
import {
  X,
  Calendar,
  Clock,
  MapPin,
  Download,
  Plus,
  Filter,
  CheckCircle2,
  CalendarCheck,
  Share2,
  Users,
  AlertCircle,
  Tag,
} from 'lucide-react';
import { CollegeEvent } from '../types';

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

export const CalendarSyncModal: React.FC<CalendarSyncModalProps> = ({
  isOpen,
  onClose,
}) => {
  const { events, addCollegeEvent, currentUser } = useCollege();
  const [selectedCategory, setSelectedCategory] = useState<string>('All');
  const [showAddForm, setShowAddForm] = useState(false);
  const [copiedSyncLink, setCopiedSyncLink] = useState(false);

  // New Event Form State (Admin)
  const [newEvent, setNewEvent] = useState({
    title: '',
    date: new Date().toISOString().split('T')[0],
    endDate: '',
    time: '09:00 AM - 04:00 PM',
    location: 'Main Auditorium, Soche Technical College',
    category: 'Academic' as CollegeEvent['category'],
    description: '',
    targetAudience: 'All' as CollegeEvent['targetAudience'],
    isImportant: true,
  });

  if (!isOpen) return null;

  const filteredEvents = selectedCategory === 'All'
    ? events
    : events.filter(e => e.category === selectedCategory);

  const handleCreateEvent = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newEvent.title || !newEvent.date) return;

    addCollegeEvent(newEvent);
    setShowAddForm(false);
    setNewEvent({
      title: '',
      date: new Date().toISOString().split('T')[0],
      endDate: '',
      time: '09:00 AM - 04:00 PM',
      location: 'Main Auditorium, Soche Technical College',
      category: 'Academic',
      description: '',
      targetAudience: 'All',
      isImportant: true,
    });
  };

  // Export .ics calendar file
  const downloadIcsFile = () => {
    let icsContent = `BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//Soche Technical College//CMS Event Calendar//EN\nCALSCALE:GREGORIAN\nMETHOD:PUBLISH\nX-WR-CALNAME:Soche Technical College Academic Calendar\n`;

    events.forEach(evt => {
      const cleanDate = evt.date.replace(/-/g, '');
      icsContent += `BEGIN:VEVENT\nSUMMARY:${evt.title}\nDESCRIPTION:${evt.description}\nLOCATION:${evt.location}\nDTSTART;VALUE=DATE:${cleanDate}\nSTATUS:CONFIRMED\nEND:VEVENT\n`;
    });

    icsContent += `END:VCALENDAR`;

    const blob = new Blob([icsContent], { type: 'text/calendar;charset=utf-8' });
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.setAttribute('download', 'soche_college_calendar_2026.ics');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const handleCopySyncUrl = () => {
    navigator.clipboard?.writeText('webcal://sochetech.org/api/calendar/sync.ics');
    setCopiedSyncLink(true);
    setTimeout(() => setCopiedSyncLink(false), 3000);
  };

  return (
    <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-2 sm:p-4 overflow-y-auto">
      <div className="bg-white rounded-2xl shadow-2xl max-w-3xl w-full max-h-[92vh] flex flex-col overflow-hidden border border-slate-200 animate-in fade-in zoom-in-95">
        
        {/* Modal Header */}
        <div className="bg-slate-900 text-white px-6 py-4 flex items-center justify-between border-b border-slate-800 shrink-0">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-emerald-600 border border-emerald-400 flex items-center justify-center font-bold text-white shadow-sm">
              <Calendar className="w-5 h-5" />
            </div>
            <div>
              <h2 className="text-base font-bold tracking-tight text-white leading-tight">
                Academic Calendar & Event Schedules
              </h2>
              <p className="text-xs text-emerald-400 font-mono">
                July 2026 Intake • Examinations & Key Milestones
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            aria-label="Close modal"
            className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-800 rounded-lg transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Action Header Banner */}
        <div className="bg-slate-100 border-b border-slate-200 px-6 py-3 flex flex-wrap items-center justify-between gap-3 shrink-0">
          <div className="flex flex-wrap items-center gap-2">
            {['All', 'Examination', 'Academic', 'Registration', 'Financial'].map(cat => (
              <button
                key={cat}
                onClick={() => setSelectedCategory(cat)}
                className={`px-2.5 py-1 rounded-md text-xs font-semibold transition ${
                  selectedCategory === cat
                    ? 'bg-slate-900 text-white'
                    : 'bg-white text-slate-700 hover:bg-slate-200 border border-slate-300'
                }`}
              >
                {cat}
              </button>
            ))}
          </div>

          <div className="flex items-center gap-2">
            {currentUser.role === 'admin' && (
              <button
                onClick={() => setShowAddForm(!showAddForm)}
                className="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold rounded-lg transition flex items-center gap-1.5 shadow-sm"
              >
                <Plus className="w-3.5 h-3.5" />
                {showAddForm ? 'Cancel' : 'Upload Event'}
              </button>
            )}

            <button
              onClick={downloadIcsFile}
              className="px-3 py-1.5 bg-white hover:bg-slate-50 text-slate-800 border border-slate-300 text-xs font-semibold rounded-lg transition flex items-center gap-1.5 shadow-sm"
              title="Download iCal .ics for Google Calendar, Apple Calendar, Outlook"
            >
              <Download className="w-3.5 h-3.5 text-emerald-600" />
              Sync to Phone (.ics)
            </button>
          </div>
        </div>

        {/* Modal Body */}
        <div className="flex-1 overflow-y-auto p-4 sm:p-6 space-y-4">
          
          {/* Admin Event Creation Form */}
          {showAddForm && (
            <form onSubmit={handleCreateEvent} className="p-4 bg-slate-50 border border-slate-300 rounded-xl space-y-3 text-xs animate-in fade-in">
              <h3 className="font-bold text-slate-900 text-sm flex items-center gap-2">
                <CalendarCheck className="w-4 h-4 text-emerald-600" />
                Publish New College Event / Exam Timetable
              </h3>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div className="sm:col-span-2">
                  <label className="block font-semibold text-slate-700 mb-1">EVENT TITLE *</label>
                  <input
                    type="text"
                    required
                    placeholder="e.g. City & Guilds Practical Exam Series"
                    value={newEvent.title}
                    onChange={e => setNewEvent({ ...newEvent, title: e.target.value })}
                    className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block font-semibold text-slate-700 mb-1">START DATE *</label>
                  <input
                    type="date"
                    required
                    value={newEvent.date}
                    onChange={e => setNewEvent({ ...newEvent, date: e.target.value })}
                    className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block font-semibold text-slate-700 mb-1">TIME / DURATION</label>
                  <input
                    type="text"
                    placeholder="e.g. 08:30 AM - 04:30 PM"
                    value={newEvent.time}
                    onChange={e => setNewEvent({ ...newEvent, time: e.target.value })}
                    className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block font-semibold text-slate-700 mb-1">CATEGORY</label>
                  <select
                    value={newEvent.category}
                    onChange={e => setNewEvent({ ...newEvent, category: e.target.value as any })}
                    className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg"
                  >
                    <option value="Academic">Academic</option>
                    <option value="Examination">Examination</option>
                    <option value="Registration">Registration</option>
                    <option value="Financial">Financial</option>
                    <option value="Sports & Social">Sports & Social</option>
                  </select>
                </div>

                <div>
                  <label className="block font-semibold text-slate-700 mb-1">TARGET AUDIENCE</label>
                  <select
                    value={newEvent.targetAudience}
                    onChange={e => setNewEvent({ ...newEvent, targetAudience: e.target.value as any })}
                    className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg"
                  >
                    <option value="All">All College Members</option>
                    <option value="Students">Students Only</option>
                    <option value="Parents">Parents / Guardians</option>
                    <option value="Teachers">Lecturers & Staff</option>
                  </select>
                </div>

                <div className="sm:col-span-2">
                  <label className="block font-semibold text-slate-700 mb-1">LOCATION / VENUE</label>
                  <input
                    type="text"
                    value={newEvent.location}
                    onChange={e => setNewEvent({ ...newEvent, location: e.target.value })}
                    className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                  />
                </div>

                <div className="sm:col-span-2">
                  <label className="block font-semibold text-slate-700 mb-1">DESCRIPTION</label>
                  <textarea
                    rows={2}
                    placeholder="Provide details about the event, required materials, or candidate instructions..."
                    value={newEvent.description}
                    onChange={e => setNewEvent({ ...newEvent, description: e.target.value })}
                    className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                  />
                </div>
              </div>

              <div className="flex justify-end gap-2 pt-2">
                <button
                  type="button"
                  onClick={() => setShowAddForm(false)}
                  className="px-3 py-1.5 text-slate-600 hover:bg-slate-200 rounded-lg font-semibold"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg shadow-sm"
                >
                  Publish to Calendar & Broadcast
                </button>
              </div>
            </form>
          )}

          {/* Sync Link Card */}
          <div className="p-3 bg-emerald-50 border border-emerald-300 rounded-xl flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 text-xs text-emerald-950">
            <div className="flex items-center gap-2.5">
              <CalendarCheck className="w-5 h-5 text-emerald-700 shrink-0" />
              <div>
                <strong className="text-emerald-900 block">Live Calendar Subscription</strong>
                <span className="text-[11px] text-slate-600">
                  Sync all examination dates, CAT schedules, and fee balance deadlines automatically to Google Calendar or Apple iCal.
                </span>
              </div>
            </div>

            <button
              onClick={handleCopySyncUrl}
              className="px-3 py-1.5 bg-emerald-700 hover:bg-emerald-800 text-white font-semibold rounded-lg shrink-0 transition flex items-center gap-1.5 text-xs"
            >
              {copiedSyncLink ? (
                <>
                  <CheckCircle2 className="w-3.5 h-3.5 text-emerald-300" />
                  Link Copied!
                </>
              ) : (
                <>
                  <Share2 className="w-3.5 h-3.5" />
                  Copy Sync Feed URL
                </>
              )}
            </button>
          </div>

          {/* Events List */}
          <div className="space-y-3">
            {filteredEvents.map(evt => (
              <div
                key={evt.id}
                className="border border-slate-200 rounded-xl p-4 bg-white hover:border-slate-300 transition shadow-xs space-y-2 text-xs"
              >
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                  <div className="flex items-center gap-2">
                    <span className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${
                      evt.category === 'Examination'
                        ? 'bg-rose-100 text-rose-900 border border-rose-300'
                        : evt.category === 'Financial'
                        ? 'bg-amber-100 text-amber-900 border border-amber-300'
                        : evt.category === 'Registration'
                        ? 'bg-blue-100 text-blue-900 border border-blue-300'
                        : 'bg-emerald-100 text-emerald-900 border border-emerald-300'
                    }`}>
                      {evt.category}
                    </span>
                    <h4 className="font-bold text-sm text-slate-900">{evt.title}</h4>
                  </div>

                  <span className="text-slate-600 font-mono text-xs flex items-center gap-1">
                    <Clock className="w-3.5 h-3.5 text-slate-400" />
                    {evt.date} {evt.endDate ? `to ${evt.endDate}` : ''}
                  </span>
                </div>

                <p className="text-slate-600 leading-relaxed">{evt.description}</p>

                <div className="flex flex-wrap items-center justify-between gap-2 pt-2 border-t border-slate-100 text-[11px] text-slate-500">
                  <div className="flex items-center gap-4">
                    <span className="flex items-center gap-1">
                      <Clock className="w-3 h-3 text-slate-400" />
                      {evt.time}
                    </span>
                    <span className="flex items-center gap-1">
                      <MapPin className="w-3 h-3 text-slate-400" />
                      {evt.location}
                    </span>
                  </div>

                  <span className="bg-slate-100 px-2 py-0.5 rounded text-slate-700 font-medium">
                    Audience: {evt.targetAudience}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};
