'use client';

import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { ArrowLeft, Zap, Trophy, Users, Clock, Calendar } from 'lucide-react';
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 {
  getGetRaceWithSOFUseCase,
  getGetRaceResultsDetailUseCase,
  getImportRaceResultsUseCase,
} from '@/lib/di-container';
import type {
  RaceResultsHeaderViewModel,
  RaceResultsLeagueViewModel,
} from '@gridpilot/racing/application/presenters/IRaceResultsDetailPresenter';

type PenaltyTypeDTO =
  | 'time_penalty'
  | 'grid_penalty'
  | 'points_deduction'
  | 'disqualification'
  | 'warning'
  | 'license_points'
  | string;

interface PenaltyData {
  driverId: string;
  type: PenaltyTypeDTO;
  value?: number;
}

interface RaceResultRowDTO {
  id: string;
  raceId: string;
  driverId: string;
  position: number;
  fastestLap: number;
  incidents: number;
  startPosition: number;
  getPositionChange(): number;
}

interface DriverRowDTO {
  id: string;
  name: string;
}

interface ImportResultRowDTO {
  id: string;
  raceId: string;
  driverId: string;
  position: number;
  fastestLap: number;
  incidents: number;
  startPosition: number;
}

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

  const [race, setRace] = useState<RaceResultsHeaderViewModel | null>(null);
  const [league, setLeague] = useState<RaceResultsLeagueViewModel | null>(null);
  const [results, setResults] = useState<RaceResultRowDTO[]>([]);
  const [drivers, setDrivers] = useState<DriverRowDTO[]>([]);
  const [currentDriverId, setCurrentDriverId] = useState<string | undefined>(undefined);
  const [raceSOF, setRaceSOF] = useState<number | null>(null);
  const [penalties, setPenalties] = useState<PenaltyData[]>([]);
  const [pointsSystem, setPointsSystem] = useState<Record<number, number>>({});
  const [fastestLapTime, setFastestLapTime] = useState<number | undefined>(undefined);
  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 raceResultsUseCase = getGetRaceResultsDetailUseCase();
      await raceResultsUseCase.execute({ raceId });

      const viewModel = raceResultsUseCase.presenter.getViewModel();

      if (!viewModel) {
        setError('Failed to load race data');
        setLoading(false);
        return;
      }

      if (viewModel.error && !viewModel.race) {
        setError(viewModel.error);
        setRace(null);
        setLeague(null);
        setResults([]);
        setDrivers([]);
        setPenalties([]);
        setPointsSystem({});
        setFastestLapTime(undefined);
        setCurrentDriverId(undefined);
      } else {
        setError(null);
        setRace(viewModel.race);
        setLeague(viewModel.league);
        setResults(viewModel.results as unknown as RaceResultRowDTO[]);
        setDrivers(
          viewModel.drivers.map((d) => ({
            id: d.id,
            name: d.name,
          })),
        );
        setPointsSystem(viewModel.pointsSystem);
        setFastestLapTime(viewModel.fastestLapTime);
        setCurrentDriverId(viewModel.currentDriverId);
        setPenalties(
          viewModel.penalties.map((p) => ({
            driverId: p.driverId,
            type: p.type as PenaltyTypeDTO,
            value: p.value,
          })),
        );
      }

      try {
        const raceWithSOFUseCase = getGetRaceWithSOFUseCase();
        await raceWithSOFUseCase.execute({ raceId });
        const raceViewModel = raceWithSOFUseCase.presenter.getViewModel();
        if (raceViewModel) {
          setRaceSOF(raceViewModel.strengthOfField);
        }
      } catch (sofErr) {
        console.error('Failed to load SOF:', sofErr);
      }
    } 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: ImportResultRowDTO[]) => {
    setImporting(true);
    setError(null);

    try {
      const importUseCase = getImportRaceResultsUseCase();
      await importUseCase.execute({
        raceId,
        results: importedResults,
      });

      setImportSuccess(true);
      await loadData();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to import results');
    } finally {
      setImporting(false);
    }
  };

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

  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/${race.id}` }] : []),
    { 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">
        <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>

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

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

        <Card>
          {hasResults ? (
            <ResultsTable
              results={results}
              drivers={drivers}
              pointsSystem={pointsSystem}
              fastestLapTime={fastestLapTime}
              penalties={penalties}
              currentDriverId={currentDriverId}
            />
          ) : (
            <>
              <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>
  );
}