'use client';

import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Link from 'next/link';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import Heading from '@/components/ui/Heading';
import Breadcrumbs from '@/components/layout/Breadcrumbs';
import type { Race } from '@gridpilot/racing/domain/entities/Race';
import type { League } from '@gridpilot/racing/domain/entities/League';
import type { Driver } from '@gridpilot/racing/domain/entities/Driver';
import {
  getRaceRepository,
  getLeagueRepository,
  getDriverRepository,
  getGetRaceRegistrationsQuery,
  getIsDriverRegisteredForRaceQuery,
  getRegisterForRaceUseCase,
  getWithdrawFromRaceUseCase,
  getTrackRepository,
  getCarRepository,
  getGetRaceWithSOFQuery,
} from '@/lib/di-container';
import { getMembership } from '@/lib/leagueMembership';
import { useEffectiveDriverId } from '@/lib/currentDriver';
import {
  Calendar,
  Clock,
  MapPin,
  Car,
  Trophy,
  Users,
  Zap,
  PlayCircle,
  CheckCircle2,
  XCircle,
  ChevronRight,
  Flag,
  Timer,
  UserPlus,
  UserMinus,
  AlertTriangle,
  ArrowRight,
  ArrowLeft,
  ExternalLink,
  Award,
} from 'lucide-react';
import { getDriverStats, getAllDriverRankings } from '@/lib/di-container';

export default function RaceDetailPage() {
  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 [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [cancelling, setCancelling] = useState(false);
  const [registering, setRegistering] = useState(false);
  const [entryList, setEntryList] = useState<Driver[]>([]);
  const [isUserRegistered, setIsUserRegistered] = useState(false);
  const [canRegister, setCanRegister] = useState(false);
  const [raceSOF, setRaceSOF] = useState<number | null>(null);

  const currentDriverId = useEffectiveDriverId();

  const loadRaceData = async () => {
    try {
      const raceRepo = getRaceRepository();
      const leagueRepo = getLeagueRepository();
      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 entry list
      await loadEntryList(raceData.id, raceData.leagueId);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load race');
    } finally {
      setLoading(false);
    }
  };

  const loadEntryList = async (raceId: string, leagueId: string) => {
    try {
      const driverRepo = getDriverRepository();

      const raceRegistrationsQuery = getGetRaceRegistrationsQuery();
      const registeredDriverIds = await raceRegistrationsQuery.execute({ raceId });

      const drivers = await Promise.all(
        registeredDriverIds.map((id: string) => driverRepo.findById(id)),
      );
      const validDrivers = drivers.filter((d: Driver | null): d is Driver => d !== null);
      setEntryList(validDrivers);

      const isRegisteredQuery = getIsDriverRegisteredForRaceQuery();
      const userIsRegistered = await isRegisteredQuery.execute({
        raceId,
        driverId: currentDriverId,
      });
      setIsUserRegistered(userIsRegistered);

      const membership = getMembership(leagueId, currentDriverId);
      const isUpcoming = race?.status === 'scheduled';
      setCanRegister(!!membership && membership.status === 'active' && !!isUpcoming);
    } catch (err) {
      console.error('Failed to load entry list:', err);
    }
  };

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

  const handleCancelRace = async () => {
    if (!race || race.status !== 'scheduled') return;

    const confirmed = window.confirm(
      'Are you sure you want to cancel this race? This action cannot be undone.'
    );

    if (!confirmed) return;

    setCancelling(true);
    try {
      const raceRepo = getRaceRepository();
      const cancelledRace = race.cancel();
      await raceRepo.update(cancelledRace);
      setRace(cancelledRace);
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Failed to cancel race');
    } finally {
      setCancelling(false);
    }
  };

  const handleRegister = async () => {
    if (!race || !league) return;

    const confirmed = window.confirm(
      `Register for ${race.track}?\n\nYou'll be added to the entry list for this race.`
    );

    if (!confirmed) return;

    setRegistering(true);
    try {
      const useCase = getRegisterForRaceUseCase();
      await useCase.execute({
        raceId: race.id,
        leagueId: league.id,
        driverId: currentDriverId,
      });
      await loadEntryList(race.id, league.id);
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Failed to register for race');
    } finally {
      setRegistering(false);
    }
  };

  const handleWithdraw = async () => {
    if (!race || !league) return;

    const confirmed = window.confirm(
      'Withdraw from this race?\n\nYou can register again later if you change your mind.'
    );

    if (!confirmed) return;

    setRegistering(true);
    try {
      const useCase = getWithdrawFromRaceUseCase();
      await useCase.execute({
        raceId: race.id,
        driverId: currentDriverId,
      });
      await loadEntryList(race.id, league.id);
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Failed to withdraw from race');
    } finally {
      setRegistering(false);
    }
  };

  const formatDate = (date: Date) => {
    return new Date(date).toLocaleDateString('en-US', {
      weekday: 'long',
      month: 'long',
      day: 'numeric',
      year: 'numeric',
    });
  };

  const formatTime = (date: Date) => {
    return new Date(date).toLocaleTimeString('en-US', {
      hour: '2-digit',
      minute: '2-digit',
      timeZoneName: 'short',
    });
  };

  const getTimeUntil = (date: Date) => {
    const now = new Date();
    const target = new Date(date);
    const diffMs = target.getTime() - now.getTime();
    
    if (diffMs < 0) return null;
    
    const days = Math.floor(diffMs / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
    
    if (days > 0) return `${days}d ${hours}h`;
    if (hours > 0) return `${hours}h ${minutes}m`;
    return `${minutes}m`;
  };

  const statusConfig = {
    scheduled: {
      icon: Clock,
      color: 'text-primary-blue',
      bg: 'bg-primary-blue/10',
      border: 'border-primary-blue/30',
      label: 'Scheduled',
      description: 'This race is scheduled and waiting to start',
    },
    running: {
      icon: PlayCircle,
      color: 'text-performance-green',
      bg: 'bg-performance-green/10',
      border: 'border-performance-green/30',
      label: 'LIVE NOW',
      description: 'This race is currently in progress',
    },
    completed: {
      icon: CheckCircle2,
      color: 'text-gray-400',
      bg: 'bg-gray-500/10',
      border: 'border-gray-500/30',
      label: 'Completed',
      description: 'This race has finished',
    },
    cancelled: {
      icon: XCircle,
      color: 'text-warning-amber',
      bg: 'bg-warning-amber/10',
      border: 'border-warning-amber/30',
      label: 'Cancelled',
      description: 'This race has been cancelled',
    },
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-deep-graphite py-8 px-4 sm:px-6 lg:px-8">
        <div className="max-w-4xl mx-auto">
          <div className="animate-pulse space-y-6">
            <div className="h-6 bg-iron-gray rounded w-1/4" />
            <div className="h-48 bg-iron-gray rounded-xl" />
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              <div className="lg:col-span-2 h-64 bg-iron-gray rounded-xl" />
              <div className="h-64 bg-iron-gray rounded-xl" />
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (error || !race) {
    return (
      <div className="min-h-screen bg-deep-graphite py-8 px-4 sm:px-6 lg:px-8">
        <div className="max-w-4xl mx-auto">
          <Breadcrumbs items={[{ label: 'Races', href: '/races' }, { label: 'Error' }]} />
          
          <Card className="text-center py-12 mt-6">
            <div className="flex flex-col items-center gap-4">
              <div className="p-4 bg-warning-amber/10 rounded-full">
                <AlertTriangle className="w-8 h-8 text-warning-amber" />
              </div>
              <div>
                <p className="text-white font-medium mb-1">{error || 'Race not found'}</p>
                <p className="text-sm text-gray-500">The race you're looking for doesn't exist or has been removed.</p>
              </div>
              <Button
                variant="secondary"
                onClick={() => router.push('/races')}
                className="mt-4"
              >
                Back to Races
              </Button>
            </div>
          </Card>
        </div>
      </div>
    );
  }

  const config = statusConfig[race.status];
  const StatusIcon = config.icon;
  const timeUntil = race.status === 'scheduled' ? getTimeUntil(race.scheduledAt) : null;

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

  // Build driver rankings for entry list display
  const getDriverRank = (driverId: string): { rating: number | null; rank: number | null } => {
    const stats = getDriverStats(driverId);
    if (!stats) return { rating: null, rank: null };
    
    const allRankings = getAllDriverRankings();
    let rank = stats.overallRank;
    if (!rank || rank <= 0) {
      const indexInGlobal = allRankings.findIndex(s => s.driverId === driverId);
      if (indexInGlobal !== -1) {
        rank = indexInGlobal + 1;
      }
    }
    
    return { rating: stats.rating, rank };
  };

  return (
    <div className="min-h-screen bg-deep-graphite py-8 px-4 sm:px-6 lg:px-8">
      <div className="max-w-4xl 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 ${config.bg} border ${config.border} p-6 sm:p-8`}>
          {/* Live indicator */}
          {race.status === 'running' && (
            <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-performance-green via-performance-green/50 to-performance-green animate-pulse" />
          )}
          
          <div className="absolute top-0 right-0 w-64 h-64 bg-white/5 rounded-full blur-3xl" />
          
          <div className="relative z-10">
            {/* Status Badge */}
            <div className="flex items-center gap-3 mb-4">
              <div className={`flex items-center gap-2 px-3 py-1.5 rounded-full ${config.bg} border ${config.border}`}>
                {race.status === 'running' && (
                  <span className="w-2 h-2 bg-performance-green rounded-full animate-pulse" />
                )}
                <StatusIcon className={`w-4 h-4 ${config.color}`} />
                <span className={`text-sm font-semibold ${config.color}`}>{config.label}</span>
              </div>
              {timeUntil && (
                <span className="text-sm text-gray-400">
                  Starts in <span className="text-white font-medium">{timeUntil}</span>
                </span>
              )}
            </div>

            {/* Title */}
            <Heading level={1} className="text-2xl sm:text-3xl font-bold text-white mb-2">
              {race.track}
            </Heading>
            
            {/* Meta */}
            <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-gray-400">
              <span className="flex items-center gap-2">
                <Calendar className="w-4 h-4" />
                {formatDate(race.scheduledAt)}
              </span>
              <span className="flex items-center gap-2">
                <Clock className="w-4 h-4" />
                {formatTime(race.scheduledAt)}
              </span>
              <span className="flex items-center gap-2">
                <Car className="w-4 h-4" />
                {race.car}
              </span>
              {raceSOF && (
                <span className="flex items-center gap-2 text-warning-amber">
                  <Zap className="w-4 h-4" />
                  SOF {raceSOF}
                </span>
              )}
            </div>
          </div>
        </div>

        {/* League Banner */}
        {league && (
          <Link
            href={`/leagues/${league.id}`}
            className="block group"
          >
            <div className="relative overflow-hidden rounded-xl bg-gradient-to-r from-primary-blue/10 via-primary-blue/5 to-transparent border border-primary-blue/20 p-4 transition-all hover:border-primary-blue/40">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <div className="p-3 bg-primary-blue/20 rounded-xl">
                    <Trophy className="w-6 h-6 text-primary-blue" />
                  </div>
                  <div>
                    <p className="text-xs text-gray-400 uppercase tracking-wide">Part of</p>
                    <p className="text-lg font-semibold text-white group-hover:text-primary-blue transition-colors">
                      {league.name}
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-2 text-primary-blue">
                  <span className="text-sm hidden sm:block">View League</span>
                  <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
                </div>
              </div>
            </div>
          </Link>
        )}

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Main Content */}
          <div className="lg:col-span-2 space-y-6">
            {/* Race Details */}
            <Card>
              <h2 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                <Flag className="w-5 h-5 text-primary-blue" />
                Race Details
              </h2>
              
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="p-4 bg-deep-graphite rounded-lg">
                  <p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Track</p>
                  <p className="text-white font-medium">{race.track}</p>
                </div>
                <div className="p-4 bg-deep-graphite rounded-lg">
                  <p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Car</p>
                  <p className="text-white font-medium">{race.car}</p>
                </div>
                <div className="p-4 bg-deep-graphite rounded-lg">
                  <p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Session Type</p>
                  <p className="text-white font-medium capitalize">{race.sessionType}</p>
                </div>
                <div className="p-4 bg-deep-graphite rounded-lg">
                  <p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Status</p>
                  <p className={`font-medium ${config.color}`}>{config.label}</p>
                </div>
                <div className="p-4 bg-deep-graphite rounded-lg">
                  <p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Strength of Field</p>
                  <p className="text-warning-amber font-medium flex items-center gap-1.5">
                    <Zap className="w-4 h-4" />
                    {raceSOF ?? '—'}
                  </p>
                </div>
                {race.registeredCount !== undefined && (
                  <div className="p-4 bg-deep-graphite rounded-lg">
                    <p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Registered</p>
                    <p className="text-white font-medium">
                      {race.registeredCount}
                      {race.maxParticipants && ` / ${race.maxParticipants}`}
                    </p>
                  </div>
                )}
              </div>
            </Card>

            {/* Entry List */}
            <Card>
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-lg font-semibold text-white flex items-center gap-2">
                  <Users className="w-5 h-5 text-primary-blue" />
                  Entry List
                </h2>
                <span className="text-sm text-gray-400">
                  {entryList.length} driver{entryList.length !== 1 ? 's' : ''}
                </span>
              </div>

              {entryList.length === 0 ? (
                <div className="text-center py-8">
                  <div className="p-4 bg-iron-gray rounded-full inline-block mb-3">
                    <Users className="w-6 h-6 text-gray-500" />
                  </div>
                  <p className="text-gray-400">No drivers registered yet</p>
                  <p className="text-sm text-gray-500">Be the first to sign up!</p>
                </div>
              ) : (
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                    {entryList.map((driver, index) => {
                      const driverRankInfo = getDriverRank(driver.id);
                      return (
                        <div
                          key={driver.id}
                          onClick={() => router.push(`/drivers/${driver.id}`)}
                          className="flex items-center gap-2 p-2 bg-deep-graphite rounded-lg hover:bg-charcoal-outline/50 cursor-pointer transition-colors"
                        >
                          <span className="w-6 text-xs text-gray-500 font-mono">#{index + 1}</span>
                          <div className="w-7 h-7 bg-iron-gray rounded-full flex items-center justify-center flex-shrink-0">
                            <span className="text-sm font-bold text-gray-400">
                              {driver.name.charAt(0)}
                            </span>
                          </div>
                          <div className="flex-1 min-w-0">
                            <p className="text-white text-sm font-medium truncate">{driver.name}</p>
                          </div>
                          {driverRankInfo.rating && (
                            <span className="text-xs text-warning-amber font-medium">
                              {driverRankInfo.rating}
                            </span>
                          )}
                          {driver.id === currentDriverId && (
                            <span className="px-1.5 py-0.5 text-xs font-medium bg-primary-blue/20 text-primary-blue rounded">
                              You
                            </span>
                          )}
                        </div>
                      );
                    })}
                  </div>
              )}
            </Card>
          </div>

          {/* Sidebar - Actions */}
          <div className="space-y-6">
            {/* Quick Actions Card */}
            <Card>
              <h2 className="text-lg font-semibold text-white mb-4">Actions</h2>
              
              <div className="space-y-3">
                {/* Registration Actions */}
                {race.status === 'scheduled' && canRegister && !isUserRegistered && (
                  <Button
                    variant="primary"
                    className="w-full flex items-center justify-center gap-2"
                    onClick={handleRegister}
                    disabled={registering}
                  >
                    <UserPlus className="w-4 h-4" />
                    {registering ? 'Registering...' : 'Register for Race'}
                  </Button>
                )}

                {race.status === 'scheduled' && isUserRegistered && (
                  <>
                    <div className="flex items-center gap-2 px-4 py-3 bg-performance-green/10 border border-performance-green/30 rounded-lg text-performance-green">
                      <CheckCircle2 className="w-5 h-5" />
                      <span className="font-medium">You're Registered</span>
                    </div>
                    <Button
                      variant="secondary"
                      className="w-full flex items-center justify-center gap-2"
                      onClick={handleWithdraw}
                      disabled={registering}
                    >
                      <UserMinus className="w-4 h-4" />
                      {registering ? 'Withdrawing...' : 'Withdraw'}
                    </Button>
                  </>
                )}

                {race.status === 'completed' && (
                  <Button
                    variant="primary"
                    className="w-full flex items-center justify-center gap-2"
                    onClick={() => router.push(`/races/${race.id}/results`)}
                  >
                    <Trophy className="w-4 h-4" />
                    View Results
                  </Button>
                )}

                {race.status === 'scheduled' && (
                  <Button
                    variant="secondary"
                    className="w-full flex items-center justify-center gap-2"
                    onClick={handleCancelRace}
                    disabled={cancelling}
                  >
                    <XCircle className="w-4 h-4" />
                    {cancelling ? 'Cancelling...' : 'Cancel Race'}
                  </Button>
                )}
              </div>
            </Card>

            {/* Status Info */}
            <Card className={`${config.bg} border ${config.border}`}>
              <div className="flex items-start gap-3">
                <div className={`p-2 rounded-lg ${config.bg}`}>
                  <StatusIcon className={`w-5 h-5 ${config.color}`} />
                </div>
                <div>
                  <p className={`font-medium ${config.color}`}>{config.label}</p>
                  <p className="text-sm text-gray-400 mt-1">{config.description}</p>
                </div>
              </div>
            </Card>

            {/* Quick Links */}
            <Card>
              <h3 className="text-sm font-semibold text-white mb-3">Quick Links</h3>
              <div className="space-y-2">
                <Link
                  href="/races"
                  className="flex items-center gap-3 p-2 rounded-lg hover:bg-deep-graphite transition-colors"
                >
                  <Flag className="w-4 h-4 text-gray-400" />
                  <span className="text-sm text-gray-300">All Races</span>
                </Link>
                {league && (
                  <Link
                    href={`/leagues/${league.id}`}
                    className="flex items-center gap-3 p-2 rounded-lg hover:bg-deep-graphite transition-colors"
                  >
                    <Trophy className="w-4 h-4 text-gray-400" />
                    <span className="text-sm text-gray-300">{league.name}</span>
                  </Link>
                )}
                {league && (
                  <Link
                    href={`/leagues/${league.id}/standings`}
                    className="flex items-center gap-3 p-2 rounded-lg hover:bg-deep-graphite transition-colors"
                  >
                    <Users className="w-4 h-4 text-gray-400" />
                    <span className="text-sm text-gray-300">League Standings</span>
                  </Link>
                )}
              </div>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}