'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'; // Adjust path as needed

const MedicalEventsComponent = () => {
  const [selectedPeriod, setSelectedPeriod] = useState('Upcoming Events');
  const [activeTab, setActiveTab] = useState('Upcoming Events');
  const [upcomingEvents, setUpcomingEvents] = useState<Event[]>([]);
  const [pastEvents, setPastEvents] = useState<Event[]>([]);
  const [nextEvent, setNextEvent] = useState<Event | null>(null);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  
  const router = useRouter();

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

  const loadEvents = async () => {
    try {
      setLoading(true);
      const [upcoming, past] = await Promise.all([
        eventAPI.getUpcomingEvents(),
        eventAPI.getPastEvents()
      ]);
      
      setUpcomingEvents(upcoming);
      setPastEvents(past);
      
      // Set the next event (first upcoming event)
      if (upcoming.length > 0) {
        setNextEvent(upcoming[0]);
      }
    } catch (error) {
      console.error('Error loading events:', error);
    } finally {
      setLoading(false);
    }
  };

  // Filter events based on search term
  const filteredEvents = () => {
    const events = activeTab === 'Upcoming Events' ? upcomingEvents : pastEvents;
    if (!searchTerm) return events;
    
    return events.filter(event => 
      event.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      event.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
      event.subject.toLowerCase().includes(searchTerm.toLowerCase())
    );
  };

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

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

  // Get safe image URL with fallback
  const getSafeImageUrl = (imageUrl: string | undefined, fallback: string) => {
    return imageUrl && imageUrl.trim() !== '' ? imageUrl : fallback;
  };

  // Get gallery images with fallbacks
  const getGalleryImages = (galleryImages: string[] | undefined) => {
    const fallbackImages = [
      'https://images.unsplash.com/photo-1551601651-2a8555f1a136?w=200&h=100&fit=crop',
      'https://images.unsplash.com/photo-1582750433449-648ed127bb54?w=200&h=100&fit=crop',
      'https://images.unsplash.com/photo-1638202993928-7267aad84c31?w=200&h=100&fit=crop',
      'https://images.unsplash.com/photo-1551601651-2a8555f1a136?w=200&h=100&fit=crop'
    ];
    
    if (!galleryImages || galleryImages.length === 0) {
      return fallbackImages;
    }
    
    // Fill missing images with fallbacks
    const validImages = galleryImages.filter(img => img && img.trim() !== '');
    while (validImages.length < 4 && validImages.length < fallbackImages.length) {
      validImages.push(fallbackImages[validImages.length]);
    }
    
    return validImages.slice(0, 4);
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-lg" style={{ color: '#012068' }}>Loading events...</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, 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 an event..."
                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 Event Hero Section */}
          {nextEvent && (
            <div className="mb-8">
              <h2 className="text-lg font-medium mb-4" style={{ color: '#012068' }}>Next Event</h2>
              <div 
                className="bg-white border border-gray-100 rounded-lg overflow-hidden cursor-pointer hover:shadow-lg transition-shadow"
                onClick={() => navigateToEventDetail(nextEvent.id)}
              >
                <div className="relative h-48 md:h-64">
                  <img 
                    src={getSafeImageUrl(nextEvent.mainImage, "https://images.unsplash.com/photo-1576091160550-2173dba999ef?w=800&h=300&fit=crop")} 
                    alt={nextEvent.title}
                    className="w-full h-full object-cover"
                  />
                  <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' }}>{nextEvent.date}</div>
                      <div className="text-lg md:text-xl font-medium mb-2" style={{ color: '#012068' }}>
                        {nextEvent.title}
                      </div>
                      <div className="text-xs leading-relaxed mb-1" style={{ color: '#333' }}>
                        {nextEvent.description}
                      </div>
                      <div className="text-xs leading-relaxed mb-4" style={{ color: '#333' }}>
                        {nextEvent.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' }}>
                          📍 {nextEvent.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();
                          console.log('Book seat clicked');
                        }}
                      >
                        Book Your Seat
                      </button>
                      <div className="text-sm font-medium" style={{ color: '#e64838' }}>{formatPrice(nextEvent)}</div>
                      <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 ({upcomingEvents.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 ({pastEvents.length})
                  </button>
                </div>
              </div>

              {/* Event Rows */}
              <div className="space-y-6">
                {filteredEvents().length === 0 ? (
                  <div className="text-center py-8">
                    <p className="text-gray-500">No events found.</p>
                  </div>
                ) : (
                  filteredEvents().map((event) => (
                    <div 
                      key={event.id} 
                      className="bg-white border border-gray-100 rounded-lg p-4 md:p-6 cursor-pointer hover:shadow-lg transition-shadow"
                      onClick={() => navigateToEventDetail(event.id)}
                    >
                      <div className="flex flex-col md:flex-row gap-4">
                        {/* Images Section */}
                        <div className="flex flex-col sm:flex-row gap-1 md:w-auto">
                          {/* Main image */}
                          <div className="w-full sm:w-48 h-32 md:h-30 flex-shrink-0 rounded-xs overflow-hidden">
                            <img 
                              src={getSafeImageUrl(event.mainImage, "https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=400&h=200&fit=crop")}
                              alt={event.title}
                              className="w-full h-full object-cover"
                            />
                          </div>
                          
                          {/* Gallery grid */}
                          <div className="grid grid-cols-2 gap-1 w-full sm:w-60 h-32 md:h-30">
                            {getGalleryImages(event.galleryImages).map((img, index) => (
                              <div key={index} className="rounded-xs overflow-hidden">
                                <img 
                                  src={img}
                                  alt={`${event.title} gallery ${index + 1}`}
                                  className="w-full h-full object-cover"
                                />
                              </div>
                            ))}
                          </div>
                        </div>
                        
                        {/* Event details */}
                        <div className="flex-1 text-sm">
                          <div className="mb-1 font-medium text-xs" style={{ color: '#e64838' }}>
                            {event.date}
                          </div>
                          <div className="font-medium mb-2 text-lg md:text-xl" 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 mb-4" style={{ color: '#333' }}>
                            {event.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();
                                navigateToEventDetail(event.id);
                              }}
                            >
                              View Details
                            </button>
                            <span className="text-gray-400 hidden sm:inline">|</span>
                            <span className="text-xs font-medium" style={{ color: '#e64838' }}>
                              {formatPrice(event)}
                            </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">
                {pastEvents.slice(0, 2).map((event) => (
                  <div 
                    key={event.id}
                    className="cursor-pointer hover:bg-gray-50 p-2 rounded-lg transition-colors"
                    onClick={() => navigateToEventDetail(event.id)}
                  >
                    <div className="w-full h-32 lg:h-28 mb-3 overflow-hidden rounded-xs">
                      <img 
                        src={getSafeImageUrl(event.mainImage, "https://images.unsplash.com/photo-1551601651-2a8555f1a136?w=300&h=200&fit=crop")} 
                        alt={event.title}
                        className="w-full h-full object-cover"
                      />
                    </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;