'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useLanguage } from '@/context/LanguageContext';
import { eventsApi, Event } from '@/lib/api';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import ShareButtons from '@/components/ShareButtons';
import { 
  CalendarIcon, 
  MapPinIcon, 
  UserGroupIcon,
  ArrowLeftIcon,
} from '@heroicons/react/24/outline';

interface EventDetailClientProps {
  eventId: string;
  initialEvent: Event;
}

export default function EventDetailClient({ eventId, initialEvent }: EventDetailClientProps) {
  const { t, locale } = useLanguage();
  const [event, setEvent] = useState<Event>(initialEvent);
  const [mounted, setMounted] = useState(false);

  // Ensure consistent hydration by only rendering dynamic content after mount
  useEffect(() => {
    setMounted(true);
  }, []);

  // Refresh event data on client for real-time availability
  useEffect(() => {
    eventsApi.getById(eventId)
      .then(({ event }) => setEvent(event))
      .catch(console.error);
  }, [eventId]);

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString(locale === 'es' ? 'es-ES' : 'en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  const formatTime = (dateStr: string) => {
    return new Date(dateStr).toLocaleTimeString(locale === 'es' ? 'es-ES' : 'en-US', {
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const isSoldOut = event.availableSeats === 0;
  const isCancelled = event.status === 'cancelled';
  // Only calculate isPastEvent after mount to avoid hydration mismatch
  const isPastEvent = mounted ? new Date(event.startDatetime) < new Date() : false;
  const canBook = !isSoldOut && !isCancelled && !isPastEvent && event.status === 'published';

  return (
    <div className="section-padding">
      <div className="container-page">
        <Link 
          href="/events" 
          className="inline-flex items-center gap-2 text-gray-600 hover:text-primary-dark mb-8"
        >
          <ArrowLeftIcon className="w-4 h-4" />
          {t('common.back')}
        </Link>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Event Details */}
          <div className="lg:col-span-2">
            <Card className="overflow-hidden">
              {/* Banner - LCP element, loaded with high priority */}
              {/* Using unoptimized for backend-served images via /uploads/ rewrite */}
              {event.bannerUrl ? (
                <div className="relative h-64 w-full">
                  <Image 
                    src={event.bannerUrl} 
                    alt={`${event.title} - Spanglish language exchange event in Asunción`}
                    fill
                    className="object-cover"
                    sizes="(max-width: 1024px) 100vw, 66vw"
                    priority
                    unoptimized
                  />
                </div>
              ) : (
                <div className="h-64 bg-gradient-to-br from-primary-yellow/40 to-secondary-blue/30 flex items-center justify-center">
                  <CalendarIcon className="w-24 h-24 text-primary-dark/30" />
                </div>
              )}
              
              <div className="p-8">
                <div className="flex items-start justify-between gap-4">
                  <h1 className="text-3xl font-bold text-primary-dark" suppressHydrationWarning>
                    {locale === 'es' && event.titleEs ? event.titleEs : event.title}
                  </h1>
                  {isCancelled && (
                    <span className="badge badge-danger text-sm">{t('events.details.cancelled')}</span>
                  )}
                  {isSoldOut && !isCancelled && (
                    <span className="badge badge-warning text-sm">{t('events.details.soldOut')}</span>
                  )}
                </div>
                
                <div className="mt-8 grid grid-cols-1 sm:grid-cols-2 gap-6">
                  <div className="flex items-start gap-3">
                    <CalendarIcon className="w-6 h-6 text-primary-yellow flex-shrink-0" />
                    <div>
                      <p className="font-medium">{t('events.details.date')}</p>
                      <p className="text-gray-600" suppressHydrationWarning>{formatDate(event.startDatetime)}</p>
                    </div>
                  </div>
                  
                  <div className="flex items-start gap-3">
                    <span className="w-6 h-6 flex items-center justify-center text-primary-yellow text-xl">⏰</span>
                    <div>
                      <p className="font-medium">{t('events.details.time')}</p>
                      <p className="text-gray-600" suppressHydrationWarning>{formatTime(event.startDatetime)}</p>
                    </div>
                  </div>
                  
                  <div className="flex items-start gap-3">
                    <MapPinIcon className="w-6 h-6 text-primary-yellow flex-shrink-0" />
                    <div>
                      <p className="font-medium">{t('events.details.location')}</p>
                      <p className="text-gray-600">{event.location}</p>
                      {event.locationUrl && (
                        <a 
                          href={event.locationUrl} 
                          target="_blank" 
                          rel="noopener noreferrer"
                          className="text-secondary-blue hover:underline text-sm"
                        >
                          View on map
                        </a>
                      )}
                    </div>
                  </div>
                  
                  <div className="flex items-start gap-3">
                    <UserGroupIcon className="w-6 h-6 text-primary-yellow flex-shrink-0" />
                    <div>
                      <p className="font-medium">{t('events.details.capacity')}</p>
                      <p className="text-gray-600">
                        {event.availableSeats} / {event.capacity} {t('events.details.spotsLeft')}
                      </p>
                    </div>
                  </div>
                </div>
                
                <div className="mt-8 pt-8 border-t border-secondary-light-gray">
                  <h2 className="font-semibold text-lg mb-4">About this event</h2>
                  <p className="text-gray-700 whitespace-pre-line" suppressHydrationWarning>
                    {locale === 'es' && event.descriptionEs 
                      ? event.descriptionEs 
                      : event.description}
                  </p>
                </div>
                
                {/* Social Sharing */}
                <div className="mt-8 pt-8 border-t border-secondary-light-gray" suppressHydrationWarning>
                  <ShareButtons 
                    title={locale === 'es' && event.titleEs ? event.titleEs : event.title}
                    description={`${locale === 'es' ? 'Únete a' : 'Join'} ${locale === 'es' && event.titleEs ? event.titleEs : event.title} - ${formatDate(event.startDatetime)}`}
                  />
                </div>
              </div>
            </Card>
          </div>

          {/* Booking Card */}
          <div className="lg:col-span-1">
            <Card className="p-6 sticky top-24">
              <div className="text-center mb-6">
                <p className="text-sm text-gray-500">{t('events.details.price')}</p>
                <p className="text-4xl font-bold text-primary-dark">
                  {event.price === 0 
                    ? t('events.details.free')
                    : `${event.price.toLocaleString()} ${event.currency}`}
                </p>
              </div>
              
              {canBook ? (
                <Link href={`/book/${event.id}`}>
                  <Button className="w-full" size="lg">
                    {t('events.booking.join')}
                  </Button>
                </Link>
              ) : (
                <Button className="w-full" size="lg" disabled>
                  {isPastEvent 
                    ? t('events.details.eventEnded')
                    : isSoldOut 
                      ? t('events.details.soldOut') 
                      : t('events.details.cancelled')}
                </Button>
              )}
              
              <p className="mt-4 text-center text-sm text-gray-500">
                {event.availableSeats} {t('events.details.spotsLeft')}
              </p>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}
