'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 Breadcrumbs from '@/components/layout/Breadcrumbs';
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,
  getGetRaceWithSOFQuery,
} from '@/lib/di-container';
import { ArrowLeft, Zap, Trophy, Users, Clock, Calendar } from 'lucide-react';

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 [raceSOF, setRaceSOF] = useState<number | null>(null);
  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 raceWithSOFQuery = getGetRaceWithSOFQuery();

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

      setRace(raceData);

      // Load race with SOF from application query
      const raceWithSOF = await raceWithSOFQuery.execute({ raceId });
      if (raceWithSOF) {
        setRaceSOF(raceWithSOF.strengthOfField);
      }

      // 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;

  const breadcrumbItems = [
    { label: 'Races', href: '/races' },
    ...(league ? [{ label: league.name, href: `/leagues/${league.id}` }] : []),
    ...(race ? [{ label: race.track, href: `/races/${raceId}` }] : []),
    { label: 'Results' },
  ];

  return (
    <div className="min-h-screen bg-deep-graphite py-8 px-4 sm:px-6 lg:px-8">
      <div className="max-w-6xl mx-auto space-y-6">
        {/* Navigation Row: Breadcrumbs left, Back button right */}
        <div className="flex items-center justify-between">
          <Breadcrumbs items={breadcrumbItems} className="text-sm text-gray-400" />
          <Button
            variant="secondary"
            onClick={() => router.back()}
            className="flex items-center gap-2 text-sm"
          >
            <ArrowLeft className="w-4 h-4" />
            Back
          </Button>
        </div>

        {/* Hero Header */}
        <div className="relative overflow-hidden rounded-2xl bg-gray-500/10 border border-gray-500/30 p-6 sm:p-8">
          <div className="absolute top-0 right-0 w-64 h-64 bg-white/5 rounded-full blur-3xl" />
          
          <div className="relative z-10">
            <div className="flex items-center gap-3 mb-4">
              <div className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-performance-green/10 border border-performance-green/30">
                <Trophy className="w-4 h-4 text-performance-green" />
                <span className="text-sm font-semibold text-performance-green">Final Results</span>
              </div>
              {raceSOF && (
                <span className="flex items-center gap-1.5 text-warning-amber text-sm">
                  <Zap className="w-4 h-4" />
                  SOF {raceSOF}
                </span>
              )}
            </div>
            
            <h1 className="text-2xl sm:text-3xl font-bold text-white mb-2">
              {race?.track ?? 'Race'} Results
            </h1>
            
            <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-gray-400">
              {race && (
                <>
                  <span className="flex items-center gap-2">
                    <Calendar className="w-4 h-4" />
                    {new Date(race.scheduledAt).toLocaleDateString('en-US', {
                      weekday: 'short',
                      month: 'short',
                      day: 'numeric',
                    })}
                  </span>
                  <span className="flex items-center gap-2">
                    <Users className="w-4 h-4" />
                    {results.length} drivers classified
                  </span>
                </>
              )}
              {league && (
                <span className="text-primary-blue">{league.name}</span>
              )}
            </div>
          </div>
        </div>

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

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

        {/* Content */}
        <Card>
          {hasResults ? (
            <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>
  );
}