'use client'
import React, { useState, useEffect } from 'react';
import { Calendar, MapPin, Clock, Users, Star, Share2, ArrowLeft, ChevronRight } from 'lucide-react';
import { useRouter, useParams } from 'next/navigation';
import Link from "next/link";
import { eventAPI, Event } from '../../lib/api'; // Adjust path as needed

const EventDetail = () => {
  const router = useRouter();
  const params = useParams();
  const eventId = params.id as string;
  
  const [eventData, setEventData] = useState<Event | null>(null);
  const [isBookmarked, setIsBookmarked] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchEventData = async () => {
      if (!eventId) {
        console.log('No event ID provided');
        return;
      }
      
      console.log('Fetching event with ID:', eventId);
      setIsLoading(true);
      try {
        const numericId = parseInt(eventId, 10);
        if (isNaN(numericId)) {
          console.error('Invalid event ID:', eventId);
          throw new Error('Invalid event ID');
        }
        console.log('Converted to numeric ID:', numericId);
        
        const event = await eventAPI.getEventById(numericId);
        console.log('Fetched event:', event);
        setEventData(event);
      } catch (error) {
        console.error('Failed to fetch event data:', error);
        setEventData(null);
      } finally {
        setIsLoading(false);
      }
    };
    
    fetchEventData();
  }, [eventId]);

  useEffect(() => {
    if (eventData && typeof window !== 'undefined') {
      try {
        const bookmarkedEvents = JSON.parse(localStorage.getItem('bookmarkedEvents') || '[]');
        setIsBookmarked(bookmarkedEvents.includes(eventData.id.toString()));
      } catch (error) {
        console.error('Error accessing localStorage:', error);
      }
    }
  }, [eventData]);

  const handleBookmark = () => {
    if (!eventData || typeof window === 'undefined') return;

    try {
      const bookmarkedEvents = JSON.parse(localStorage.getItem('bookmarkedEvents') || '[]');
      const eventIdStr = eventData.id.toString();
      let updatedBookmarks;
      if (isBookmarked) {
        updatedBookmarks = bookmarkedEvents.filter((id: string) => id !== eventIdStr);
      } else {
        updatedBookmarks = [...bookmarkedEvents, eventIdStr];
      }
      localStorage.setItem('bookmarkedEvents', JSON.stringify(updatedBookmarks));
      setIsBookmarked(!isBookmarked);
    } catch (error) {
      console.error('Error updating bookmarks:', error);
    }
  };

  // NEW FUNCTION: Handle book seat click - redirects to admin-provided link
  const handleBookSeat = () => {
    if (!eventData) return;
    
    // Check if admin has provided a custom booking link
    if (eventData.bookSeatLink && eventData.bookSeatLink.trim() !== '') {
      // Validate if it's a proper URL
      try {
        // If the URL doesn't start with http:// or https://, add https://
        let url = eventData.bookSeatLink;
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
          url = 'https://' + url;
        }
        // Open in new tab
        window.open(url, '_blank', 'noopener,noreferrer');
      } catch (error) {
        console.error('Invalid booking link:', error);
        alert('Invalid registration link. Please contact the organizers.');
      }
    } else {
      // Fallback: Show alert if no link is configured
      alert('Registration link not configured for this event. Please contact the organizers at ' + eventData.email);
    }
  };

  const handleShare = async () => {
    if (!eventData || typeof window === 'undefined') return;

    try {
      if (navigator.share) {
        await navigator.share({
          title: eventData.title,
          url: window.location.href,
        });
      } else {
        await navigator.clipboard.writeText(window.location.href);
        alert('Event link copied to clipboard!');
      }
    } catch (error) {
      console.error('Share failed:', error);
    }
  };

  const handleGoBack = () => {
    router.back();
  };

  // Helper functions to format API data for display
  const formatPrice = (event: Event) => {
    if (event.fee && event.fee.length > 0) {
      return `₹${event.fee[0].cost} per seat`;
    }
    return '₹1,800 per seat';
  };

  const getPrimaryVenue = (event: Event) => {
    if (event.venue && event.venue.length > 0) {
      return {
        name: event.venue[0].title || 'Medical College Auditorium',
        address: event.venue[0].address || 'Chennai, Tamil Nadu'
      };
    }
    return {
      name: 'Medical College Auditorium',
      address: 'Chennai, Tamil Nadu'
    };
  };

  const getSafeImageUrl = (imageUrl: string | undefined, fallback: string) => {
    return imageUrl && imageUrl.trim() !== '' ? imageUrl : fallback;
  };

  const getGalleryImages = (galleryImages: string[] | undefined) => {
    const fallbackImages = [
      'https://images.unsplash.com/photo-1576091160550-2173dba999ef?w=400&h=200&fit=crop',
      'https://images.unsplash.com/photo-1582750433449-648ed127bb54?w=400&h=200&fit=crop'
    ];
    
    if (!galleryImages || galleryImages.length === 0) {
      return fallbackImages;
    }
    
    const validImages = galleryImages.filter(img => img && img.trim() !== '');
    if (validImages.length === 0) {
      return fallbackImages;
    }
    
    while (validImages.length < 2) {
      validImages.push(fallbackImages[validImages.length % fallbackImages.length]);
    }
    
    return validImages.slice(0, 2);
  };

  const getFormattedDescription = (event: Event) => {
    return {
      overview: event.description || 'Join leading medical professionals for this comprehensive event focusing on the latest developments in healthcare.',
      highlights: event.highlights && event.highlights.length > 0 ? event.highlights : [
        'Expert presentations and case studies',
        'Latest medical innovations and techniques',
        'Hands-on workshops and demonstrations',
        'Networking sessions with industry leaders'
      ],
      includes: [
        'CME Credits',
        'Course materials and resources',
        'Networking breaks and lunch',
        'Certificate of attendance'
      ],
      targetAudience: event.subject ? [event.subject] : [
        'Medical professionals',
        'Healthcare practitioners',
        'Medical students and residents',
        'Healthcare administrators'
      ]
    };
  };

  if (isLoading) {
    return (
      <div className="min-h-screen" style={{ backgroundColor: '#f4f4f4' }}>
        <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' }} />
              <a href="/events" className="hover:opacity-70 transition-opacity duration-200" style={{ color: '#012068' }}>
                Medical Events
              </a>
              <ChevronRight className="w-4 h-4" style={{ color: '#012068' }} />
              <span className="font-medium" style={{ color: '#e64838' }}>Loading...</span>
            </nav>
          </div>
        </section>

        <div className="py-6">
          <div className="max-w-7xl mx-auto px-4">
            <div className="bg-white shadow-lg rounded-lg overflow-hidden">
              <div className="animate-pulse">
                <div className="h-64 md:h-80 bg-gray-200"></div>
                <div className="p-4 md:p-8">
                  <div className="h-4 bg-gray-200 rounded mb-4"></div>
                  <div className="h-6 md:h-8 bg-gray-200 rounded mb-6"></div>
                  <div className="space-y-3">
                    <div className="h-4 bg-gray-200 rounded"></div>
                    <div className="h-4 bg-gray-200 rounded"></div>
                    <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (!eventData) {
    return (
      <div className="min-h-screen" style={{ backgroundColor: '#f4f4f4' }}>
        <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' }} />
              <a href="/events" className="hover:opacity-70 transition-opacity duration-200" style={{ color: '#012068' }}>
                Medical Events
              </a>
              <ChevronRight className="w-4 h-4" style={{ color: '#012068' }} />
              <span className="font-medium" style={{ color: '#e64838' }}>Event Not Found</span>
            </nav>
          </div>
        </section>

        <div className="py-6">
          <div className="max-w-7xl mx-auto px-4">
            <div className="bg-white shadow-lg rounded-lg p-4 md:p-8 text-center">
              <h1 className="text-xl md:text-2xl font-medium mb-4" style={{ color: '#012068' }}>
                Event Not Found
              </h1>
              <button
                onClick={handleGoBack}
                className="px-6 py-2 text-sm rounded-lg hover:opacity-90 transition-opacity"
                style={{ backgroundColor: '#012068', color: '#f4f4f4' }}
              >
                Go Back
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const venue = getPrimaryVenue(eventData);
  const description = getFormattedDescription(eventData);
  const galleryImages = getGalleryImages(eventData.galleryImages);
  const mainImage = getSafeImageUrl(eventData.mainImage, 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=800&h=400&fit=crop');

  return (
    <div className="min-h-screen" style={{ backgroundColor: '#f4f4f4' }}>
      {/* 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' }} />
            <a href="/events" className="hover:opacity-70 transition-opacity duration-200" style={{ color: '#012068' }}>
              Medical Events
            </a>
            <ChevronRight className="w-4 h-4" style={{ color: '#012068' }} />
            <span className="font-medium truncate" style={{ color: '#e64838' }}>
              {eventData.title}
            </span>
          </nav>

          {/* Back Button */}
          <div className="mt-4">
            <button
              onClick={handleGoBack}
              className="flex items-center hover:opacity-70 text-sm transition-opacity duration-200"
              style={{ color: '#012068' }}
            >
              <ArrowLeft className="w-4 h-4 mr-2" />
              Back to Events
            </button>
          </div>
        </div>
      </section>

      <div className="py-6">
        <div className="max-w-7xl mx-auto px-4">
          {/* Image Section */}
          <div className="bg-white shadow-lg rounded-md overflow-hidden mb-6" style={{ borderColor: '#012068' }}>
            <div className="relative">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-1">
                <div className="md:col-span-2 relative overflow-hidden">
                  <img
                    src={mainImage}
                    alt={eventData.title}
                    className="w-full h-auto hover:scale-105 transition-transform duration-300"
                  />
                </div>
                <div className="hidden md:flex md:flex-col gap-1">
                  {galleryImages.map((image, index) => (
                    <div key={index} className="relative overflow-hidden flex-1">
                      <img
                        src={image}
                        alt={`Gallery ${index + 1}`}
                        className="w-full h-full object-cover hover:scale-105 transition-transform duration-300"
                      />
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>

          {/* Event Details Section */}
          <div className="bg-white shadow-lg rounded-lg overflow-hidden" style={{ borderColor: '#012068' }}>
            <div className="p-4 md:p-8">
              {/* Header Section */}
              <div className="flex flex-col sm:flex-row justify-between items-start gap-4 mb-6">
                <div className="flex-1">
                  <div className="text-xs font-medium mb-2" style={{ color: '#e64838' }}>
                    {eventData.date}
                  </div>
                  <h1 className="text-2xl md:text-3xl font-medium leading-tight" style={{ color: '#012068' }}>
                    {eventData.title}
                  </h1>
                </div>
                <div className="text-left sm:text-right w-full sm:w-auto">
                  <div className="text-xs mb-1" style={{ color: '#012068', opacity: 0.8 }}>From</div>
                  <div className="text-lg font-medium mb-3" style={{ color: '#e64838' }}>
                    {formatPrice(eventData)}
                  </div>
                  <button
                    onClick={handleBookSeat}
                    className="w-full sm:w-auto px-6 py-2 text-sm rounded-lg transition-all duration-200 hover:opacity-90"
                    style={{ backgroundColor: '#012068', color: '#f4f4f4' }}
                  >
                    Book Your Seat
                  </button>
                </div>
              </div>

              {/* Event Info Grid */}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
                <div className="flex items-center" style={{ color: '#012068' }}>
                  <Calendar className="w-4 h-4 mr-3 flex-shrink-0" style={{ color: '#e64838' }} />
                  <div>
                    <div className="text-sm font-medium">{eventData.date}</div>
                    <div className="text-xs opacity-80">Full Day Event</div>
                  </div>
                </div>
                <div className="flex items-center" style={{ color: '#012068' }}>
                  <Clock className="w-4 h-4 mr-3 flex-shrink-0" style={{ color: '#e64838' }} />
                  <div>
                    <div className="text-sm font-medium">9:00 AM - 5:00 PM</div>
                    <div className="text-xs opacity-80">8 hours</div>
                  </div>
                </div>
                <div className="flex items-center sm:col-span-2 lg:col-span-1" style={{ color: '#012068' }}>
                  <MapPin className="w-4 h-4 mr-3 flex-shrink-0" style={{ color: '#e64838' }} />
                  <div>
                    <div className="text-sm font-medium">{venue.name}</div>
                    <div className="text-xs opacity-80">{venue.address}</div>
                  </div>
                </div>
              </div>

              {/* About Section */}
              <div className="space-y-4 mb-8">
                <h3 className="text-lg font-medium" style={{ color: '#012068' }}>About This Event</h3>
                <p className="text-md leading-relaxed" style={{ color: '#333' }}>{description.overview}</p>

                {description.highlights.length > 0 && (
                  <div>
                    <h4 className="text-md font-medium mb-2" style={{ color: '#012068' }}>Event Highlights</h4>
                    <ul className="text-sm space-y-1" style={{ color: '#333' }}>
                      {description.highlights.map((highlight, index) => (
                        <li key={index}>• {highlight}</li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>

              {/* Attendees Info */}
              <div className="mb-8 p-4 rounded-lg" style={{ backgroundColor: '#f4f4f4' }}>
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                  <div className="flex items-center" style={{ color: '#012068' }}>
                    <Users className="w-4 h-4 mr-2 flex-shrink-0" style={{ color: '#e64838' }} />
                    <span className="text-xs">Medical professionals attending</span>
                  </div>
                  <div className="text-xs" style={{ color: '#012068', opacity: 0.8 }}>
                    Event ID: #{eventData.id}
                  </div>
                </div>
              </div>

              {/* Info Cards */}
              <div className="mb-8 grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="p-4 border rounded-lg" style={{ borderColor: '#012068' }}>
                  <h4 className="text-sm font-medium mb-2" style={{ color: '#012068' }}>What&apos;s Included</h4>
                  <ul className="text-xs space-y-1" style={{ color: '#333' }}>
                    {description.includes.map((item, index) => (
                      <li key={index}>• {item}</li>
                    ))}
                  </ul>
                </div>
                <div className="p-4 border rounded-lg" style={{ borderColor: '#012068' }}>
                  <h4 className="text-sm font-medium mb-2" style={{ color: '#012068' }}>Target Audience</h4>
                  <ul className="text-xs space-y-1" style={{ color: '#333' }}>
                    {description.targetAudience.map((audience, index) => (
                      <li key={index}>• {audience}</li>
                    ))}
                  </ul>
                </div>
              </div>

              {/* Footer Actions */}
              <div className="flex flex-col sm:flex-row sm:items-center gap-4">
                <button
                  onClick={handleShare}
                  className="flex items-center text-xs hover:underline"
                  style={{ color: '#012068' }}
                >
                  <Share2 className="w-3 h-3 mr-1" />
                  Share Event
                </button>
                <span className="text-gray-400 hidden sm:inline">|</span>
                <span className="text-xs" style={{ color: '#012068', opacity: 0.8 }}>
                  📍 {venue.name}, {venue.address}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default EventDetail;