// app/events/[event_id]/results/page.tsx
// Event championship results page with auto-refresh

import { query } from '@/lib/db';
import Link from 'next/link';
import EventResultsClient from '@/components/events/EventResultsClient';
import { Event } from '@/types/racing';

export const dynamic = "force-dynamic";

async function getEventResults(eventId: string) {

  if (eventId == undefined) {
    return { event: null, standings: [] };
  }
  // Get event info
  const eventSql = `
    SELECT 
      event_id,
      event_name,
      event_track,
      event_date,
      event_status
    FROM events
    WHERE event_id = $1
  `;
  const events = await query(eventSql, [eventId]);
  const event = (events[0] as Event) ?? null;

  // Get team standings with driver details
  const standingsSql = `
    SELECT 
      tcs.team_id,
      t.name as team_name,
      tcs.total_points,
      tcs.races_participated,
      tcs.best_finish,
      json_agg(
        json_build_object(
          'driver_guid', u.driver_guid,
          'driver_name', u.driver_name,
          'position', er.position,
          'points_awarded', er.points_awarded,
          'laps_completed', er.laps_completed,
          'dnf', er.dnf
        ) ORDER BY er.position ASC
      ) as drivers
    FROM team_championship_standings tcs
    JOIN teams t ON tcs.team_id = t.id
    LEFT JOIN event_results er ON tcs.event_id = er.event_id AND tcs.team_id = er.team_id
    LEFT JOIN users u ON er.driver_guid = u.driver_guid
    WHERE tcs.event_id = $1
    GROUP BY tcs.team_id, t.name, tcs.total_points, tcs.races_participated, tcs.best_finish
    ORDER BY tcs.total_points DESC, tcs.best_finish ASC
  `;
  
  const standings = await query(standingsSql, [eventId]);

  return { event, standings: standings as any[] };
}
  
export default async function EventResultsPage({
  params,
}: {
  params: Promise<{ event_id: string }>;
}) {

  const { event_id } = await params;
  const eventId = parseInt(event_id, 10);

  console.log('Fetching results for event ID:', event_id);
  const { event, standings } = await getEventResults(event_id);
  if (!event) {
    return (
      <div className="max-w-7xl mx-auto px-6 py-16">
        <div className="border border-white/10 p-16 text-center bg-black">
          <p className="text-white/40">Event not found</p>
        </div>
      </div>
    );
  }

  return (
    <>
      {/* Hero */}
      <div className="relative border-b border-white/10 grid-overlay">
        <div className="max-w-7xl mx-auto px-6 py-16">
          <div className="space-y-4">
            <Link 
              href={`/events/${event_id}`}
              className="inline-flex items-center space-x-2 text-white/60 hover:text-white transition-colors text-sm"
            >
              <span>←</span>
              <span>Back to Event</span>
            </Link>
            
            <div className="flex items-center space-x-3">
              <div>
                <h1 className="text-5xl font-bold tracking-tight">
                  CHAMPIONSHIP RESULTS
                </h1>
                <p className="text-white/60 text-lg mt-2">
                  {event.event_name}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Team Championship Standings */}
      <div className="max-w-7xl mx-auto px-6 py-12">
        <EventResultsClient 
          eventId={eventId} 
          initialStandings={standings}
        />

        {/* Points System Info */}
        <div className="mt-8 border border-white/10 p-6 bg-black">
          <h3 className="text-sm font-bold tracking-wider text-white/60 mb-4">POINTS SYSTEM</h3>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div><span className="font-mono text-white/80">P1:</span> <span className="font-bold">5 pts</span></div>
            <div><span className="font-mono text-white/80">P2:</span> <span className="font-bold">3 pts</span></div>
            <div><span className="font-mono text-white/80">P3:</span> <span className="font-bold">2 pts</span></div>
            <div><span className="font-mono text-white/80">P4...:</span> <span className="font-bold">1 pts</span></div>
          </div>
          <p className="text-xs text-white/40 mt-4">
            Team points are the sum of all driver points from that team in the event • Updates every 5 seconds
          </p>
        </div>
      </div>
    </>
  );
}
