'use client';

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

export function Dashboard() {
  const { user } = useAuth();
  const [dashboard, setDashboard] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const loadDashboard = async () => {
    try {
      setIsLoading(true);
      if (user?.role === 'Organizer') {
        const data = await api.getOrganizerDashboard();
        setDashboard(data);
      } else {
        const data = await api.getParticipantDashboard();
        setDashboard(data);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load dashboard');
    } finally {
      setIsLoading(false);
    }
  };

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

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

  if (!dashboard) {
    return <div className="text-center py-8">No data available</div>;
  }

  return (
    <div className="space-y-8">
      {/* Quick Actions */}
      <div className="flex gap-4 flex-wrap">
        {user?.role === 'Organizer' ? (
          <>
            <a href="/events/create" className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
              Create Event
            </a>
            <a href="/events" className="px-6 py-3 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">
              Manage Events
            </a>
          </>
        ) : (
          <>
            <a href="/events" className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
              Browse Events
            </a>
            <a href="/registrations" className="px-6 py-3 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">
              My Registrations
            </a>
          </>
        )}
      </div>

      {/* Stats Grid */}
      {user?.role === 'Organizer' ? (
        <OrganizerDashboard data={dashboard} />
      ) : (
        <ParticipantDashboard data={dashboard} />
      )}
    </div>
  );
}

function OrganizerDashboard({ data }: { data: any }) {
  return (
    <>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard title="Total Events" value={data.totalEvents} />
        <StatCard title="Published" value={data.publishedEvents} color="green" />
        <StatCard title="Draft" value={data.draftEvents} color="yellow" />
        <StatCard title="Total Registrations" value={data.totalRegistrations} color="blue" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-lg font-semibold mb-4">Upcoming Events</h3>
          {data.upcomingEvents?.length > 0 ? (
            <div className="space-y-3">
              {data.upcomingEvents.map((event: any) => (
                <div key={event.id} className="border-b pb-3 last:border-0">
                  <a href={`/events/${event.id}`} className="font-medium hover:text-blue-600">
                    {event.name}
                  </a>
                  <p className="text-sm text-gray-500">
                    {new Date(event.eventDate).toLocaleDateString()} - {event.registrationCount} registered
                  </p>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-gray-500">No upcoming events</p>
          )}
        </div>

        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-lg font-semibold mb-4">Revenue</h3>
          <div className="text-3xl font-bold text-green-600 mb-2">
            ${data.totalRevenue?.toFixed(2) || '0.00'}
          </div>
          <div className="grid grid-cols-3 gap-4 mt-4 text-sm">
            <div className="text-center">
              <div className="font-bold text-green-600">{data.paidRegistrations}</div>
              <div className="text-gray-500">Paid</div>
            </div>
            <div className="text-center">
              <div className="font-bold text-yellow-600">{data.pendingRegistrations}</div>
              <div className="text-gray-500">Pending</div>
            </div>
            <div className="text-center">
              <div className="font-bold text-red-600">{data.cancelledRegistrations}</div>
              <div className="text-gray-500">Cancelled</div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

function ParticipantDashboard({ data }: { data: any }) {
  return (
    <>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard title="Total Registrations" value={data.totalRegistrations} />
        <StatCard title="Upcoming Events" value={data.upcomingEvents} color="green" />
        <StatCard title="Completed" value={data.completedEvents} color="blue" />
        <StatCard title="Cancelled" value={data.cancelledRegistrations} color="red" />
      </div>

      <div className="bg-white rounded-lg shadow-md p-6">
        <h3 className="text-lg font-semibold mb-4">My Recent Registrations</h3>
        {data.myRegistrations?.length > 0 ? (
          <div className="space-y-3">
            {data.myRegistrations.slice(0, 5).map((reg: any) => (
              <div key={reg.id} className="flex justify-between items-center border-b pb-3 last:border-0">
                <div>
                  <a href={`/events/${reg.eventId}`} className="font-medium hover:text-blue-600">
                    {reg.eventName}
                  </a>
                  <p className="text-sm text-gray-500">
                    {new Date(reg.eventDate).toLocaleDateString()} - 
                    <span className={`ml-2 px-2 py-1 text-xs rounded ${
                      reg.status === 'Confirmed' ? 'bg-green-100 text-green-800' :
                      reg.status === 'Pending' ? 'bg-yellow-100 text-yellow-800' :
                      'bg-red-100 text-red-800'
                    }`}>
                      {reg.status}
                    </span>
                  </p>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-gray-500">
            No registrations yet. <a href="/events" className="text-blue-600 hover:underline">Browse events</a>
          </p>
        )}
      </div>
    </>
  );
}

function StatCard({ title, value, color = 'gray' }: { title: string; value: number; color?: string }) {
  const colorClasses: Record<string, string> = {
    gray: 'bg-white',
    green: 'bg-green-50',
    yellow: 'bg-yellow-50',
    blue: 'bg-blue-50',
    red: 'bg-red-50',
  };

  return (
    <div className={`${colorClasses[color]} rounded-lg shadow-md p-6`}>
      <h3 className="text-sm font-medium text-gray-500 mb-2">{title}</h3>
      <div className="text-3xl font-bold">{value}</div>
    </div>
  );
}