import React, { useState, useEffect } from 'react';
import type { Event } from '../../types';
import EventCard from './EventCard';
import CategoryGrid from './CategoryGrid';
import DomainSelection from './DomainSelection';
import EventsHeroSlider from './EventsHeroSlider';

interface EventListProps {
  events: Event[];
  selectedCategory: string | null;
  bookedEventIds: string[];
  onToggleBooking: (id: string) => void;
  onSelectCategory: (id: string | null) => void;
  onTrackStatus?: (event: Event) => void;
  currentUserName: string;
  userRole?: string;
  userRegistrations?: any[];
}
const EventList: React.FC<EventListProps> = ({ 
  events,
  selectedCategory, 
  bookedEventIds, 
  onToggleBooking, 
  onSelectCategory,
  onTrackStatus,
  currentUserName,
  userRole,
  userRegistrations = []
}) => {
  const [selectedDomain, setSelectedDomain] = useState<string | null>(null);
  const [selectedDomainName, setSelectedDomainName] = useState<string | null>(null);

  useEffect(() => {
    setSelectedDomain('ALL');
    if (selectedCategory === 'TECHNICAL') setSelectedDomainName('Technical Events');
    else if (selectedCategory === 'NON-TECHNICAL') setSelectedDomainName('Non-Technical Events');
    else if (selectedCategory === 'WORKSHOP') setSelectedDomainName('Workshops');
    else if (selectedCategory === 'CENTRE-ACTIVITY') setSelectedDomainName('Centre Activities');
    else setSelectedDomainName('All Events');
  }, [selectedCategory]);

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [selectedDomain]);

  if (!selectedCategory) {
    const hasActiveEvents = events.some(e => e.status !== 'Completed');
    return (
      <div className={!hasActiveEvents ? 'pt-32' : ''}>
        <EventsHeroSlider events={events} />
        <CategoryGrid onSelectCategory={onSelectCategory} />
      </div>
    );
  }

  if (!selectedDomain) {
    return (
      <DomainSelection 
        category={selectedCategory} 
        onSelectDomain={(id, name) => {
           setSelectedDomain(id);
           if (name) setSelectedDomainName(name);
        }}
        onBack={() => onSelectCategory(null)}
      />
    );
  }

  let filteredEvents = events;
  if (selectedCategory !== 'ALL') {
    filteredEvents = filteredEvents.filter(e => e.category === selectedCategory);
  }
  if (selectedDomain !== 'ALL') {
    filteredEvents = filteredEvents.filter(e => e.domain === selectedDomain);
  }

  const categoryName = selectedCategory === 'ALL' ? 'All' : 
                      selectedCategory.charAt(0) + selectedCategory.slice(1).toLowerCase();
  const domainName = selectedDomainName || (selectedDomain === 'ALL' ? 'All Domains' : selectedDomain);

  return (
    <div className="pt-40 pb-16 px-6 md:px-12 lg:px-24 animate-in fade-in duration-500">
      <button 
        onClick={() => onSelectCategory(null)}
        className="flex items-center gap-2 text-[#f97316] font-black uppercase tracking-widest mb-10 group hover:translate-x-[-5px] transition-transform"
      >
        <i className="fas fa-arrow-left"></i>
        BACK TO CATEGORIES
      </button>

      <div className="flex flex-col md:flex-row md:items-end justify-between mb-12 gap-6">
        <div>
          <h1 className="text-4xl md:text-5xl font-black text-[#1A202C] tracking-tight mb-2">
            {domainName}
          </h1>
          <p className="text-[#f97316] font-bold text-sm tracking-[0.2em] uppercase">
            Exploring {categoryName} Category
          </p>
        </div>
        <p className="text-gray-400 font-medium">Showing {filteredEvents.length} events found</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10">
        {filteredEvents.map(event => {
          const reg = userRegistrations.find(r => String(r.event_id) === String(event.id));
          return (
            <EventCard 
              key={event.id}
              event={event}
              isBooked={bookedEventIds.includes(event.id)}
              onToggle={() => onToggleBooking(event.id)}
              onTrackStatus={onTrackStatus}
              currentUserName={currentUserName}
              userRole={userRole}
              registration={reg}
            />
          );
        })}
      </div>

      {filteredEvents.length === 0 && (
        <div className="py-24 text-center bg-white rounded-[40px] shadow-xl shadow-gray-900/10 border border-gray-200">
          <div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6">
            <i className="fas fa-calendar-times text-gray-300 text-3xl"></i>
          </div>
          <p className="text-gray-400 text-xl font-medium">No events found in this domain yet.</p>
          <button onClick={() => setSelectedDomain(null)} className="mt-6 px-6 py-2 bg-[#1A202C] text-white rounded-full text-xs font-bold uppercase tracking-widest hover:bg-black transition-colors">Try another domain</button>
        </div>
      )}
    </div>
  );
};

export default EventList;
