import { API_BASE_URL } from '../../lib/config';
import React, { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { 
  Calendar, 
  MapPin, 
  Clock, 
  Filter,
  Search,
  Trash2,
  FileSpreadsheet
} from 'lucide-react';
import { cn } from '../../lib/utils';
import { useAuth } from '../../context/AuthContext';
import { StatusTimeline, type Event } from './EventStatusTimeline';
import { Pagination } from './Pagination';

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

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

  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">
                          {(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>
    </div>
  );
};
