import React, { useState, useMemo, useEffect } from 'react';
import { motion } from 'framer-motion';
import { MapPin, Clock, Calendar as CalendarIcon, ArrowRight, Building2 } from 'lucide-react';
import { cn } from '../../lib/utils';
import { format, isSameDay } from 'date-fns';
import { EventDetailsModal } from './EventDetailsModal';
import { API_BASE_URL } from '../../lib/config';

interface VenuesAtGlanceProps {
  events: any[];
}

export const VenuesAtGlance: React.FC<VenuesAtGlanceProps> = ({ events }) => {
  const [selectedEvent, setSelectedEvent] = useState<any | null>(null);
  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 glance:', error);
      }
    };
    fetchVenues();
  }, []);

  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 today = new Date();

  // Combine core venues with any dynamically used venues in events today
  const allVenues = useMemo(() => {
    const todayEvents = events.filter(e => {
      if (e.status !== 'APPROVED' && e.status !== 'COMPLETED') return false;
      const eventDate = parseDate(e.startDate);
      if (!eventDate) return false;
      return isSameDay(eventDate, today);
    });

    const dynamicVenues = todayEvents
      .filter(e => e.location && e.location !== 'N/A' && e.location !== 'Others.')
      .map(e => e.location.trim());
    
    const finalVenues = [...coreVenues];
    dynamicVenues.forEach(dv => {
      if (!finalVenues.some(cv => cv.toLowerCase() === dv.toLowerCase())) {
        finalVenues.push(dv);
      }
    });
    return finalVenues;
  }, [events, coreVenues]);

  return (
    <div className="card-widget">
      <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">
            <MapPin className="w-5 h-5 text-brand-indigo" />
            Venues At A Glance
          </h3>
          <p className="text-[10px] font-black uppercase tracking-widest text-slate-400 mt-1">
            Today's Scheduled Events • {format(today, 'MMMM d, yyyy')}
          </p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
        {allVenues.map((venue, idx) => {
          // Find if there is an approved/completed event for this venue today
          const todayEvents = events.filter(e => {
            if (e.status !== 'APPROVED' && e.status !== 'COMPLETED') return false;
            const eventDate = parseDate(e.startDate);
            if (!eventDate) return false;
            return isSameDay(eventDate, today) && e.location?.trim().toLowerCase() === venue.trim().toLowerCase();
          });

          const isOccupied = todayEvents.length > 0;

          return (
            <motion.div
              key={venue}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: idx * 0.05 }}
              className={cn(
                "rounded-[1.5rem] p-5 border transition-all relative overflow-hidden",
                isOccupied 
                  ? "bg-slate-50 border-slate-200 hover:border-brand-indigo/30 premium-shadow-sm group cursor-pointer" 
                  : "bg-white border-slate-100 hover:bg-slate-50 opacity-70 hover:opacity-100"
              )}
              onClick={() => isOccupied && setSelectedEvent(todayEvents[0])}
            >
              {isOccupied && (
                <div className="absolute top-0 right-0 w-16 h-16 bg-brand-indigo/5 rounded-bl-[100%] transition-transform group-hover:scale-110" />
              )}
              
              <div className="flex items-start justify-between gap-4 mb-4 relative z-10">
                <div className="flex items-center gap-3">
                  <div className={cn(
                    "w-10 h-10 rounded-xl flex items-center justify-center shrink-0 transition-colors",
                    isOccupied ? "bg-white text-brand-indigo shadow-sm" : "bg-slate-50 text-slate-400"
                  )}>
                    <Building2 className="w-5 h-5" />
                  </div>
                  <div>
                    <h4 className="text-sm font-black text-brand-navy tracking-tight line-clamp-1" title={venue}>
                      {venue}
                    </h4>
                    <span className={cn(
                      "text-[9px] font-black uppercase tracking-widest",
                      isOccupied ? "text-emerald-500" : "text-slate-400"
                    )}>
                      {isOccupied ? 'Occupied' : 'Available'}
                    </span>
                  </div>
                </div>
              </div>

              {isOccupied ? (
                <div className="space-y-3 relative z-10">
                  <div className="bg-white rounded-xl p-3 border border-slate-100 shadow-sm transition-transform group-hover:-translate-y-1">
                    <p className="text-xs font-bold text-brand-navy line-clamp-1 mb-2">
                      {todayEvents[0].title}
                    </p>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-1.5 text-text-muted">
                        <Clock className="w-3.5 h-3.5 text-brand-indigo" />
                        <span className="text-[10px] font-black uppercase tracking-widest">
                          {format(parseDate(todayEvents[0].startDate)!, 'hh:mm a')}
                        </span>
                      </div>
                      <div className="w-6 h-6 rounded-lg bg-brand-glow flex items-center justify-center text-brand-indigo group-hover:bg-brand-indigo group-hover:text-white transition-colors">
                        <ArrowRight className="w-3 h-3" />
                      </div>
                    </div>
                  </div>
                  {todayEvents.length > 1 && (
                    <p className="text-[9px] font-bold text-brand-indigo/60 text-right">
                      + {todayEvents.length - 1} more today
                    </p>
                  )}
                </div>
              ) : (
                <div className="h-16 flex items-center justify-center border border-dashed border-slate-200 rounded-xl">
                  <p className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-300">
                    No Events
                  </p>
                </div>
              )}
            </motion.div>
          );
        })}
      </div>

      <EventDetailsModal 
        isOpen={!!selectedEvent} 
        onClose={() => setSelectedEvent(null)} 
        event={selectedEvent} 
      />
    </div>
  );
};
