'use client'
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { eventAPI, Event } from '../../lib/api';

const EventsSection = () => {
  const router = useRouter();
  const [upcomingEvents, setUpcomingEvents] = useState<Event[]>([]);
  const [pastEvents, setPastEvents] = useState<Event[]>([]);
  const [loading, setLoading] = useState(true);

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

  const loadEvents = async () => {
    try {
      setLoading(true);
      const [upcoming, past] = await Promise.all([
        eventAPI.getUpcomingEvents(),
        eventAPI.getPastEvents()
      ]);
      setUpcomingEvents(upcoming);
      setPastEvents(past);
    } catch (error) {
      console.error('Error loading events:', error);
    } finally {
      setLoading(false);
    }
  };

  // Navigation function for App Router
  const navigateToEventDetail = (eventId: string | number) => {
    router.push(`/event-detail/${eventId}`);
  };

  const navigateToAllEvents = () => {
    router.push('/events');
  };

  // Format price display from fees
  const formatPrice = (event: Event) => {
    if (event.fee && event.fee.length > 0) {
      return `₹${event.fee[0].cost} per ticket`;
    }
    return '₹1,800 per ticket';
  };

  // Top section events (first 4 events for the grid)
  const topEvents = upcomingEvents.slice(0, 4);
  
  // Featured event (first event)
  const featuredEvent = upcomingEvents.length > 0 ? upcomingEvents[0] : null;

  if (loading) {
    return (
      <div className="py-12 px-6 sm:px-8 md:px-6 lg:px-6 xl:px-6 bg-white max-w-7xl mx-auto">
        <div className="text-center" style={{ color: '#012068' }}>Loading events...</div>
      </div>
    );
  }

  return (
    <div className="py-12 px-6 sm:px-8 md:px-6 lg:px-6 xl:px-6 bg-white max-w-7xl mx-auto">
      {/* Section Header */}
      <div className="flex justify-between items-center mb-8">
        <h2 className="text-2xl md:text-3xl font-bold" style={{ color: '#012068' }}>
          Our Events
        </h2>
        <button 
          className="text-sm font-medium hover:opacity-70 transition-opacity duration-200"
          style={{ color: '#e64838' }}
          onClick={navigateToAllEvents}
        >
          View All
        </button>
      </div>

      {/* Events Grid - Top Section with Event Details */}
      {topEvents.length === 0 ? (
        <div className="text-center py-8 mb-12">
          <p className="text-gray-500">No upcoming events.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-12">
          {topEvents.map((event, index) => (
            <div 
              key={event.id} 
              className={`relative rounded-lg h-48 overflow-hidden cursor-pointer hover:shadow-lg transition-shadow ${
                index === 2 ? 'lg:hidden xl:block' : ''
              } ${index === 3 ? 'md:col-span-2 lg:col-span-1' : ''}`}
              onClick={() => navigateToEventDetail(event.id)}
            >
              <img 
                src={event.mainImage}
                alt={event.title}
                className="w-full h-full object-cover"
              />
              {/* Gradient overlay for better text readability */}
              <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent"></div>
              
              {/* Event details overlay */}
              <div className="absolute bottom-0 left-0 right-0 p-4 text-white">
                <div className="text-xs font-medium mb-1" style={{ color: '#e64838' }}>
                  {event.date}
                </div>
                <h4 className="font-medium mb-2 text-sm leading-tight">
                  {event.title}
                </h4>
                <div className="text-xs font-medium">
                  {formatPrice(event)}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Featured Events Section */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Left - Large Featured Event */}
        <div className="lg:col-span-2 px-4 py-4 rounded-lg" style={{ backgroundColor: '#f4f4f4' }}>
          <h3 className="text-xl font-semibold mb-4" style={{ color: '#012068' }}>Upcoming Events</h3>
          {!featuredEvent ? (
            <div className="text-center py-8">
              <p className="text-gray-500">No upcoming events.</p>
            </div>
          ) : (
            <div 
              className="bg-white border border-gray-100 rounded-lg overflow-hidden cursor-pointer hover:shadow-lg transition-shadow"
              onClick={() => navigateToEventDetail(featuredEvent.id)}
            >
              <div className="relative h-48 md:h-64">
                <img 
                  src={featuredEvent.mainImage} 
                  alt={featuredEvent.title}
                  className="w-full h-full object-cover"
                />
                {/* Pagination dots */}
                <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex space-x-2">
                  <div className="w-2 h-2 bg-white rounded-full shadow"></div>
                  <div className="w-2 h-2 bg-gray-400 rounded-full"></div>
                  <div className="w-2 h-2 bg-gray-400 rounded-full"></div>
                </div>
              </div>
              <div className="p-4 md:p-6">
                <div className="flex flex-col lg:flex-row lg:justify-between gap-4">
                  <div className="flex-1">
                    <div className="text-xs font-medium mb-3" style={{ color: '#e64838' }}>
                      {featuredEvent.date}
                    </div>
                    <h4 className="text-lg md:text-xl font-medium mb-2" style={{ color: '#012068' }}>
                      {featuredEvent.title}
                    </h4>
                    <div className="text-xs leading-relaxed mb-1" style={{ color: '#333' }}>
                      {featuredEvent.description}
                    </div>
                    <div className="text-xs leading-relaxed mb-4" style={{ color: '#333' }}>
                      {featuredEvent.detail}
                    </div>
                    <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">
                      <div 
                        className="text-xs cursor-pointer hover:underline"
                        style={{ color: '#012068' }}
                      >
                        Share Event
                      </div>
                      <div className="text-xs" style={{ color: '#012068' }}>
                        📍 {featuredEvent.venue?.[0]?.address || 'Convention Center, Medical District'}
                      </div>
                    </div>
                  </div>
                  <div className="text-left lg:text-right">
                    <button 
                      className="w-full lg:w-auto px-6 py-2 text-sm rounded-lg mb-2 transition-colors hover:opacity-90"
                      style={{ 
                        backgroundColor: '#e64838',
                        color: 'white'
                      }}
                      onClick={(e) => {
                        e.stopPropagation();
                        console.log('Book seat clicked');
                      }}
                    >
                      Book Your Seat
                    </button>
                    <div className="text-sm font-medium" style={{ color: '#e64838' }}>
                      {formatPrice(featuredEvent)}
                    </div>
                    <div className="text-xs mt-1" style={{ color: '#012068', opacity: 0.8 }}>
                      Early bird discount available
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Right - Event List with Scroller */}
        <div className="lg:col-span-1">
          <h3 className="text-xl font-semibold mb-4" style={{ color: '#012068' }}>Past Events</h3>
          {pastEvents.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-gray-500">No past events.</p>
            </div>
          ) : (
            <div className="h-96 overflow-y-auto pr-2 space-y-4 scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100">
              {pastEvents.map((event) => (
                <div 
                  key={event.id} 
                  className="bg-white border border-gray-100 rounded-lg overflow-hidden cursor-pointer hover:shadow-lg transition-shadow flex-shrink-0"
                  onClick={() => navigateToEventDetail(event.id)}
                >
                  <div className="h-24">
                    <img 
                      src={event.mainImage}
                      alt={event.title}
                      className="w-full h-full object-cover"
                    />
                  </div>
                  <div className="p-4">
                    <div className="text-xs font-medium mb-1" style={{ color: '#e64838' }}>
                      {event.date}
                    </div>
                    <h4 className="font-medium mb-1 text-sm" style={{ color: '#012068' }}>
                      {event.title}
                    </h4>
                    <p className="text-xs leading-relaxed" style={{ color: '#333' }}>
                      {event.description}
                    </p>
                    <div className="mt-2 flex justify-between items-center">
                      <button 
                        className="text-xs hover:underline"
                        style={{ color: '#012068' }}
                        onClick={(e) => {
                          e.stopPropagation();
                          navigateToEventDetail(event.id);
                        }}
                      >
                        View Details
                      </button>
                      {/* <span className="text-xs font-medium" style={{ color: '#e64838' }}>
                        {formatPrice(event)}
                      </span> */}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default EventsSection;