import { API_BASE_URL } from '../../lib/config';
import React, { useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Calendar, 
  MapPin, 
  Clock, 
  Filter,
  Search,
  Trash2,
  FileSpreadsheet,
  FileText,
  Users,
  Ticket,
  Wallet,
  Heart,
  XCircle,
  AlertTriangle,
  Split,
  Layers,
  CheckCircle
} from 'lucide-react';
import { cn } from '../../lib/utils';
import { useAuth } from '../../context/AuthContext';
import { StatusTimeline, type Event } from './EventStatusTimeline';
import { Pagination } from './Pagination';

interface ExtendedEvent extends Event {
  description?: string;
  sponsors?: string[];
  academicYears?: string[];
  dayConfigs?: any[];
  deptLimits?: Record<string, any>;
  deptSectionLimits?: Record<string, any>;
  budget?: number;
  hasRegistrationFee?: boolean;
  registrationFee?: number;
  conflictMessage?: string;
}

interface AllEventsProps {
  onEditEvent?: (event: any) => void;
}

export const AllEvents: React.FC<AllEventsProps> = ({ onEditEvent }) => {
  const { user } = useAuth();
  const [events, setEvents] = useState<ExtendedEvent[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedEvent, setSelectedEvent] = useState<ExtendedEvent | null>(null);

  useEffect(() => {
    fetchEvents();
  }, []);

  const parseDate = (dateSource: any): Date | null => {
    if (!dateSource) return null;
    if (typeof dateSource === 'string') return new Date(dateSource);
    if (Array.isArray(dateSource)) {
      return new Date(dateSource[0], dateSource[1] - 1, dateSource[2], dateSource[3] || 0, dateSource[4] || 0);
    }
    return null;
  };

  const fetchEvents = async () => {
    try {
      const response = await fetch(API_BASE_URL + '/api/events');
      if (response.ok) {
        const data = await response.json();
        setEvents(data);
      }
    } catch (error) {
      console.error('Failed to fetch events:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const deleteEvent = async (eventId: number) => {
    if (!window.confirm('Are you sure you want to permanently delete this event? This action cannot be undone.')) return;
    try {
      const res = await fetch(`${API_BASE_URL}/api/events/${eventId}`, { method: 'DELETE' });
      if (res.ok) {
        setEvents(prev => prev.filter(e => e.id !== eventId));
      } else {
        alert('Failed to delete event. Please try again.');
      }
    } catch (err) {
      console.error('Delete failed:', err);
      alert('An error occurred while deleting the event.');
    }
  };

  const getStatusColor = (status: Event['status']) => {
    switch (status) {
      case 'REQUESTED': return 'bg-brand-glow text-brand-indigo border-brand-indigo/20';
      case 'PENDING_PR': return 'bg-amber-50 text-amber-600 border-amber-100';
      case 'APPROVED': return 'bg-emerald-50 text-emerald-600 border-emerald-100';
      case 'COMPLETED': return 'bg-slate-100 text-slate-600 border-slate-200';
      case 'CANCELLED': return 'bg-red-50 text-red-600 border-red-100';
      default: return 'bg-slate-50 text-slate-500 border-slate-100';
    }
  };

  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

  const filteredEvents = events
    .filter(event => 
      event.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      event.department.toLowerCase().includes(searchTerm.toLowerCase())
    )
    .sort((a, b) => {
      const dateA = new Date(a.updatedAt || a.createdAt || 0).getTime();
      const dateB = new Date(b.updatedAt || b.createdAt || 0).getTime();
      return dateB - dateA;
    });

  const totalPages = Math.ceil(filteredEvents.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const currentEvents = filteredEvents.slice(startIndex, startIndex + itemsPerPage);

  useEffect(() => {
    setCurrentPage(1);
  }, [searchTerm]);

  return (
    <div className="space-y-8">
      {/* Header & Controls */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h2 className="text-3xl font-black text-text-dark tracking-tight">All Events</h2>
          <p className="text-text-muted font-medium">Overview of all institutional activities and their status.</p>
        </div>
        
        <div className="flex items-center gap-3">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" />
            <input 
              type="text" 
              placeholder="Filter events..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="bg-white border border-slate-200 rounded-xl py-2 pl-10 pr-4 text-sm focus:outline-none focus:ring-2 focus:ring-brand-indigo/10 focus:border-brand-indigo transition-all premium-shadow-sm"
            />
          </div>
          {(user?.role === 'ADMIN' || user?.role === 'PRINCIPAL') && (
            <button 
              onClick={() => window.dispatchEvent(new CustomEvent('navigate', { detail: 'import-excel' }))}
              className="flex items-center gap-2 px-4 py-2 bg-brand-glow text-brand-indigo rounded-xl hover:bg-brand-indigo hover:text-white transition-all premium-shadow-sm border border-brand-indigo/10 text-sm font-black uppercase tracking-widest"
            >
              <FileSpreadsheet className="w-4 h-4" />
              Import
            </button>
          )}
          <button className="p-2 bg-white border border-slate-200 rounded-xl hover:bg-slate-50 transition-all premium-shadow-sm">
            <Filter className="w-5 h-5 text-text-secondary" />
          </button>
        </div>
      </div>

      {/* Events List */}
      <div className="bg-white rounded-[2.5rem] border border-slate-100 premium-shadow overflow-hidden flex flex-col">
        {isLoading ? (
          <div className="p-20 text-center text-text-muted italic">Loading events...</div>
        ) : filteredEvents.length === 0 ? (
          <div className="p-20 text-center">
            <div className="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-4">
              <Calendar className="w-8 h-8 text-slate-300" />
            </div>
            <p className="text-text-muted font-medium italic">No events found matching your search.</p>
          </div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="border-b border-slate-50">
                    <th className="px-8 py-6 text-[10px] font-black uppercase tracking-[0.2em] text-text-muted">Event Details</th>
                    <th className="px-8 py-6 text-[10px] font-black uppercase tracking-[0.2em] text-text-muted">Date & Venue</th>
                    <th className="px-8 py-6 text-[10px] font-black uppercase tracking-[0.2em] text-text-muted">Department</th>
                    <th className="px-8 py-6 text-[10px] font-black uppercase tracking-[0.2em] text-text-muted">Status</th>
                    <th className="px-8 py-6 text-[10px] font-black uppercase tracking-[0.2em] text-text-muted text-right">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-50">
                  {currentEvents.map((event, idx) => (
                    <motion.tr 
                      key={event.id}
                      initial={{ opacity: 0, y: 10 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: idx * 0.05 }}
                      className="group hover:bg-slate-50/50 transition-colors"
                    >
                      <td className="px-8 py-6">
                        <div className="flex flex-col">
                          <span className="font-bold text-text-dark text-sm group-hover:text-brand-indigo transition-colors">{event.title}</span>
                          <span className="text-[10px] font-black uppercase tracking-widest text-text-muted mt-1">{event.type} • {event.institution}</span>
                        </div>
                      </td>
                      <td className="px-8 py-6">
                        <div className="space-y-1.5">
                          <div className="flex items-center gap-2 text-xs font-semibold text-text-secondary">
                            <Clock className="w-3.5 h-3.5 text-brand-indigo opacity-60" />
                            {parseDate(event.startDate) ? parseDate(event.startDate)!.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' }) : 'N/A'}
                          </div>
                          <div className="flex items-center gap-2 text-[10px] font-bold text-text-muted uppercase tracking-wider">
                            <MapPin className="w-3.5 h-3.5 text-brand-indigo opacity-60" />
                            {event.location}
                          </div>
                        </div>
                      </td>
                      <td className="px-8 py-6">
                        <div className="flex items-center gap-2">
                          <div className="w-7 h-7 rounded-lg bg-brand-glow flex items-center justify-center text-[10px] font-black text-brand-indigo">
                            {event.department.substring(0, 2)}
                          </div>
                          <span className="text-xs font-bold text-text-secondary">{event.department}</span>
                        </div>
                      </td>
                      <td className="px-8 py-6">
                        {user?.role === 'FACULTY' && event.proposer?.email === user?.email ? (
                          <StatusTimeline event={event} compact />
                        ) : (
                          <span className={cn(
                            "inline-flex items-center px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-widest border",
                            getStatusColor(event.status)
                          )}>
                            {event.status === 'PENDING_PR' ? 'PENDING PRINCIPAL' : event.status}
                          </span>
                        )}
                      </td>
                      <td className="px-8 py-6 text-right">
                        <div className="flex items-center justify-end gap-2">
                          <button
                            onClick={() => setSelectedEvent(event)}
                            className="px-4 py-2 bg-slate-50 text-brand-indigo hover:bg-brand-indigo hover:text-white rounded-xl text-[9px] font-black uppercase tracking-widest transition-all border border-brand-indigo/10"
                          >
                            View
                          </button>
                          {(user?.role === 'ADMIN' || (event.status === 'REQUESTED' && event.proposer?.email === user?.email)) && onEditEvent && (
                            <button 
                              onClick={() => onEditEvent(event)}
                              className="px-4 py-2 bg-slate-50 text-brand-indigo hover:bg-brand-indigo hover:text-white rounded-xl text-[9px] font-black uppercase tracking-widest transition-all border border-brand-indigo/10"
                            >
                              Edit
                            </button>
                          )}
                          {user?.role === 'ADMIN' && (
                            <button
                              onClick={() => deleteEvent(event.id)}
                              className="p-2 rounded-lg hover:bg-red-50 transition-all text-slate-300 hover:text-red-500"
                              title="Delete Event"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          )}
                        </div>
                      </td>
                    </motion.tr>
                  ))}
                </tbody>
              </table>
            </div>

            <Pagination 
              currentPage={currentPage}
              totalItems={filteredEvents.length}
              itemsPerPage={itemsPerPage}
              onPageChange={setCurrentPage}
              onItemsPerPageChange={(val) => {
                setItemsPerPage(val);
                setCurrentPage(1);
              }}
              itemsPerPageOptions={[5, 10, 20, 50]}
            />
          </>
        )}
      </div>

      {/* Details Modal */}
      <AnimatePresence>
        {selectedEvent && (
          <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setSelectedEvent(null)}
              className="absolute inset-0 bg-slate-900/40 backdrop-blur-sm"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.9, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.9, y: 20 }}
              className="relative w-full max-w-2xl bg-white rounded-[2.5rem] premium-shadow overflow-hidden max-h-[90vh] overflow-y-auto"
            >
              <div className={cn(
                "p-8 text-white flex justify-between items-start",
                selectedEvent.status === 'CANCELLED' ? "bg-red-600" : "bg-brand-navy"
              )}>
                <div>
                  <div className="flex items-center gap-2 mb-2">
                    <span className="text-[10px] font-black uppercase tracking-[0.2em] text-white/60">Event Details</span>
                    <span className="w-1 h-1 bg-white/30 rounded-full" />
                    <span className="text-[10px] font-black uppercase tracking-[0.2em] text-white/60">{selectedEvent.institution}</span>
                    {selectedEvent.category === 'CLUB' && (
                      <>
                        <span className="w-1 h-1 bg-white/30 rounded-full" />
                        <span className="text-[10px] font-black uppercase tracking-[0.2em] text-emerald-400">Institutional Club Event</span>
                      </>
                    )}
                  </div>
                  <h3 className="text-2xl font-black tracking-tight">{selectedEvent.title}</h3>
                </div>
                <button 
                  onClick={() => setSelectedEvent(null)}
                  className="p-2 hover:bg-white/10 rounded-xl transition-all"
                >
                  <XCircle className="w-6 h-6" />
                </button>
              </div>

              <div className="p-8 space-y-8">
                {/* Description Section */}
                {selectedEvent.description && (
                  <div className="space-y-2">
                    <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-text-muted">
                      <FileText className="w-3.5 h-3.5" />
                      Event Description
                    </div>
                    <p className="text-sm font-medium text-text-dark leading-relaxed bg-slate-50 p-4 rounded-2xl border border-slate-100">
                      {selectedEvent.description}
                    </p>
                  </div>
                )}

                <div className="grid grid-cols-2 gap-8">
                  <div className="space-y-6">
                    <div className="space-y-1">
                      <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-text-muted">
                        <Calendar className="w-3.5 h-3.5" />
                        Schedule
                      </div>
                      <p className="text-sm font-bold text-text-dark">
                        {parseDate(selectedEvent.startDate) ? parseDate(selectedEvent.startDate)!.toLocaleString('en-IN') : 'N/A'}
                      </p>
                    </div>
                    <div className="space-y-1">
                      <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-text-muted">
                        <MapPin className="w-3.5 h-3.5" />
                        Venue
                      </div>
                      <p className="text-sm font-bold text-text-dark">{selectedEvent.location}</p>
                    </div>
                  </div>

                  <div className="space-y-6">
                    <div className="space-y-1">
                      <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-text-muted">
                        <Users className="w-3.5 h-3.5" />
                        Proposed By
                      </div>
                      <p className="text-sm font-bold text-text-dark">{selectedEvent.proposer?.fullName || 'Faculty'}</p>
                      <p className="text-[10px] font-black text-brand-indigo uppercase">{selectedEvent.department}</p>
                    </div>
                    {selectedEvent.academicYears && selectedEvent.academicYears.length > 0 && (
                      <div className="space-y-1">
                        <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-text-muted">
                          <Users className="w-3.5 h-3.5" />
                          Target Audience
                        </div>
                        <p className="text-sm font-bold text-text-dark">{selectedEvent.academicYears.join(', ')} Batches</p>
                      </div>
                    )}
                  </div>
                </div>

                {/* Sponsors Section */}
                {selectedEvent.sponsors && selectedEvent.sponsors.length > 0 && (
                  <div className="space-y-3">
                    <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-text-muted">
                      <Heart className="w-3.5 h-3.5 text-brand-indigo" />
                      Event Sponsors
                    </div>
                    <div className="flex flex-wrap gap-2">
                      {selectedEvent.sponsors.map((sponsor, idx) => (
                        <span key={idx} className="px-3 py-1 bg-brand-glow text-brand-indigo rounded-lg text-[10px] font-black uppercase tracking-widest border border-brand-indigo/10">
                          {sponsor}
                        </span>
                      ))}
                    </div>
                  </div>
                )}

                {/* Itinerary & Day Configs */}
                {selectedEvent.dayConfigs && selectedEvent.dayConfigs.length > 0 && (
                  <div className="space-y-3">
                    <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-text-muted">
                      <Calendar className="w-3.5 h-3.5 text-brand-indigo" />
                      Detailed Itinerary & Schedule
                    </div>
                    <div className="space-y-4">
                      {selectedEvent.dayConfigs.map((day: any, dIdx: number) => {
                        const dayDate = day.date ? new Date(day.date) : null;
                        return (
                          <div key={dIdx} className="p-4 rounded-2xl bg-slate-50 border border-slate-100 space-y-3">
                            <div className="flex justify-between items-center border-b border-slate-200 pb-1.5">
                              <span className="text-[11px] font-black text-brand-navy uppercase tracking-wider">
                                Day {dIdx + 1}: {dayDate && !isNaN(dayDate.getTime()) ? dayDate.toLocaleDateString() : day.date || 'TBD'}
                              </span>
                              <span className="px-2 py-0.5 bg-brand-glow text-brand-indigo text-[8px] font-black uppercase tracking-widest rounded">
                                {day.batches?.length || 0} {(day.batches?.length || 0) === 1 ? 'Batch' : 'Batches'}
                              </span>
                            </div>
                            <div className="space-y-3 divide-y divide-slate-200/50">
                              {day.batches?.map((batch: any, bIdx: number) => (
                                <div key={bIdx} className="pt-3 first:pt-0 space-y-2">
                                  <div className="flex justify-between items-center">
                                    <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest">
                                      Batch {batch.id || bIdx + 1}
                                    </span>
                                    <span className="text-[10px] font-bold text-brand-indigo bg-white px-2 py-0.5 rounded-lg border border-slate-200 shadow-sm flex items-center gap-1">
                                      <Clock className="w-3.5 h-3.5" />
                                      {batch.startTime || 'TBD'} - {batch.endTime || 'TBD'}
                                    </span>
                                  </div>
                                  {batch.resourcePerson && batch.resourcePerson.name && (
                                    <div className="p-3 bg-white rounded-xl border border-slate-100 space-y-1.5">
                                      <div className="flex justify-between items-start">
                                        <div>
                                          <p className="text-[8px] font-black text-slate-400 uppercase tracking-widest">Resource Person</p>
                                          <p className="text-xs font-bold text-text-dark">{batch.resourcePerson.name}</p>
                                        </div>
                                        <span className={cn(
                                          "px-2 py-0.5 rounded text-[8px] font-black uppercase tracking-wider",
                                          batch.resourcePerson.type === 'EXTERNAL' ? "bg-amber-50 text-amber-600 border border-amber-100" : "bg-brand-glow text-brand-indigo border border-brand-indigo/10"
                                        )}>
                                          {batch.resourcePerson.type || 'INTERNAL'}
                                        </span>
                                      </div>
                                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-1.5 text-[9px] text-text-muted font-semibold">
                                        {batch.resourcePerson.dept && (
                                          <div>
                                            <span className="font-bold text-slate-400 uppercase tracking-wider">Dept:</span> {batch.resourcePerson.dept}
                                          </div>
                                        )}
                                        {batch.resourcePerson.college_name && (
                                          <div className="col-span-2">
                                            <span className="font-bold text-slate-400 uppercase tracking-wider">Inst:</span> {batch.resourcePerson.college_name}
                                          </div>
                                        )}
                                        {batch.resourcePerson.phone && (
                                          <div>
                                            <span className="font-bold text-slate-400 tracking-wider uppercase">Phone:</span> {batch.resourcePerson.phone}
                                          </div>
                                        )}
                                        {batch.resourcePerson.email && (
                                          <div>
                                            <span className="font-bold text-slate-400 tracking-wider uppercase">Email:</span> {batch.resourcePerson.email}
                                          </div>
                                        )}
                                      </div>
                                    </div>
                                  )}
                                </div>
                              ))}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                {/* Department limits and quotas */}
                {selectedEvent.deptLimits && Object.keys(selectedEvent.deptLimits).length > 0 && (
                  <div className="space-y-3">
                    <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-text-muted">
                      <Users className="w-3.5 h-3.5 text-brand-indigo" />
                      Department Limits & Quotas
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      {Object.entries(selectedEvent.deptLimits).map(([dept, maxSeats]) => {
                        const sectionLimits = selectedEvent.deptSectionLimits?.[dept];
                        const hasSectionLimits = sectionLimits && Object.keys(sectionLimits).length > 0;
                        return (
                          <div key={dept} className="bg-slate-50 border border-slate-100 rounded-2xl p-4 space-y-3">
                            <div className="flex justify-between items-center">
                              <span className="text-xs font-black text-brand-navy uppercase tracking-wider">{dept}</span>
                              <span className="px-2 py-0.5 bg-brand-indigo text-white text-[9px] font-black uppercase rounded-md">
                                Quota: {maxSeats} Seats
                              </span>
                            </div>
                            {hasSectionLimits && (
                              <div className="pt-2 border-t border-slate-200/60 grid grid-cols-3 gap-2">
                                {Object.entries(sectionLimits).map(([sec, limit]) => (
                                  <div key={sec} className="bg-white px-2 py-1 rounded-xl border border-slate-100 text-center">
                                    <span className="block text-[8px] font-black text-slate-400 uppercase mb-0.5">Sec {sec}</span>
                                    <span className="text-[10px] font-black text-brand-navy">{String(limit)}</span>
                                  </div>
                                ))}
                              </div>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                <div className="grid grid-cols-2 gap-8 pt-4 border-t border-slate-50">
                  <div className="p-4 bg-slate-50 rounded-2xl">
                    <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-text-muted mb-1">
                      <Wallet className="w-3.5 h-3.5 text-brand-indigo" />
                      Estimated Budget
                    </div>
                    <p className="text-lg font-black text-text-dark">₹{selectedEvent.budget?.toLocaleString() || '0'}</p>
                  </div>
                  <div className="p-4 bg-slate-50 rounded-2xl">
                    <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-text-muted mb-1">
                      <Ticket className="w-3.5 h-3.5 text-brand-indigo" />
                      Registration
                    </div>
                    <p className="text-lg font-black text-text-dark">
                      {selectedEvent.hasRegistrationFee ? `₹${selectedEvent.registrationFee}` : 'FREE'}
                    </p>
                  </div>
                </div>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
};

