import React, { useState, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Clock, 
  CheckCircle2, 
  AlertCircle, 
  Edit3, 
  Calendar,
  MapPin,
  ChevronRight,
  ShieldCheck,
  XCircle,
  Timer,
  ChevronLeft,
  ChevronDown,
  Users
} from 'lucide-react';
import { cn } from '../../lib/utils';
import { format } from 'date-fns';

interface Event {
  id: number;
  title: string;
  startDate: any;
  endDate: any;
  location: string;
  status: 'REQUESTED' | 'APPROVED' | 'COMPLETED' | 'CANCELLED' | 'PENDING_PR' | 'HOD_REJECTED' | 'PRINCIPAL_REJECTED';
  rejectionReason?: string;
  category?: string;
  currentParticipants?: number;
}

interface FacultyEventManagementProps {
  events: Event[];
  onEditEvent: (event: Event) => void;
}

export const FacultyEventManagement: React.FC<FacultyEventManagementProps> = ({ events, onEditEvent }) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(3);

  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 sortedEvents = useMemo(() => {
    return [...events].sort((a, b) => {
      const dateA = parseDate(a.startDate)?.getTime() || 0;
      const dateB = parseDate(b.startDate)?.getTime() || 0;
      return dateB - dateA;
    });
  }, [events]);

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

  const rangeStart = events.length === 0 ? 0 : (currentPage - 1) * itemsPerPage + 1;
  const rangeEnd = Math.min(currentPage * itemsPerPage, events.length);

  const getStatusConfig = (status: string) => {
    switch (status) {
      case 'APPROVED':
        return { color: 'text-emerald-500', bg: 'bg-emerald-50', border: 'border-emerald-100', icon: CheckCircle2, label: 'Approved' };
      case 'PENDING_PR':
        return { color: 'text-brand-indigo', bg: 'bg-brand-glow', border: 'border-brand-indigo/10', icon: ShieldCheck, label: 'At Principal Desk' };
      case 'REQUESTED':
        return { color: 'text-amber-500', bg: 'bg-amber-50', border: 'border-amber-100', icon: Timer, label: 'At HoD Desk' };
      case 'HOD_REJECTED':
      case 'PRINCIPAL_REJECTED':
        return { color: 'text-red-500', bg: 'bg-red-50', border: 'border-red-100', icon: XCircle, label: 'Rejected' };
      case 'CANCELLED':
        return { color: 'text-slate-400', bg: 'bg-slate-50', border: 'border-slate-200', icon: XCircle, label: 'Cancelled' };
      default:
        return { color: 'text-slate-500', bg: 'bg-slate-50', border: 'border-slate-100', icon: Clock, label: status };
    }
  };

  return (
    <div className="card-widget h-full flex flex-col">
      <div className="flex items-center justify-between mb-8">
        <div>
          <h3 className="text-xl font-black text-brand-navy tracking-tight flex items-center gap-2">
            <Calendar className="w-5 h-5 text-brand-indigo" />
            My Event Proposals
          </h3>
          <p className="text-[10px] font-black uppercase tracking-widest text-slate-400 mt-1">
            Track and manage your submitted requests
          </p>
        </div>
        <div className="flex items-center gap-3">
          <div className="bg-slate-50 px-3 py-1.5 rounded-xl border border-slate-100">
            <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">
              {events.length} Total
            </span>
          </div>
        </div>
      </div>

      <div className="flex-1 space-y-4 overflow-hidden">
        <AnimatePresence mode="wait">
          {events.length === 0 ? (
            <motion.div 
              key="empty"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              className="flex flex-col items-center justify-center py-12 text-center"
            >
              <div className="w-16 h-16 bg-slate-50 rounded-2xl flex items-center justify-center mb-4">
                <Calendar className="w-8 h-8 text-slate-200" />
              </div>
              <p className="text-sm font-bold text-slate-400 italic">No event proposals yet.</p>
            </motion.div>
          ) : (
            <motion.div 
              key={currentPage + '-' + itemsPerPage}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -10 }}
              className="space-y-4"
            >
              {currentEvents.map((event, idx) => {
                const config = getStatusConfig(event.status);
                const eventDate = parseDate(event.startDate);
                const canEdit = ['REQUESTED', 'PENDING_PR'].includes(event.status);

                return (
                  <div
                    key={event.id}
                    className="group relative bg-white border border-slate-100 rounded-2xl p-4 hover:border-brand-indigo/30 hover:shadow-md transition-all"
                  >
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                          <div className={cn("px-2 py-0.5 rounded-md text-[8px] font-black uppercase tracking-widest border", config.bg, config.color, config.border)}>
                            {config.label}
                          </div>
                          <span className="text-[9px] font-black text-slate-300 uppercase tracking-widest">•</span>
                          <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest">ID: #{event.id}</span>
                        </div>
                        <h4 className="text-sm font-black text-brand-navy truncate group-hover:text-brand-indigo transition-colors mb-2">
                          {event.title}
                        </h4>
                        <div className="flex flex-wrap gap-x-4 gap-y-2">
                          <div className="flex items-center gap-1.5 text-slate-500">
                            <Clock className="w-3.5 h-3.5 text-brand-indigo/60" />
                            <span className="text-[10px] font-bold">
                              {eventDate ? format(eventDate, 'MMM d, h:mm a') : 'TBD'}
                            </span>
                          </div>
                          <div className="flex items-center gap-1.5 text-slate-500">
                            <MapPin className="w-3.5 h-3.5 text-brand-indigo/60" />
                            <span className="text-[10px] font-bold truncate max-w-[120px]">
                              {event.location}
                            </span>
                          </div>
                          <div className="flex items-center gap-1.5 text-slate-500">
                            <Users className="w-3.5 h-3.5 text-brand-indigo/60" />
                            <span className="text-[10px] font-bold">
                              {event.currentParticipants || 0} Registered
                            </span>
                          </div>
                        </div>
                      </div>

                      <div className="flex flex-col gap-2">
                        {canEdit ? (
                          <button
                            onClick={() => onEditEvent(event)}
                            className="p-2.5 bg-brand-glow text-brand-indigo rounded-xl hover:bg-brand-indigo hover:text-white transition-all shadow-sm group/btn"
                            title="Edit Proposal"
                          >
                            <Edit3 className="w-4 h-4 transition-transform group-hover/btn:scale-110" />
                          </button>
                        ) : (
                          <div className="p-2.5 bg-slate-50 text-slate-300 rounded-xl cursor-not-allowed" title="Cannot edit once in review">
                            <Edit3 className="w-4 h-4" />
                          </div>
                        )}
                        <button className="p-2.5 bg-white border border-slate-100 text-slate-400 rounded-xl hover:bg-slate-50 hover:text-brand-indigo transition-all shadow-sm">
                          <ChevronRight className="w-4 h-4" />
                        </button>
                      </div>
                    </div>

                    {event.rejectionReason && (
                      <div className="mt-3 p-3 bg-red-50/50 border border-red-100 rounded-xl flex items-start gap-2">
                        <AlertCircle className="w-3.5 h-3.5 text-red-500 shrink-0 mt-0.5" />
                        <p className="text-[10px] font-medium text-red-700 italic">
                          "{event.rejectionReason}"
                        </p>
                      </div>
                    )}
                  </div>
                );
              })}
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      <div className="mt-6 flex items-center justify-end gap-8 pt-4 border-t border-slate-50">
        <div className="flex items-center gap-3">
          <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Rows per page</span>
          <div className="relative group">
            <select
              value={itemsPerPage}
              onChange={(e) => {
                setItemsPerPage(Number(e.target.value));
                setCurrentPage(1);
              }}
              className="bg-slate-50 border border-slate-100 rounded-xl px-4 py-2 text-[11px] font-black text-brand-navy appearance-none pr-10 cursor-pointer hover:border-brand-indigo/30 transition-all focus:outline-none"
            >
              {[3, 5, 10, 20].map(val => (
                <option key={val} value={val}>{val}</option>
              ))}
            </select>
            <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-3 h-3 text-slate-400 pointer-events-none" />
          </div>
        </div>

        <div className="text-[11px] font-black text-brand-navy tracking-tight min-w-[80px] text-center">
          {rangeStart}-{rangeEnd} <span className="text-slate-300 mx-1">of</span> {events.length}
        </div>

        <div className="flex items-center gap-1">
          <button 
            onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
            disabled={currentPage === 1}
            className="p-2 text-slate-400 hover:text-brand-indigo disabled:opacity-20 disabled:cursor-not-allowed transition-all hover:bg-slate-50 rounded-lg"
          >
            <ChevronLeft className="w-5 h-5" />
          </button>
          <button 
            onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
            disabled={currentPage === totalPages || events.length === 0}
            className="p-2 text-slate-400 hover:text-brand-indigo disabled:opacity-20 disabled:cursor-not-allowed transition-all hover:bg-slate-50 rounded-lg"
          >
            <ChevronRight className="w-5 h-5" />
          </button>
        </div>
      </div>
    </div>
  );
};
