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

// Combined type for events and courses
type EventOrCourse = (Event & { type: 'event' }) | (Course & { type: 'course', date: string, mainImage: string });

const EventsSection = () => {
  const router = useRouter();
  const [upcomingEvents, setUpcomingEvents] = useState<Event[]>([]);
  const [pastEvents, setPastEvents] = useState<Event[]>([]);
  const [courses, setCourses] = useState<Course[]>([]);
  const [loading, setLoading] = useState(true);
  const [combinedUpcoming, setCombinedUpcoming] = useState<EventOrCourse[]>([]);

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

  const loadData = async () => {
    try {
      setLoading(true);
      const [upcoming, past, activeCourses] = await Promise.all([
        eventAPI.getUpcomingEvents(),
        eventAPI.getPastEvents(),
        educationService.getActiveCourses()
      ]);
      
      setUpcomingEvents(upcoming);
      setPastEvents(past);
      setCourses(activeCourses);

      // Combine events and courses for display
      const eventsWithType: EventOrCourse[] = upcoming.map(event => ({ 
        ...event, 
        type: 'event' as const 
      }));

      const coursesWithType: EventOrCourse[] = activeCourses.map(course => ({
        ...course,
        type: 'course' as const,
        date: course.startDate || 'Date TBD',
        mainImage: course.image
      }));

      // Combine and sort by date
      const combined = [...eventsWithType, ...coursesWithType].sort((a, b) => {
        const dateA = new Date(a.date);
        const dateB = new Date(b.date);
        return dateA.getTime() - dateB.getTime();
      });

      setCombinedUpcoming(combined);
    } catch (error) {
      console.error('Error loading data:', error);
    } finally {
      setLoading(false);
    }
  };

  // Get safe image URL - no fallback
  const getSafeImageUrl = (item: EventOrCourse): string => {
    if (!item.mainImage || item.mainImage.trim() === '') {
      return '';
    }
    return item.mainImage;
  };

  // Navigation functions
  const navigateToDetail = (item: EventOrCourse) => {
    if (item.type === 'event') {
      router.push(`/event-detail/${item.id}`);
    } else {
      router.push(`/education-training/course-detail?id=${item.id}`);
    }
  };

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

  // Format price display
  const formatPrice = (item: EventOrCourse) => {
    if (item.type === 'event') {
      if (item.fee && item.fee.length > 0) {
        return `₹${item.fee[0].cost} per ticket`;
      }
      return '₹1,800 per ticket';
    } else {
      return item.price !== 'N/A' ? item.price : 'Contact for pricing';
    }
  };

  // Get title for the item
  const getTitle = (item: EventOrCourse) => {
    return item.title;
  };

  // Get description for the item
  const getDescription = (item: EventOrCourse) => {
    if (item.type === 'event') {
      return item.description;
    } else {
      return item.description;
    }
  };

  // Top section items (first 4 for the grid)
  const topItems = combinedUpcoming.slice(0, 4);
  
  // Featured item (first item)
  const featuredItem = combinedUpcoming.length > 0 ? combinedUpcoming[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 and courses...</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 & Courses
        </h2>
        <button 
          className="text-sm font-medium hover:opacity-70 transition-opacity duration-200"
          style={{ color: '#e64838' }}
          onClick={navigateToAllEvents}
        >
          View All
        </button>
      </div>

      {/* Events/Courses Grid - Top Section with Details */}
      {topItems.length === 0 ? (
        <div className="text-center py-8 mb-12">
          <p className="text-gray-500">No upcoming events or courses.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-12">
          {topItems.map((item, index) => (
            <div 
              key={`${item.type}-${item.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={() => navigateToDetail(item)}
            >
              {getSafeImageUrl(item) ? (
                <img 
                  src={getSafeImageUrl(item)}
                  alt={getTitle(item)}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div className="w-full h-full bg-gray-200 flex items-center justify-center">
                  <span className="text-gray-400 text-sm">No image</span>
                </div>
              )}
              {/* Gradient overlay for better text readability */}
              <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent"></div>
              
              {/* Item type badge */}
              <div className="absolute top-3 right-3">
                <span 
                  className="text-xs font-medium px-2 py-1 rounded"
                  style={{ 
                    backgroundColor: item.type === 'event' ? '#e64838' : '#012068',
                    color: 'white'
                  }}
                >
                  {item.type === 'event' ? 'Event' : 'Course'}
                </span>
              </div>
              
              {/* Item 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' }}>
                  {item.date}
                </div>
                <h4 className="font-medium mb-2 text-sm leading-tight line-clamp-2">
                  {getTitle(item)}
                </h4>
                <div className="text-xs font-medium">
                  {formatPrice(item)}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Featured Section */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Left - Large Featured Item */}
        <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' }}>
            Featured {featuredItem?.type === 'course' ? 'Course' : 'Event'}
          </h3>
          {!featuredItem ? (
            <div className="text-center py-8">
              <p className="text-gray-500">No upcoming events or courses.</p>
            </div>
          ) : (
            <div 
              className="bg-white border border-gray-100 rounded-lg overflow-hidden cursor-pointer hover:shadow-lg transition-shadow"
              onClick={() => navigateToDetail(featuredItem)}
            >
              <div className="relative h-48 md:h-64">
                {getSafeImageUrl(featuredItem) ? (
                  <img 
                    src={getSafeImageUrl(featuredItem)}
                    alt={getTitle(featuredItem)}
                    className="w-full h-full object-cover"
                  />
                ) : (
                  <div className="w-full h-full bg-gray-200 flex items-center justify-center">
                    <span className="text-gray-400">No image available</span>
                  </div>
                )}
                {/* Item type badge */}
                <div className="absolute top-4 right-4">
                  <span 
                    className="text-xs font-medium px-3 py-1 rounded"
                    style={{ 
                      backgroundColor: featuredItem.type === 'event' ? '#e64838' : '#012068',
                      color: 'white'
                    }}
                  >
                    {featuredItem.type === 'event' ? 'Event' : 'Course'}
                  </span>
                </div>
                {/* 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' }}>
                      {featuredItem.date}
                    </div>
                    <h4 className="text-lg md:text-xl font-medium mb-2" style={{ color: '#012068' }}>
                      {getTitle(featuredItem)}
                    </h4>
                    <div className="text-xs leading-relaxed mb-4" style={{ color: '#333' }}>
                      {getDescription(featuredItem)}
                    </div>
                    {featuredItem.type === 'event' && (
                      <div className="text-xs leading-relaxed mb-4" style={{ color: '#333' }}>
                        {featuredItem.detail}
                      </div>
                    )}
                    {featuredItem.type === 'course' && (
                      <div className="flex items-center gap-4 mb-4 text-xs" style={{ color: '#012068' }}>
                        <div className="flex items-center">
                          <span className="mr-1">⏱️</span>
                          <span>{featuredItem.duration}</span>
                        </div>
                        <div className="flex items-center">
                          <span className="mr-1">👥</span>
                          <span>{featuredItem.seats} seats</span>
                        </div>
                        <div className="flex items-center">
                          <span className="mr-1">👨‍🏫</span>
                          <span>{featuredItem.instructor}</span>
                        </div>
                      </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 {featuredItem.type === 'course' ? 'Course' : 'Event'}
                      </div>
                      {featuredItem.type === 'event' && (
                        <div className="text-xs" style={{ color: '#012068' }}>
                          📍 {featuredItem.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();
                        navigateToDetail(featuredItem);
                      }}
                    >
                      {featuredItem.type === 'course' ? 'Apply Now' : 'Book Your Seat'}
                    </button>
                    <div className="text-sm font-medium" style={{ color: '#e64838' }}>
                      {formatPrice(featuredItem)}
                    </div>
                    {featuredItem.type === 'event' && (
                      <div className="text-xs mt-1" style={{ color: '#012068', opacity: 0.8 }}>
                        Early bird discount available
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Right - Past Events List with Scroller - FIXED */}
        <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={() => router.push(`/event-detail/${event.id}`)}
                >
                  {/* FIXED: Added explicit height - no fallback */}
                  <div className="h-24 w-full overflow-hidden">
                    {event.mainImage && event.mainImage.trim() !== '' ? (
                      <img 
                        src={event.mainImage}
                        alt={event.title}
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <div className="w-full h-full bg-gray-200 flex items-center justify-center">
                        <span className="text-gray-400 text-xs">No image</span>
                      </div>
                    )}
                  </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 line-clamp-2" 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();
                          router.push(`/event-detail/${event.id}`);
                        }}
                      >
                        View Details
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default EventsSection;