'use client';

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

export function RegistrationList() {
  const [registrations, setRegistrations] = useState<Registration[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { user } = useAuth();

  useEffect(() => {
    loadRegistrations();
  }, []);

  const loadRegistrations = async () => {
    try {
      setIsLoading(true);
      const data = await api.getMyRegistrations();
      setRegistrations(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load registrations');
    } finally {
      setIsLoading(false);
    }
  };

  const handleCancel = async (id: string) => {
    if (!confirm('Are you sure you want to cancel this registration?')) {
      return;
    }
    
    try {
      await api.cancelRegistration(id);
      loadRegistrations();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to cancel registration');
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'Confirmed':
        return 'bg-green-100 text-green-800';
      case 'Pending':
        return 'bg-yellow-100 text-yellow-800';
      case 'Cancelled':
        return 'bg-red-100 text-red-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  if (isLoading) {
    return <div className="text-center py-8">Loading registrations...</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">
      {registrations.length === 0 ? (
        <div className="text-center py-8 text-gray-500">
          <p className="mb-4">You haven&apos;t registered for any events yet.</p>
          <a href="/events" className="text-blue-600 hover:underline">
            Browse events
          </a>
        </div>
      ) : (
        <div className="space-y-4">
          {registrations.map((registration) => (
            <div key={registration.id} className="bg-white rounded-lg shadow-md p-6">
              <div className="flex justify-between items-start">
                <div>
                  <div className="flex items-center gap-2 mb-2">
                    <span className={`px-2 py-1 text-xs rounded ${getStatusColor(registration.status)}`}>
                      {registration.status}
                    </span>
                    <span className="text-sm text-gray-500">
                      {new Date(registration.eventDate).toLocaleDateString()}
                    </span>
                  </div>
                  <h3 className="text-xl font-semibold mb-2">{registration.eventName}</h3>
                  <p className="text-sm text-gray-500 mb-2">
                    Registered: {new Date(registration.registeredAt).toLocaleDateString()}
                  </p>
                  {registration.totalPaid > 0 && (
                    <p className="text-sm text-green-600">
                      Paid: ${registration.totalPaid.toFixed(2)}
                    </p>
                  )}
                </div>
                
                <div className="flex flex-col gap-2">
                  <a
                    href={`/events/${registration.eventId}`}
                    className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm text-center"
                  >
                    View Event
                  </a>
                  {registration.status !== 'Cancelled' && registration.status !== 'Completed' && (
                    <button
                      onClick={() => handleCancel(registration.id)}
                      className="px-4 py-2 border border-red-500 text-red-500 rounded-md hover:bg-red-50 text-sm"
                    >
                      Cancel
                    </button>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}