import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Calendar, CheckCircle2, Circle } from 'lucide-react';
import { cn } from '../../lib/utils';
import { INSTITUTIONAL_EVENTS } from '../../constants/institutionalEvents';
import { getCurrentAcademicYear } from '../../lib/dateUtils';
import { API_BASE_URL } from '../../lib/config';

interface ClubEvent {
  id: string;
  name: string;
  month: string;
  semester: 'ODD' | 'EVEN';
}

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

interface ClubInstitutionalChecklistProps {
  onEventClick: (data: { eventName: string, isClubEvent: boolean }) => void;
}

export const ClubInstitutionalChecklist: React.FC<ClubInstitutionalChecklistProps> = ({ onEventClick }) => {
  const [events, setEvents] = useState<Event[]>([]);
  const currentAcademicYear = getCurrentAcademicYear();

  useEffect(() => {
    fetch(API_BASE_URL + '/api/events')
      .then(res => res.json())
      .then(data => setEvents(data))
      .catch(err => console.error('Failed to fetch events:', err));
  }, []);

  const getEventStatus = (eventName: string) => {
    const matching = events.filter(e => 
      e.title.toLowerCase() === eventName.toLowerCase() && 
      e.academicYears?.includes(currentAcademicYear) &&
      (e.status?.toUpperCase() === 'APPROVED' || e.status?.toUpperCase() === 'COMPLETED')
    );
    return matching.length > 0;
  };

  const oddSemesterEvents = INSTITUTIONAL_EVENTS.filter(e => e.semester === 'ODD');
  const evenSemesterEvents = INSTITUTIONAL_EVENTS.filter(e => e.semester === 'EVEN');

  const SemesterCard = ({ title, subtitle, events, gradient }: { title: string, subtitle: string, events: ClubEvent[], gradient: string }) => (
    <div className="flex-1 min-w-[400px] bg-white rounded-[2.5rem] border border-slate-100 premium-shadow overflow-hidden">
      <div className={cn("p-8 text-white flex justify-between items-start", gradient)}>
        <div>
          <h3 className="text-2xl font-black tracking-tight">{title}</h3>
          <p className="text-[10px] font-black uppercase tracking-widest opacity-80 mt-1">{subtitle}</p>
        </div>
        <Calendar className="w-6 h-6 opacity-60" />
      </div>
      
      <div className="p-8 space-y-6 max-h-[600px] overflow-y-auto custom-scrollbar">
        {events.map((event, i) => {
          const isScheduled = getEventStatus(event.name);
          return (
            <motion.button 
              key={event.id}
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: i * 0.05 }}
              onClick={() => onEventClick({ eventName: event.name, isClubEvent: true })}
              className="w-full flex items-center gap-6 group text-left"
            >
              <div className="relative">
                <Circle className={cn("w-8 h-8 fill-white", isScheduled ? "text-emerald-500" : "text-slate-100")} />
                <div className="absolute inset-0 flex items-center justify-center">
                  {isScheduled ? (
                    <CheckCircle2 className="w-5 h-5 text-emerald-500" />
                  ) : (
                    <div className="w-4 h-4 rounded-full border-2 border-slate-200 group-hover:border-brand-indigo transition-colors" />
                  )}
                </div>
              </div>
              <div>
                <p className={cn("text-sm font-black transition-colors", isScheduled ? "text-emerald-600" : "text-text-dark group-hover:text-brand-indigo")}>{event.name}</p>
                <p className="text-[9px] font-bold text-text-muted uppercase tracking-widest mt-0.5">
                  {isScheduled ? 'Scheduled & Approved' : `Target: ${event.month}`}
                </p>
              </div>
            </motion.button>
          );
        })}
      </div>
    </div>
  );

  return (
    <div className="space-y-10">
      <div className="flex items-center gap-4">
        <div className="w-1.5 h-10 bg-brand-indigo rounded-full" />
        <div>
          <h2 className="text-3xl font-black text-text-dark tracking-tighter">Institutional Checklists</h2>
          <p className="text-[10px] font-black uppercase tracking-widest text-text-muted mt-1">Track Institutional Club Requirements</p>
        </div>
      </div>

      <div className="flex flex-col xl:flex-row gap-8">
        <SemesterCard 
          title="ODD Semester" 
          subtitle="Club & Institutional Events" 
          events={oddSemesterEvents}
          gradient="bg-gradient-to-r from-blue-600 to-indigo-600"
        />
        <SemesterCard 
          title="Even Semester" 
          subtitle="Club & Institutional Events" 
          events={evenSemesterEvents}
          gradient="bg-gradient-to-r from-indigo-600 to-purple-600"
        />
      </div>
    </div>
  );
};
