'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useLanguage } from '@/context/LanguageContext';
import { Event } from '@/lib/api';
import { formatPrice, formatDateShort, formatTime } 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';

// Receives the event list already fetched on the server so event titles, dates,
// and locations are present in the initial HTML. The upcoming/past filter below
// is client-side interactivity layered on top of the server-rendered data.
export default function EventsClient({ initialEvents }: { initialEvents: Event[] }) {
  const { t, locale } = useLanguage();
  const [filter, setFilter] = useState<'upcoming' | 'past'>('upcoming');

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

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

  const formatDate = (dateStr: string) => formatDateShort(dateStr, locale as 'en' | 'es');
  const fmtTime = (dateStr: string) => formatTime(dateStr, locale as 'en' | 'es');

  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">
          {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.slug}`} 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)} - {fmtTime(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>
  );
}
