'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 ResultsTable from '@/components/races/ResultsTable';
import ImportResultsForm from '@/components/races/ImportResultsForm';
import { Race } from '@gridpilot/racing/domain/entities/Race';
import { League } from '@gridpilot/racing/domain/entities/League';
import { Result } from '@gridpilot/racing/domain/entities/Result';
import { Driver } from '@gridpilot/racing/domain/entities/Driver';
import {
  getRaceRepository,
  getLeagueRepository,
  getResultRepository,
  getStandingRepository,
  getDriverRepository
} from '@/lib/di-container';

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

  const [race, setRace] = useState<Race | null>(null);
  const [league, setLeague] = useState<League | null>(null);
  const [results, setResults] = useState<Result[]>([]);
  const [drivers, setDrivers] = useState<Driver[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [importing, setImporting] = useState(false);
  const [importSuccess, setImportSuccess] = useState(false);

  const loadData = async () => {
    try {
      const raceRepo = getRaceRepository();
      const leagueRepo = getLeagueRepository();
      const resultRepo = getResultRepository();
      const driverRepo = getDriverRepository();

      const raceData = await raceRepo.findById(raceId);
      
      if (!raceData) {
        setError('Race not found');
        setLoading(false);
        return;
      }

      setRace(raceData);

      // Load league data
      const leagueData = await leagueRepo.findById(raceData.leagueId);
      setLeague(leagueData);

      // Load results
      const resultsData = await resultRepo.findByRaceId(raceId);
      setResults(resultsData);

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

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

  const handleImportSuccess = async (importedResults: Result[]) => {
    setImporting(true);
    setError(null);

    try {
      const resultRepo = getResultRepository();
      const standingRepo = getStandingRepository();

      // Check if results already exist
      const existingResults = await resultRepo.existsByRaceId(raceId);
      if (existingResults) {
        throw new Error('Results already exist for this race');
      }

      // Create all results
      await resultRepo.createMany(importedResults);

      // Recalculate standings for the league
      if (league) {
        await standingRepo.recalculate(league.id);
      }

      // Reload results
      const resultsData = await resultRepo.findByRaceId(raceId);
      setResults(resultsData);
      setImportSuccess(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to import results');
    } finally {
      setImporting(false);
    }
  };

  const handleImportError = (errorMessage: string) => {
    setError(errorMessage);
  };

  const getPointsSystem = (): Record<number, number> => {
    if (!league) return {};
    
    const pointsSystems: Record<string, Record<number, number>> = {
      'f1-2024': {
        1: 25, 2: 18, 3: 15, 4: 12, 5: 10,
        6: 8, 7: 6, 8: 4, 9: 2, 10: 1
      },
      'indycar': {
        1: 50, 2: 40, 3: 35, 4: 32, 5: 30,
        6: 28, 7: 26, 8: 24, 9: 22, 10: 20,
        11: 19, 12: 18, 13: 17, 14: 16, 15: 15
      }
    };

    return league.settings.customPoints || 
           pointsSystems[league.settings.pointsSystem] || 
           pointsSystems['f1-2024'];
  };

  const getFastestLapTime = (): number | undefined => {
    if (results.length === 0) return undefined;
    return Math.min(...results.map(r => r.fastestLap));
  };

  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 results...</div>
        </div>
      </div>
    );
  }

  if (error && !race) {
    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 || 'Race not found'}
            </div>
            <Button
              variant="secondary"
              onClick={() => router.push('/races')}
            >
              Back to Races
            </Button>
          </Card>
        </div>
      </div>
    );
  }

  const hasResults = results.length > 0;

  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(`/races/${raceId}`)}
            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 Race Details
          </button>
        </div>

        {/* Page Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-white mb-2">Race Results</h1>
          {race && (
            <div>
              <p className="text-gray-400">{race.track}</p>
              {league && (
                <p className="text-sm text-gray-500">{league.name}</p>
              )}
            </div>
          )}
        </div>

        {/* Success Message */}
        {importSuccess && (
          <div className="mb-6 p-4 bg-performance-green/10 border border-performance-green/30 rounded text-performance-green">
            <strong>Success!</strong> Results imported and standings updated.
          </div>
        )}

        {/* Error Message */}
        {error && (
          <div className="mb-6 p-4 bg-warning-amber/10 border border-warning-amber/30 rounded text-warning-amber">
            <strong>Error:</strong> {error}
          </div>
        )}

        {/* Content */}
        <Card>
          {hasResults ? (
            <>
              <h2 className="text-xl font-semibold text-white mb-6">Results</h2>
              <ResultsTable 
                results={results}
                drivers={drivers}
                pointsSystem={getPointsSystem()}
                fastestLapTime={getFastestLapTime()}
              />
            </>
          ) : (
            <>
              <h2 className="text-xl font-semibold text-white mb-6">Import Results</h2>
              <p className="text-gray-400 text-sm mb-6">
                No results imported. Upload CSV to test the standings system.
              </p>
              {importing ? (
                <div className="text-center py-8 text-gray-400">
                  Importing results and updating standings...
                </div>
              ) : (
                <ImportResultsForm
                  raceId={raceId}
                  onSuccess={handleImportSuccess}
                  onError={handleImportError}
                />
              )}
            </>
          )}
        </Card>
      </div>
    </div>
  );
}