'use client';

import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import StandingsTable from '@/components/alpha/StandingsTable';
import { League } from '@/domain/entities/League';
import { Standing } from '@/domain/entities/Standing';
import { Driver } from '@/domain/entities/Driver';
import {
  getLeagueRepository,
  getStandingRepository,
  getDriverRepository
} from '@/lib/di-container';

export default function LeagueStandingsPage() {
  const router = useRouter();
  const params = useParams();
  const leagueId = params.id as string;

  const [league, setLeague] = useState<League | null>(null);
  const [standings, setStandings] = useState<Standing[]>([]);
  const [drivers, setDrivers] = useState<Driver[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadData = async () => {
    try {
      const leagueRepo = getLeagueRepository();
      const standingRepo = getStandingRepository();
      const driverRepo = getDriverRepository();

      const leagueData = await leagueRepo.findById(leagueId);
      
      if (!leagueData) {
        setError('League not found');
        setLoading(false);
        return;
      }

      setLeague(leagueData);

      // Load standings
      const standingsData = await standingRepo.findByLeagueId(leagueId);
      setStandings(standingsData);

      // Load drivers
      const driversData = await driverRepo.findAll();
      setDrivers(driversData);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load standings');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [leagueId]);

  if (loading) {
    return (
      <div className="min-h-screen bg-deep-graphite py-12 px-4 sm:px-6 lg:px-8">
        <div className="max-w-6xl mx-auto">
          <div className="text-center text-gray-400">Loading standings...</div>
        </div>
      </div>
    );
  }

  if (error || !league) {
    return (
      <div className="min-h-screen bg-deep-graphite py-12 px-4 sm:px-6 lg:px-8">
        <div className="max-w-6xl mx-auto">
          <Card className="text-center py-12">
            <div className="text-warning-amber mb-4">
              {error || 'League not found'}
            </div>
            <Button
              variant="secondary"
              onClick={() => router.push('/leagues')}
            >
              Back to Leagues
            </Button>
          </Card>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-deep-graphite py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-6xl mx-auto">
        {/* Breadcrumb */}
        <div className="mb-6">
          <button
            onClick={() => router.push(`/leagues/${leagueId}`)}
            className="text-gray-400 hover:text-primary-blue transition-colors text-sm flex items-center gap-2"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
            Back to League Details
          </button>
        </div>

        {/* Page Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-white mb-2">Championship Standings</h1>
          <p className="text-gray-400">{league.name}</p>
        </div>

        {/* Standings Content */}
        <Card>
          {standings.length > 0 ? (
            <>
              <h2 className="text-xl font-semibold text-white mb-6">Current Standings</h2>
              <StandingsTable standings={standings} drivers={drivers} />
            </>
          ) : (
            <div className="text-center py-12">
              <div className="text-gray-400 mb-2">No standings available yet</div>
              <p className="text-sm text-gray-500">
                Standings will appear after race results are imported
              </p>
            </div>
          )}
        </Card>
      </div>
    </div>
  );
}