import React, { useState, useEffect, useMemo } from 'react';
import { motion } from 'framer-motion';
import { 
  Calendar, 
  CheckCircle2, 
  Circle, 
  Clock, 
  AlertCircle, 
  ShieldCheck,
  ChevronRight,
  Loader2
} from 'lucide-react';
import { cn } from '../../lib/utils';
import { API_BASE_URL } from '../../lib/config';
import { getCurrentAcademicYear } from '../../lib/dateUtils';

interface Event {
  id: number;
  title: string;
  status: string;
  academicYears: string[];
  startDate: string;
}

export const PrincipalMasterChecklist: React.FC = () => {
  const [events, setEvents] = useState<Event[]>([]);
  const [instEvents, setInstEvents] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const currentAcademicYear = getCurrentAcademicYear();

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

  const fetchData = async () => {
    try {
      const [eventsRes, instEventsRes] = await Promise.all([
        fetch(API_BASE_URL + '/api/events'),
        fetch(API_BASE_URL + '/api/institutional-events')
      ]);

      if (eventsRes.ok && instEventsRes.ok) {
        const eventsData = await eventsRes.json();
        const instEventsData = await instEventsRes.json();
        setEvents(eventsData);
        setInstEvents(instEventsData);
      }
    } catch (err) {
      console.error('Failed to fetch data:', err);
    } finally {
      setLoading(false);
    }
  };

  const getEventStatus = (eventName: string) => {
    const currentYear = new Date().getFullYear();
    const matchingEvents = events.filter(e => {
      const matchesName = e.title.toLowerCase().includes(eventName.toLowerCase());
      const eventDate = new Date(e.startDate);
      // Check if event is within the current academic cycle (roughly current year +/- 1)
      const matchesCycle = eventDate.getFullYear() === currentYear || 
                          (eventDate.getFullYear() === currentYear - 1 && eventDate.getMonth() >= 5) ||
                          (eventDate.getFullYear() === currentYear + 1 && eventDate.getMonth() < 5);
      return matchesName && matchesCycle;
    });

    if (matchingEvents.some(e => e.status?.toUpperCase() === 'COMPLETED')) return 'COMPLETED';
    if (matchingEvents.some(e => e.status?.toUpperCase() === 'APPROVED')) return 'APPROVED';
    if (matchingEvents.some(e => e.status?.toUpperCase() === 'PENDING_PR' || e.status?.toUpperCase() === 'REQUESTED')) return 'PENDING';
    return 'NOT_SCHEDULED';
  };

  const oddSemesterEvents = useMemo(() => instEvents.filter(e => e.semester === 'ODD'), [instEvents]);
  const evenSemesterEvents = useMemo(() => instEvents.filter(e => e.semester === 'EVEN'), [instEvents]);

  const SemesterCard = ({ title, events }: { title: string, events: any[] }) => (
    <div className="flex-1 bg-white rounded-[2.5rem] border border-slate-100 premium-shadow overflow-hidden flex flex-col">
      <div className="p-8 border-b border-slate-50 bg-slate-50/30">
        <h3 className="text-xl font-black text-brand-navy tracking-tight">{title}</h3>
        <p className="text-[10px] font-black uppercase tracking-widest text-slate-400 mt-1">Institutional Milestones</p>
      </div>
      
      <div className="p-8 space-y-4 flex-1 overflow-y-auto max-h-[500px] custom-scrollbar">
        {events.map((event, i) => {
          const status = getEventStatus(event.name);
          return (
            <motion.div 
              key={event.id}
              initial={{ opacity: 0, x: -10 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: i * 0.05 }}
              className="flex items-center justify-between group p-4 hover:bg-slate-50 rounded-2xl transition-all"
            >
              <div className="flex items-center gap-4">
                <div className={cn(
                  "w-10 h-10 rounded-xl flex items-center justify-center transition-all",
                  status === 'COMPLETED' ? "bg-emerald-500 text-white" :
                  status === 'APPROVED' ? "bg-brand-indigo text-white" :
                  status === 'PENDING' ? "bg-amber-500 text-white" : "bg-slate-100 text-slate-300"
                )}>
                  {status === 'COMPLETED' ? <CheckCircle2 className="w-5 h-5" /> :
                   status === 'APPROVED' ? <Calendar className="w-5 h-5" /> :
                   status === 'PENDING' ? <Clock className="w-5 h-5" /> : <Circle className="w-5 h-5" />}
                </div>
                <div>
                  <p className="text-sm font-black text-brand-navy group-hover:text-brand-indigo transition-colors">{event.name}</p>
                  <p className="text-[9px] font-bold text-slate-400 uppercase tracking-widest mt-0.5">TARGET: {event.month}</p>
                </div>
              </div>
              
              <div className={cn(
                "px-3 py-1 rounded-lg text-[8px] font-black uppercase tracking-widest border transition-all",
                status === 'COMPLETED' ? "bg-emerald-50 text-emerald-600 border-emerald-100" :
                status === 'APPROVED' ? "bg-brand-glow text-brand-indigo border-brand-indigo/10" :
                status === 'PENDING' ? "bg-amber-50 text-amber-600 border-amber-100" : "bg-slate-50 text-slate-400 border-slate-100"
              )}>
                {status.replace('_', ' ')}
              </div>
            </motion.div>
          );
        })}
      </div>
    </div>
  );

  if (loading) {
    return (
      <div className="flex items-center justify-center p-20">
        <Loader2 className="w-8 h-8 text-brand-indigo animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-8">
      <div className="bg-brand-navy p-10 rounded-[3rem] text-white flex flex-col md:flex-row md:items-center justify-between gap-8 relative overflow-hidden">
        <div className="relative z-10">
          <h2 className="text-3xl font-black tracking-tight mb-2">Institutional Master Checklist</h2>
          <p className="text-sm font-medium text-white/60 flex items-center gap-2">
            <ShieldCheck className="w-4 h-4 text-emerald-400" />
            Strategic event tracking for Academic Year {currentAcademicYear}
          </p>
        </div>
        <div className="relative z-10 flex items-center gap-4">
           <div className="px-5 py-3 bg-white/10 rounded-2xl border border-white/10">
              <span className="text-[10px] font-black uppercase tracking-[0.2em]">Principal Desk Control</span>
           </div>
        </div>
        <div className="absolute top-0 right-0 w-64 h-64 bg-brand-indigo/20 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2" />
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
        <SemesterCard title="ODD Semester Milestones" events={oddSemesterEvents} />
        <SemesterCard title="EVEN Semester Milestones" events={evenSemesterEvents} />
      </div>
    </div>
  );
};
