'use client';

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

export default function EventsPage() {
  const { t, locale } = useLanguage();
  const [events, setEvents] = useState<Event[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<'upcoming' | 'past'>('upcoming');

  useEffect(() => {
    eventsApi.getAll()
      .then(({ events }) => setEvents(events))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const now = new Date();
  const upcomingEvents = events.filter(e => 
    e.status === 'published' && new Date(e.startDatetime) >= now
  );
  const pastEvents = events.filter(e => 
    e.status === 'completed' || (e.status === 'published' && new Date(e.startDatetime) < now)
  );

  const displayedEvents = filter === 'upcoming' ? upcomingEvents : pastEvents;

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

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

  const getStatusBadge = (event: Event) => {
    if (event.status === 'cancelled') {
      return <span className="badge badge-danger">{t('events.details.cancelled')}</span>;
    }
    if (event.availableSeats === 0) {
      return <span className="badge badge-warning">{t('events.details.soldOut')}</span>;
    }
    return null;
  };

  return (
    <div className="section-padding">
      <div className="container-page">
        <h1 className="section-title">{t('events.title')}</h1>
        
        {/* Filter tabs */}
        <div className="mt-8 flex gap-2">
          <button
            onClick={() => setFilter('upcoming')}
            className={clsx(
              'px-4 py-2 rounded-btn font-medium transition-colors',
              filter === 'upcoming'
                ? 'bg-primary-yellow text-primary-dark'
                : 'bg-secondary-gray text-gray-600 hover:bg-gray-200'
            )}
          >
            {t('events.upcoming')} ({upcomingEvents.length})
          </button>
          <button
            onClick={() => setFilter('past')}
            className={clsx(
              'px-4 py-2 rounded-btn font-medium transition-colors',
              filter === 'past'
                ? 'bg-primary-yellow text-primary-dark'
                : 'bg-secondary-gray text-gray-600 hover:bg-gray-200'
            )}
          >
            {t('events.past')} ({pastEvents.length})
          </button>
        </div>

        {/* Events grid */}
        <div className="mt-8">
          {loading ? (
            <div className="text-center py-12">
              <div className="animate-spin w-8 h-8 border-4 border-primary-yellow border-t-transparent rounded-full mx-auto" />
            </div>
          ) : displayedEvents.length === 0 ? (
            <div className="text-center py-16 text-gray-500">
              <CalendarIcon className="w-16 h-16 mx-auto mb-4 text-gray-300" />
              <p className="text-lg">{t('events.noEvents')}</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {displayedEvents.map((event) => (
                <Link key={event.id} href={`/events/${event.id}`} className="block">
                  <Card variant="elevated" className="card-hover overflow-hidden cursor-pointer h-full">
                    {/* Event banner */}
                    {event.bannerUrl ? (
                      <img 
                        src={event.bannerUrl} 
                        alt={`${event.title} - Spanglish language exchange event in Asunción`}
                        className="h-40 w-full object-cover"
                        loading="lazy"
                      />
                    ) : (
                      <div className="h-40 bg-gradient-to-br from-primary-yellow/30 to-secondary-blue/20 flex items-center justify-center">
                        <CalendarIcon className="w-16 h-16 text-primary-dark/30" />
                      </div>
                    )}
                    
                    <div className="p-6">
                      <div className="flex items-start justify-between gap-2">
                        <h3 className="font-semibold text-lg text-primary-dark">
                          {locale === 'es' && event.titleEs ? event.titleEs : event.title}
                        </h3>
                        {getStatusBadge(event)}
                      </div>
                      
                      <div className="mt-4 space-y-2 text-sm text-gray-600">
                        <div className="flex items-center gap-2">
                          <CalendarIcon className="w-4 h-4" />
                          <span>{formatDate(event.startDatetime)} - {formatTime(event.startDatetime)}</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <MapPinIcon className="w-4 h-4" />
                          <span className="truncate">{event.location}</span>
                        </div>
                        {!event.externalBookingEnabled && (
                          <div className="flex items-center gap-2">
                            <UserGroupIcon className="w-4 h-4" />
                            <span>
                              {Math.max(0, event.capacity - (event.bookedCount ?? 0))} / {event.capacity} {t('events.details.spotsLeft')}
                            </span>
                          </div>
                        )}
                      </div>
                      
                      <div className="mt-6 flex items-center justify-between">
                        <span className="font-bold text-xl text-primary-dark">
                          {event.price === 0 
                            ? t('events.details.free')
                            : formatPrice(event.price, event.currency)}
                        </span>
                        <Button size="sm">
                          {t('common.moreInfo')}
                        </Button>
                      </div>
                    </div>
                  </Card>
                </Link>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
