import { API_BASE_URL } from '../../lib/config';
import React, { useState, useEffect } from 'react';
import { Calendar as CalendarIcon, MapPin, Clock, ChevronLeft, ChevronRight, Loader2 } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '../../lib/utils';
import { format } from 'date-fns';
import { startOfMonth } from 'date-fns';
import { endOfMonth } from 'date-fns';
import { startOfWeek } from 'date-fns';
import { endOfWeek } from 'date-fns';
import { eachDayOfInterval } from 'date-fns';
import { isSameMonth } from 'date-fns';
import { isSameDay } from 'date-fns';
import { addMonths } from 'date-fns';
import { subMonths } from 'date-fns';

interface Event {
  id: number;
  title: string;
  type: string;
  status: string;
  department: string;
  startDate: string;
  endDate: string;
  location: string;
  academicYears: string[];
}

export const VenueTimeline: React.FC<{ compact?: boolean }> = ({ compact }) => {
  const [selectedDate, setSelectedDate] = useState(new Date());
  const [currentMonth, setCurrentMonth] = useState(new Date());
  const [events, setEvents] = useState<Event[]>([]);
  const [loading, setLoading] = useState(true);
  const [coreVenues, setCoreVenues] = useState<string[]>([
    'GB 4th floor auditorium',
    'Wozniak Auditorium',
    'C6-02 Indoor Theatre',
    'H Block Guest Lecture Theatre',
    'Steve Jobs Computer Centre 1',
    'Steve Jobs Computer Centre 2'
  ]);

  useEffect(() => {
    const fetchVenues = async () => {
      try {
        const response = await fetch(API_BASE_URL + '/api/venues');
        if (response.ok) {
          const data = await response.json();
          setCoreVenues(data.map((v: any) => v.name));
        }
      } catch (error) {
        console.error('Failed to fetch venues for timeline:', error);
      }
    };

    const fetchEvents = async () => {
      try {
        const response = await fetch(API_BASE_URL + '/api/events');
        if (response.ok) {
          const data = await response.json();
          setEvents(data.filter((e: any) => 
            e.status === 'APPROVED' || e.status === 'COMPLETED'
          ));
        }
      } catch (error) {
        console.error('Failed to fetch events for timeline:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchVenues();
    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 eventsOnSelectedDate = events.filter(event => {
    const eventDate = parseDate(event.startDate);
    if (!eventDate) return false;
    return format(eventDate, 'yyyy-MM-dd') === format(selectedDate, 'yyyy-MM-dd');
  });

  // Dynamically discover all unique venues from events on the selected date and combine with CORE_VENUES
  const allVenues = (() => {
    const dynamicVenues = eventsOnSelectedDate
      .map(e => e.location?.trim())
      .filter(l => l && l !== 'N/A' && l !== 'Others.') as string[];
      
    const finalVenues = [...coreVenues];
    dynamicVenues.forEach(dv => {
      if (!finalVenues.some(cv => cv.toLowerCase() === dv.toLowerCase())) {
        finalVenues.push(dv);
      }
    });
    return finalVenues;
  })();

  const calendarDays = (() => {
    const start = startOfWeek(startOfMonth(currentMonth));
    const end = endOfWeek(endOfMonth(currentMonth));
    return eachDayOfInterval({ start, end });
  })();

  if (loading) {
    return (
      <div className="flex items-center justify-center p-20">
        <Loader2 className="w-8 h-8 text-brand-indigo animate-spin" />
        <span className="ml-3 text-sm font-black text-brand-indigo uppercase tracking-widest tracking-widest">Initialising Timeline Audit...</span>
      </div>
    );
  }

  return (
    <div className={cn(
      "flex gap-8 items-start",
      compact ? "flex-col" : "flex-col lg:flex-row min-h-[600px]"
    )}>
      {/* Sidebar Filter - STICKY */}
      {!compact && (
        <div className="w-full lg:w-80 space-y-6 sticky top-24 self-start">
        <div className="bg-white p-8 rounded-[2.5rem] border border-slate-100 premium-shadow">
          <div className="flex items-center gap-4 mb-8">
            <div className="w-10 h-10 bg-brand-indigo rounded-2xl flex items-center justify-center text-white premium-shadow-sm">
              <CalendarIcon className="w-5 h-5" />
            </div>
            <div>
              <p className="text-[10px] font-black uppercase tracking-widest text-text-muted">Timeline Filter</p>
              <h3 className="text-lg font-black text-text-dark tracking-tight">View Date</h3>
            </div>
          </div>

          <div className="space-y-4">
            <div className="flex items-center justify-between px-2">
              <h4 className="text-sm font-black text-text-dark">{format(currentMonth, 'MMMM yyyy')}</h4>
              <div className="flex gap-2">
                <button onClick={() => setCurrentMonth(subMonths(currentMonth, 1))} className="p-1 hover:bg-slate-50 rounded-lg transition-colors">
                  <ChevronLeft className="w-4 h-4 text-text-muted" />
                </button>
                <button onClick={() => setCurrentMonth(addMonths(currentMonth, 1))} className="p-1 hover:bg-slate-50 rounded-lg transition-colors">
                  <ChevronRight className="w-4 h-4 text-text-muted" />
                </button>
              </div>
            </div>

            <div className="grid grid-cols-7 gap-1">
              {['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((day, i) => (
                <div key={`${day}-${i}`} className="text-[10px] font-black text-text-muted text-center py-2">{day}</div>
              ))}
              {calendarDays.map(day => {
                const hasEvents = events.some(e => 
                  e.startDate && format(new Date(e.startDate), 'yyyy-MM-dd') === format(day, 'yyyy-MM-dd')
                );
                const isSelected = isSameDay(day, selectedDate);

                return (
                  <button
                    key={day.toISOString()}
                    onClick={() => setSelectedDate(day)}
                    className={cn(
                      "aspect-square flex items-center justify-center text-xs font-bold rounded-xl transition-all relative group",
                      !isSameMonth(day, currentMonth) && "text-slate-200",
                      isSelected ? "bg-brand-indigo text-white premium-shadow-sm" : "hover:bg-slate-50 text-text-dark",
                      isSameDay(day, new Date()) && !isSelected && "text-brand-indigo underline decoration-2 underline-offset-4"
                    )}
                  >
                    {format(day, 'd')}
                    {hasEvents && (
                      <div className={cn(
                        "absolute bottom-1 w-1 h-1 rounded-full",
                        isSelected ? "bg-white/40" : "bg-brand-indigo/30"
                      )} />
                    )}
                  </button>
                );
              })}
            </div>
          </div>

          <div className="mt-8 p-4 bg-brand-glow/30 rounded-2xl border border-brand-indigo/10">
            <p className="text-[9px] font-bold text-brand-indigo/80 leading-relaxed italic">
              Tip: This calendar specifically filters the venue bookings timeline below.
            </p>
          </div>
        </div>
      </div>
    )}

      <div className="flex-1 space-y-6">
        {!compact && (
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-3xl font-black text-text-dark tracking-tighter">Institutional Timeline</h2>
              <p className="text-sm font-bold text-text-muted mt-1">
                Confirmed slots for <span className="text-brand-indigo">{format(selectedDate, 'MMMM d, yyyy')}</span>
              </p>
            </div>
            <div className="flex items-center gap-2 px-4 py-2 bg-emerald-50 text-emerald-600 rounded-full border border-emerald-100">
              <div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse" />
              <span className="text-[10px] font-black uppercase tracking-widest">Approved Only</span>
            </div>
          </div>
        )}

        <div className="space-y-6">
          {allVenues.map((venue, idx) => {
            const venueEvents = eventsOnSelectedDate.filter(e => 
              e.location?.trim().toLowerCase() === venue.trim().toLowerCase()
            );
            
            return (
              <motion.div
                key={venue}
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: idx * 0.05 }}
                className={cn(
                  "bg-white rounded-[2.5rem] border border-slate-100 premium-shadow overflow-hidden",
                  compact && "rounded-[1.5rem] premium-shadow-sm"
                )}
              >
                <div className={cn(
                  "p-8 border-b border-slate-50 bg-slate-50/30 flex items-center gap-4",
                  compact && "p-4"
                )}>
                  <div className={cn(
                    "w-12 h-12 bg-white rounded-2xl flex items-center justify-center premium-shadow-sm border border-slate-50",
                    compact && "w-8 h-8 rounded-xl"
                  )}>
                    <MapPin className={cn("text-slate-300", compact ? "w-4 h-4" : "w-6 h-6")} />
                  </div>
                  <h3 className={cn("font-black text-text-dark tracking-tight", compact ? "text-sm" : "text-xl")}>{venue}</h3>
                </div>

                <div className={cn("p-8", compact && "p-4")}>
                  {venueEvents.length > 0 ? (
                    <div className="space-y-4">
                      {venueEvents.map(event => (
                        <div key={event.id} className={cn(
                          "flex flex-col md:flex-row md:items-center justify-between gap-6 bg-slate-50/50 border border-slate-100 rounded-3xl hover:bg-white hover:premium-shadow transition-all group",
                          compact ? "p-4" : "p-6"
                        )}>
                          <div className="flex items-center gap-4">
                            <div className={cn(
                              "bg-white rounded-2xl flex items-center justify-center text-[10px] font-black text-brand-indigo border border-brand-indigo/10",
                              compact ? "w-8 h-8 rounded-xl text-[8px]" : "w-12 h-12"
                            )}>
                              {event.department === 'AI&DS' ? 'AIDS' : event.department?.slice(0, 4).toUpperCase()}
                            </div>
                            <div>
                              <h4 className={cn("font-black text-text-dark group-hover:text-brand-indigo transition-colors", compact ? "text-xs" : "text-lg")}>{event.title}</h4>
                              {!compact && (
                                <div className="flex items-center gap-3 mt-1">
                                  <span className="text-[10px] font-black uppercase tracking-widest text-text-muted">{event.department}</span>
                                  <span className="text-[10px] font-black uppercase tracking-widest text-slate-300">•</span>
                                  <span className="text-[10px] font-black uppercase tracking-widest text-brand-indigo/60">{event.type}</span>
                                </div>
                              )}
                            </div>
                          </div>
                          
                          <div className={cn(
                            "flex items-center gap-4 bg-white rounded-2xl border border-slate-100 premium-shadow-sm",
                            compact ? "px-3 py-2" : "px-6 py-4"
                          )}>
                            <Clock className={cn("text-brand-indigo", compact ? "w-3 h-3" : "w-4 h-4")} />
                            <div className="flex flex-col">
                              <p className="text-[8px] font-black uppercase tracking-widest text-text-muted mb-0.5">Slot</p>
                              <p className={cn("font-black text-text-dark", compact ? "text-[10px]" : "text-sm")}>
                                {parseDate(event.startDate) ? format(parseDate(event.startDate)!, 'hh:mm a') : 'TBD'}
                              </p>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className={cn(
                      "flex flex-col items-center justify-center border-2 border-dashed border-slate-50 rounded-3xl",
                      compact ? "py-4" : "py-12"
                    )}>
                      <p className="text-[10px] font-black uppercase tracking-[0.3em] text-slate-200">
                        {compact ? 'Available' : 'Available for Booking'}
                      </p>
                    </div>
                  )}
                </div>
              </motion.div>
            );
          })}
        </div>
      </div>
    </div>
  );
};
