'use client';

import { useState, useEffect } from 'react';
import { api, Event } from '@/lib/api';
import { useAuth } from '@/lib/auth-context';

interface EventDetailProps {
  eventId: string;
}

export function EventDetail({ eventId }: EventDetailProps) {
  const [event, setEvent] = useState<Event | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { user } = useAuth();

  useEffect(() => {
    loadEvent();
  }, [eventId]);

  const loadEvent = async () => {
    try {
      setIsLoading(true);
      const data = await api.getEvent(eventId);
      setEvent(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load event');
    } finally {
      setIsLoading(false);
    }
  };

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

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

  if (!event) {
    return <div className="text-center py-8">Event not found</div>;
  }

  const isOrganizer = user?.id === event.organizer.id;
  const canEdit = isOrganizer || user?.role === 'Organizer';

  return (
    <div className="max-w-4xl mx-auto">
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <div className="flex justify-between items-start mb-4">
          <div>
            <span className={`inline-block px-2 py-1 text-xs rounded mb-2 ${
              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>
            <h1 className="text-3xl font-bold">{event.name}</h1>
          </div>
          {canEdit && (
            <a
              href={`/events/${event.id}/edit`}
              className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
            >
              Edit Event
            </a>
          )}
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          <div className="space-y-3">
            <div className="flex items-center gap-3">
              <span className="text-2xl">📅</span>
              <div>
                <p className="text-sm text-gray-500">Date</p>
                <p className="font-medium">{new Date(event.eventDate).toLocaleString()}</p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <span className="text-2xl">📍</span>
              <div>
                <p className="text-sm text-gray-500">Location</p>
                <p className="font-medium">{event.location}</p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <span className="text-2xl">👥</span>
              <div>
                <p className="text-sm text-gray-500">Registrations</p>
                <p className="font-medium">
                  {event.currentRegistrations} registered
                  {event.maxParticipants && ` / ${event.maxParticipants} max`}
                </p>
              </div>
            </div>
          </div>

          <div className="space-y-3">
            {event.category && (
              <div className="flex items-center gap-3">
                <span className="text-2xl">🏷️</span>
                <div>
                  <p className="text-sm text-gray-500">Category</p>
                  <p className="font-medium">{event.category}</p>
                </div>
              </div>
            )}
            <div className="flex items-center gap-3">
              <span className="text-2xl">👤</span>
              <div>
                <p className="text-sm text-gray-500">Organizer</p>
                <p className="font-medium">{event.organizer.name}</p>
              </div>
            </div>
            {event.tags.length > 0 && (
              <div className="flex flex-wrap gap-2">
                {event.tags.map((tag) => (
                  <span key={tag} className="px-2 py-1 bg-gray-100 text-gray-700 text-sm rounded">
                    {tag}
                  </span>
                ))}
              </div>
            )}
          </div>
        </div>

        <div className="border-t pt-6">
          <h2 className="text-xl font-semibold mb-3">Description</h2>
          <p className="text-gray-700 whitespace-pre-wrap">{event.description}</p>
        </div>

        {user?.role === 'Participant' && event.status === 'Published' && (
          <div className="border-t pt-6 mt-6">
            <a
              href={`/events/${event.id}/register`}
              className="block text-center py-3 px-6 bg-green-600 text-white rounded-md hover:bg-green-700 font-semibold"
            >
              Register for Event
            </a>
          </div>
        )}
      </div>
    </div>
  );
}