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

// Combined type for events and training programs
type DisplayItem = 
  | (Event & { type: 'event'; itemDate: Date })
  | (Course & { 
      type: 'training'; 
      itemDate: Date; 
      mainImage: string; 
      date: string;  // Add this field
      detail: string; 
      galleryImages?: string[]; 
      venue?: any[] 
    });

const MedicalEventsComponent = () => {
  const [selectedPeriod, setSelectedPeriod] = useState('Upcoming Events');
  const [activeTab, setActiveTab] = useState('Upcoming Events');
  const [upcomingItems, setUpcomingItems] = useState<DisplayItem[]>([]);
  const [pastItems, setPastItems] = useState<DisplayItem[]>([]);
  const [nextItem, setNextItem] = useState<DisplayItem | null>(null);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  
  const router = useRouter();

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

  const loadData = async () => {
    try {
      setLoading(true);
      const [events, trainingPrograms] = await Promise.all([
        eventAPI.getAllEvents(), // Get all events (both upcoming and past)
        educationService.getActiveCourses() // Get all training programs
      ]);
      
      const currentDate = new Date();
      currentDate.setHours(0, 0, 0, 0); // Set to start of day for accurate comparison
      
      // Transform events with type
      const eventsWithType: DisplayItem[] = events.map(event => {
        const eventDate = new Date(event.date);
        return {
          ...event,
          type: 'event' as const,
          itemDate: eventDate
        };
      });

      // Transform training programs (courses) with type
      const trainingWithType: DisplayItem[] = trainingPrograms.map(course => {
        const courseDate = course.startDate ? new Date(course.startDate) : new Date();
        return {
          ...course,
          type: 'training' as const,
          itemDate: courseDate,
          mainImage: course.image,
          detail: `${course.duration} | ${course.seats} seats available | Led by ${course.instructor}`,
          galleryImages: [], // Training programs don't have gallery images
          date: course.startDate || 'Date TBD'
        };
      });

      // Combine all items (events + training programs)
      const allItems = [...eventsWithType, ...trainingWithType];

      // Separate into upcoming and past based on date
      const upcoming = allItems
        .filter(item => item.itemDate >= currentDate)
        .sort((a, b) => a.itemDate.getTime() - b.itemDate.getTime());

      const past = allItems
        .filter(item => item.itemDate < currentDate)
        .sort((a, b) => b.itemDate.getTime() - a.itemDate.getTime()); // Most recent first

      setUpcomingItems(upcoming);
      setPastItems(past);
      
      // Set the next item (first upcoming item)
      if (upcoming.length > 0) {
        setNextItem(upcoming[0]);
      }
    } catch (error) {
      console.error('Error loading data:', error);
    } finally {
      setLoading(false);
    }
  };

  // Filter items based on search term and active tab
  const filteredItems = () => {
    const items = activeTab === 'Upcoming Events' ? upcomingItems : pastItems;
    if (!searchTerm) return items;
    
    return items.filter(item => 
      item.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.description.toLowerCase().includes(searchTerm.toLowerCase())
    );
  };

  // Navigation function
  const navigateToDetail = (item: DisplayItem) => {
    if (item.type === 'event') {
      router.push(`/event-detail/${item.id}`);
    } else {
      // For training programs, navigate to course detail
      router.push(`/education-training/course-detail?id=${item.id}`);
    }
  };

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

  // Get safe image URL - no fallback, return empty string if no image
  const getSafeImageUrl = (imageUrl: string | undefined): string => {
    if (!imageUrl || imageUrl.trim() === '') {
      return '';
    }
    return imageUrl;
  };

  // Get gallery images - no fallbacks, only return valid images
  const getGalleryImages = (item: DisplayItem): string[] => {
    if (item.type === 'training') {
      return [];
    }
    
    const galleryImages = item.galleryImages;
    
    if (!galleryImages || galleryImages.length === 0) {
      return [];
    }
    
    // Only return valid images, no fallbacks
    return galleryImages.filter(img => img && img.trim() !== '');
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-lg" style={{ color: '#012068' }}>Loading events and training programs...</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen">
      {/* Breadcrumb Section */}
      <section className="py-4" style={{ backgroundColor: '#f4f4f4' }}>
        <div className="max-w-7xl mx-auto px-4">
          <nav className="flex items-center space-x-2 text-sm">
            <Link 
              href="/" 
              className="hover:opacity-70 transition-opacity duration-200"
              style={{ color: '#012068' }}
            >
              Home
            </Link>
            <ChevronRight className="w-4 h-4" style={{ color: '#012068' }} />
            <span className="font-medium" style={{ color: '#e64838' }}>
              Medical Events
            </span>
          </nav>
          
          {/* Page Header */}
          <div className="mt-6">
            <div className="flex items-center mb-4">
              <h1 className="text-2xl md:text-3xl font-bold" style={{ color: '#012068' }}>
                Medical Events
              </h1>
            </div>
            <p className="text-sm md:text-base max-w-2xl leading-relaxed" style={{ color: '#333' }}>
              Discover upcoming medical conferences, workshops, training programs and professional development events
            </p>
          </div>
        </div>
      </section>

      {/* Main Content */}
      <div className="py-6" style={{ backgroundColor: '#fff' }}>
        <div className="max-w-7xl mx-auto px-4">
          {/* Header with dropdown and search */}
          <div className="flex flex-col sm:flex-row justify-end items-start sm:items-center gap-4 mb-6">
            <div className="relative w-full sm:w-auto">
              <select 
                value={selectedPeriod}
                onChange={(e) => setSelectedPeriod(e.target.value)}
                className="appearance-none bg-white text-sm border rounded-lg px-4 py-2 pr-8 focus:outline-none w-full sm:w-auto"
                style={{ 
                  borderColor: '#012068',
                  color: '#333'
                }}
              >
                <option>Upcoming Events</option>
                <option>This Week</option>
                <option>This Month</option>
                <option>This Year</option>
              </select>
              <div className="absolute inset-y-0 right-0 flex items-center px-2 pointer-events-none">
                <svg className="w-4 h-4" style={{ color: '#012068' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                </svg>
              </div>
            </div>
            <div className="relative w-full sm:w-64">
              <input
                type="text"
                placeholder="Search events or training programs..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="border rounded-lg px-4 py-2 pl-4 pr-10 text-sm focus:outline-none w-full"
                style={{ 
                  borderColor: '#012068',
                  color: '#012068'
                }}
              />
              <button 
                className="absolute inset-y-0 right-0 flex items-center px-3 rounded-r-lg"
                style={{ backgroundColor: '#012068' }}
              >
                <svg className="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
              </button>
            </div>
          </div>

          {/* Next Item Hero Section */}
          {nextItem && (
            <div className="mb-8">
              <h2 className="text-lg font-medium mb-4" style={{ color: '#012068' }}>
                Next {nextItem.type === 'training' ? 'Training Program' : 'Event'}
              </h2>
              <div 
                className="bg-white border border-gray-100 rounded-lg overflow-hidden cursor-pointer hover:shadow-lg transition-shadow"
                onClick={() => navigateToDetail(nextItem)}
              >
                <div className="relative h-48 md:h-64">
                  {getSafeImageUrl(nextItem.mainImage) ? (
                    <img 
                      src={getSafeImageUrl(nextItem.mainImage)} 
                      alt={nextItem.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-sm">No image available</span>
                    </div>
                  )}
                  {/* Type Badge */}
                  <div className="absolute top-4 right-4">
                    <span 
                      className="px-3 py-1 rounded text-xs font-medium"
                      style={{ 
                        backgroundColor: nextItem.type === 'event' ? '#e64838' : '#012068',
                        color: 'white'
                      }}
                    >
                      {nextItem.type === 'event' ? 'Event' : 'Training Program'}
                    </span>
                  </div>
                  <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' }}>
                        {nextItem.type === 'event' ? nextItem.date : (nextItem.date || 'Date TBD')}
                      </div>
                      <div className="text-lg md:text-xl font-medium mb-2" style={{ color: '#012068' }}>
                        {nextItem.title}
                      </div>
                      <div className="text-xs leading-relaxed mb-1" style={{ color: '#333' }}>
                        {nextItem.description}
                      </div>
                      <div className="text-xs leading-relaxed mb-4" style={{ color: '#333' }}>
                        {nextItem.detail || (nextItem.type === 'event' ? nextItem.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 {nextItem.type === 'training' ? 'Training Program' : 'Event'}
                        </div>
                        {nextItem.type === 'event' && (
                          <div className="text-xs" style={{ color: '#012068' }}>
                            📍 {nextItem.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: '#012068',
                          color: '#f4f4f4'
                        }}
                        onClick={(e) => {
                          e.stopPropagation();
                          navigateToDetail(nextItem);
                        }}
                      >
                        {nextItem.type === 'training' ? 'Register Now' : 'Book Your Seat'}
                      </button>
                      <div className="text-sm font-medium" style={{ color: '#e64838' }}>{formatPrice(nextItem)}</div>
                      {nextItem.type === 'event' && (
                        <div className="text-xs mt-1" style={{ color: '#333' }}>
                          Early bird discount available
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          <div className="flex flex-col lg:flex-row gap-8">
            {/* Main Content */}
            <div className="flex-1">
              {/* Tabs */}
              <div className="border-b mb-6" style={{ borderColor: '#666666ff' }}>
                <div className="flex space-x-4 md:space-x-8">
                  <button
                    onClick={() => setActiveTab('Upcoming Events')}
                    className={`pb-3 text-sm ${
                      activeTab === 'Upcoming Events'
                        ? 'border-b-2 font-medium'
                        : 'hover:opacity-70'
                    }`}
                    style={{
                      borderColor: activeTab === 'Upcoming Events' ? '#e64838' : 'transparent',
                      color: activeTab === 'Upcoming Events' ? '#012068' : '#012068'
                    }}
                  >
                    Upcoming Events ({upcomingItems.length})
                  </button>
                  <button
                    onClick={() => setActiveTab('Past Events')}
                    className={`pb-3 text-sm ${
                      activeTab === 'Past Events'
                        ? 'border-b-2 font-medium'
                        : 'hover:opacity-70'
                    }`}
                    style={{
                      borderColor: activeTab === 'Past Events' ? '#e64838' : 'transparent',
                      color: activeTab === 'Past Events' ? '#012068' : '#012068'
                    }}
                  >
                    Past Events ({pastItems.length})
                  </button>
                </div>
              </div>

              {/* Item Rows - FIXED IMAGE STYLING */}
              <div className="space-y-6">
                {filteredItems().length === 0 ? (
                  <div className="text-center py-8">
                    <p className="text-gray-500">No items found.</p>
                  </div>
                ) : (
                  filteredItems().map((item) => {
                    const galleryImages = getGalleryImages(item);
                    const showGallery = item.type === 'event' && galleryImages.length > 0;
                    
                    return (
                      <div 
                        key={`${item.type}-${item.id}`}
                        className="bg-white border border-gray-100 rounded-lg p-4 md:p-6 cursor-pointer hover:shadow-lg transition-shadow"
                        onClick={() => navigateToDetail(item)}
                      >
                        <div className="flex flex-col md:flex-row gap-4">
                          {/* Images Section - FIXED */}
                          <div className="flex flex-col sm:flex-row gap-1 w-full md:w-auto">
                            {/* Main image - FIXED HEIGHT */}
                            <div className="w-full sm:w-48 h-32 md:h-32 flex-shrink-0 rounded-sm overflow-hidden relative">
                              {getSafeImageUrl(item.mainImage) ? (
                                <img 
                                  src={getSafeImageUrl(item.mainImage)}
                                  alt={item.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>
                              )}
                              {/* Type Badge */}
                              <div className="absolute top-2 right-2">
                                <span 
                                  className="px-2 py-1 rounded text-xs font-medium"
                                  style={{ 
                                    backgroundColor: item.type === 'event' ? '#e64838' : '#012068',
                                    color: 'white'
                                  }}
                                >
                                  {item.type === 'event' ? 'Event' : 'Training'}
                                </span>
                              </div>
                            </div>
                            
                            {/* Gallery grid - only for events, only if images exist */}
                            {showGallery && galleryImages.length > 0 && (
                              <div className="grid grid-cols-2 gap-1 w-full sm:w-60 h-32 md:h-32">
                                {galleryImages.map((img, index) => (
                                  <div key={index} className="rounded-sm overflow-hidden">
                                    <img 
                                      src={img}
                                      alt={`${item.title} gallery ${index + 1}`}
                                      className="w-full h-full object-cover"
                                    />
                                  </div>
                                ))}
                              </div>
                            )}
                          </div>
                          
                          {/* Item details */}
                          <div className="flex-1 text-sm">
                            <div className="mb-1 font-medium text-xs" style={{ color: '#e64838' }}>
                              {item.type === 'event' ? item.date : item.date}
                            </div>
                            <div className="font-medium mb-2 text-lg md:text-xl" style={{ color: '#012068' }}>
                              {item.title}
                            </div>
                            <div className="text-xs leading-relaxed mb-1" style={{ color: '#333' }}>
                              {item.description}
                            </div>
                            <div className="text-xs leading-relaxed mb-4" style={{ color: '#333' }}>
                              {item.type === 'event' ? item.detail : item.detail}
                            </div>
                            <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">
                              <button 
                                className="text-xs hover:underline text-left"
                                style={{ color: '#012068' }}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  navigateToDetail(item);
                                }}
                              >
                                View Details
                              </button>
                              <span className="text-gray-400 hidden sm:inline">|</span>
                              <span className="text-xs font-medium" style={{ color: '#e64838' }}>
                                {formatPrice(item)}
                              </span>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })
                )}
              </div>
            </div>

            {/* Right Sidebar */}
            <div className="w-full lg:w-64 lg:border-l lg:pl-4" style={{ borderColor: '#666666ff' }}>
              <h3 className="text-lg font-medium mb-6" style={{ color: '#012068' }}>
                Recent Past Events
              </h3>
              <div className="grid sm:grid-cols-2 lg:grid-cols-1 gap-6">
                {pastItems.filter(item => item.type === 'event').slice(0, 2).map((item) => {
                  const event = item as Event & { type: 'event'; itemDate: Date };
                  return (
                    <div 
                      key={event.id}
                      className="cursor-pointer hover:bg-gray-50 p-2 rounded-lg transition-colors"
                      onClick={() => router.push(`/event-detail/${event.id}`)}
                    >
                      <div className="w-full h-32 lg:h-28 mb-3 overflow-hidden rounded-sm">
                        {getSafeImageUrl(event.mainImage) ? (
                          <img 
                            src={getSafeImageUrl(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="text-sm">
                        <div className="mb-1 font-medium text-xs" style={{ color: '#e64838' }}>
                          {event.date}
                        </div>
                        <div className="font-medium mb-1" style={{ color: '#012068' }}>
                          {event.title}
                        </div>
                        <div className="text-xs leading-relaxed mb-1" style={{ color: '#333' }}>
                          {event.description}
                        </div>
                        <div className="text-xs leading-relaxed" style={{ color: '#333' }}>
                          {event.detail}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default MedicalEventsComponent;