'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 QuickPenaltyModal from '@/components/leagues/QuickPenaltyModal';
import {
  getGetRaceWithSOFUseCase,
  getGetRaceResultsDetailUseCase,
  getImportRaceResultsUseCase,
  getLeagueMembershipRepository,
} from '@/lib/di-container';
import { useEffectiveDriverId } from '@/lib/currentDriver';
import { isLeagueAdminOrHigherRole } from '@/lib/leagueRoles';
import { RaceWithSOFPresenter } from '@/lib/presenters/RaceWithSOFPresenter';
import { RaceResultsDetailPresenter } from '@/lib/presenters/RaceResultsDetailPresenter';
import type {
  RaceResultsHeaderViewModel,
  RaceResultsLeagueViewModel,
} from '@core/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 currentDriverId = useEffectiveDriverId();

  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 [raceSOF, setRaceSOF] = useState<number | null>(null);
  const [penalties, setPenalties] = useState<PenaltyData[]>([]);
  const [pointsSystem, setPointsSystem] = useState<Record<number, number> | undefined>(undefined);
  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 [isAdmin, setIsAdmin] = useState(false);
  const [showQuickPenaltyModal, setShowQuickPenaltyModal] = useState(false);
  const [preSelectedDriver, setPreSelectedDriver] = useState<DriverRowDTO | undefined>(undefined);

  const loadData = async () => {
    try {
      const raceResultsUseCase = getGetRaceResultsDetailUseCase();
      const raceResultsPresenter = new RaceResultsDetailPresenter();
      await raceResultsUseCase.execute({ raceId }, raceResultsPresenter);

      const viewModel = raceResultsPresenter.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);
      } 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);
        const mappedPenalties: PenaltyData[] = viewModel.penalties.map((p) => {
          const base: PenaltyData = {
            driverId: p.driverId,
            type: p.type as PenaltyTypeDTO,
          };
          if (typeof p.value === 'number') {
            return { ...base, value: p.value };
          }
          return base;
        });
        setPenalties(mappedPenalties);
      }

      try {
        const raceWithSOFUseCase = getGetRaceWithSOFUseCase();
        const sofPresenter = new RaceWithSOFPresenter();
        await raceWithSOFUseCase.execute({ raceId }, sofPresenter);
        const raceViewModel = sofPresenter.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]);

  useEffect(() => {
    if (league?.id && currentDriverId) {
      const checkAdmin = async () => {
        const membershipRepo = getLeagueMembershipRepository();
        const membership = await membershipRepo.getMembership(league.id, currentDriverId);
        setIsAdmin(membership ? isLeagueAdminOrHigherRole(membership.role) : false);
      };
      checkAdmin();
    }
  }, [league?.id, currentDriverId]);

  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);
  };

  const handlePenaltyClick = (driver: DriverRowDTO) => {
    setPreSelectedDriver(driver);
    setShowQuickPenaltyModal(true);
  };

  const handleCloseQuickPenaltyModal = () => {
    setShowQuickPenaltyModal(false);
    setPreSelectedDriver(undefined);
  };

  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>
  
          {showQuickPenaltyModal && (
            <QuickPenaltyModal
              {...({
                raceId,
                drivers: drivers as any,
                onClose: handleCloseQuickPenaltyModal,
                preSelectedDriver: preSelectedDriver as any,
                adminId: currentDriverId,
                races: undefined,
              } as any)}
            />
          )}
        </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 ?? 0}
              penalties={penalties}
              currentDriverId={currentDriverId ?? ''}
              isAdmin={isAdmin}
              onPenaltyClick={handlePenaltyClick}
            />
          ) : (
            <>
              <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>
  );
}