'use client';

import { useState, useEffect } from 'react';
import { api, Event } from '@/lib/api';

export function EventList() {
  const [events, setEvents] = useState<Event[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [category, setCategory] = useState('');
  const [status, setStatus] = useState('');

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

  const loadEvents = async () => {
    try {
      setIsLoading(true);
      const data = await api.getEvents({
        category: category || undefined,
        status: status || undefined,
      });
      setEvents(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load events');
    } finally {
      setIsLoading(false);
    }
  };

  const categories = ['Running', 'Cycling', 'Triathlon', 'Trail', 'Road'];

  if (isLoading) {
    return <div className="text-center py-8">Loading events...</div>;
  }

  if (error) {
    return (
      <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
        {error}
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Filters */}
      <div className="flex gap-4 mb-6">
        <select
          value={category}
          onChange={(e) => setCategory(e.target.value)}
          className="px-3 py-2 border border-gray-300 rounded-md"
        >
          <option value="">All Categories</option>
          {categories.map((cat) => (
            <option key={cat} value={cat}>{cat}</option>
          ))}
        </select>
        
        <select
          value={status}
          onChange={(e) => setStatus(e.target.value)}
          className="px-3 py-2 border border-gray-300 rounded-md"
        >
          <option value="">All Status</option>
          <option value="Published">Published</option>
          <option value="Draft">Draft</option>
          <option value="Cancelled">Cancelled</option>
        </select>
      </div>

      {/* Events Grid */}
      {events.length === 0 ? (
        <div className="text-center py-8 text-gray-500">No events found</div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {events.map((event) => (
            <div key={event.id} className="bg-white rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow">
              <div className="flex justify-between items-start mb-2">
                <span className={`px-2 py-1 text-xs rounded ${
                  event.status === 'Published' ? 'bg-green-100 text-green-800' :
                  event.status === 'Draft' ? 'bg-yellow-100 text-yellow-800' :
                  'bg-red-100 text-red-800'
                }`}>
                  {event.status}
                </span>
                {event.category && (
                  <span className="text-sm text-gray-500">{event.category}</span>
                )}
              </div>
              
              <h3 className="text-xl font-semibold mb-2">{event.name}</h3>
              <p className="text-gray-600 mb-4 line-clamp-2">{event.description}</p>
              
              <div className="space-y-2 text-sm text-gray-500">
                <div className="flex items-center gap-2">
                  <span>📅</span>
                  {new Date(event.eventDate).toLocaleDateString()}
                </div>
                <div className="flex items-center gap-2">
                  <span>📍</span>
                  {event.location}
                </div>
                <div className="flex items-center gap-2">
                  <span>👥</span>
                  {event.currentRegistrations}
                  {event.maxParticipants && ` / ${event.maxParticipants}`} registered
                </div>
              </div>
              
              {event.tags.length > 0 && (
                <div className="flex flex-wrap gap-2 mt-4">
                  {event.tags.map((tag) => (
                    <span key={tag} className="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded">
                      {tag}
                    </span>
                  ))}
                </div>
              )}
              
              <a
                href={`/events/${event.id}`}
                className="mt-4 block text-center py-2 px-4 bg-blue-600 text-white rounded-md hover:bg-blue-700"
              >
                View Details
              </a>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}