'use client';

import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
import { useRegisterForRace, useWithdrawFromRace } from '@/hooks/useRaceService';
import { useRouter } from 'next/navigation';
import { useMemo, useState } from 'react';
import type { LeagueScheduleRaceViewModel } from '@/lib/view-models/LeagueScheduleViewModel';

// Shared state components
import { useDataFetching } from '@/components/shared/hooks/useDataFetching';
import { StateContainer } from '@/components/shared/state/StateContainer';
import { EmptyState } from '@/components/shared/state/EmptyState';
import { useServices } from '@/lib/services/ServiceProvider';
import { Calendar } from 'lucide-react';

interface LeagueScheduleProps {
  leagueId: string;
}

export default function LeagueSchedule({ leagueId }: LeagueScheduleProps) {
  const router = useRouter();
  const [filter, setFilter] = useState<'all' | 'upcoming' | 'past'>('upcoming');

  const currentDriverId = useEffectiveDriverId();
  const { leagueService } = useServices();

  const { data: schedule, isLoading, error, retry } = useDataFetching({
    queryKey: ['leagueSchedule', leagueId],
    queryFn: () => leagueService.getLeagueSchedule(leagueId),
  });

  const registerMutation = useRegisterForRace();
  const withdrawMutation = useWithdrawFromRace();

  const races = useMemo(() => {
    return schedule?.races ?? [];
  }, [schedule]);

  const handleRegister = async (race: LeagueScheduleRaceViewModel, e: React.MouseEvent) => {
    e.stopPropagation();

    const confirmed = window.confirm(`Register for ${race.track ?? race.name}?`);

    if (!confirmed) return;

    try {
      await registerMutation.mutateAsync({ raceId: race.id, leagueId, driverId: currentDriverId });
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Failed to register');
    }
  };

  const handleWithdraw = async (race: LeagueScheduleRaceViewModel, e: React.MouseEvent) => {
    e.stopPropagation();

    const confirmed = window.confirm('Withdraw from this race?');

    if (!confirmed) return;

    try {
      await withdrawMutation.mutateAsync({ raceId: race.id, driverId: currentDriverId });
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Failed to withdraw');
    }
  };

  const upcomingRaces = races.filter((race) => race.isUpcoming);
  const pastRaces = races.filter((race) => race.isPast);

  const getDisplayRaces = () => {
    switch (filter) {
      case 'upcoming':
        return upcomingRaces;
      case 'past':
        return [...pastRaces].reverse();
      case 'all':
        return [...upcomingRaces, ...[...pastRaces].reverse()];
      default:
        return races;
    }
  };

  const displayRaces = getDisplayRaces();

  return (
    <StateContainer
      data={schedule}
      isLoading={isLoading}
      error={error}
      retry={retry}
      config={{
        loading: { variant: 'skeleton', message: 'Loading schedule...' },
        error: { variant: 'inline' },
        empty: {
          icon: Calendar,
          title: 'No races scheduled',
          description: 'This league has no races yet',
        }
      }}
    >
      {(scheduleData) => {
        const races = scheduleData?.races ?? [];
        const upcomingRaces = races.filter((race) => race.isUpcoming);
        const pastRaces = races.filter((race) => race.isPast);
        
        const getDisplayRaces = () => {
          switch (filter) {
            case 'upcoming':
              return upcomingRaces;
            case 'past':
              return [...pastRaces].reverse();
            case 'all':
              return [...upcomingRaces, ...[...pastRaces].reverse()];
            default:
              return races;
          }
        };

        const displayRaces = getDisplayRaces();

        return (
          <div>
            {/* Filter Controls */}
            <div className="mb-4 flex items-center justify-between">
              <p className="text-sm text-gray-400">
                {displayRaces.length} {displayRaces.length === 1 ? 'race' : 'races'}
              </p>
              <div className="flex gap-2">
                <button
                  onClick={() => setFilter('upcoming')}
                  className={`px-3 py-1 text-sm font-medium rounded transition-colors ${
                    filter === 'upcoming'
                      ? 'bg-primary-blue text-white'
                      : 'bg-iron-gray text-gray-400 hover:text-white'
                  }`}
                >
                  Upcoming ({upcomingRaces.length})
                </button>
                <button
                  onClick={() => setFilter('past')}
                  className={`px-3 py-1 text-sm font-medium rounded transition-colors ${
                    filter === 'past'
                      ? 'bg-primary-blue text-white'
                      : 'bg-iron-gray text-gray-400 hover:text-white'
                  }`}
                >
                  Past ({pastRaces.length})
                </button>
                <button
                  onClick={() => setFilter('all')}
                  className={`px-3 py-1 text-sm font-medium rounded transition-colors ${
                    filter === 'all'
                      ? 'bg-primary-blue text-white'
                      : 'bg-iron-gray text-gray-400 hover:text-white'
                  }`}
                >
                  All ({races.length})
                </button>
              </div>
            </div>

            {/* Race List */}
            {displayRaces.length === 0 ? (
              <div className="text-center py-8 text-gray-400">
                <p className="mb-2">No {filter} races</p>
                {filter === 'upcoming' && (
                  <p className="text-sm text-gray-500">Schedule your first race to get started</p>
                )}
              </div>
            ) : (
              <div className="space-y-3">
                {displayRaces.map((race) => {
                  const isPast = race.isPast;
                  const isUpcoming = race.isUpcoming;
                  const isRegistered = Boolean(race.isRegistered);
                  const trackLabel = race.track ?? race.name;
                  const carLabel = race.car ?? '—';
                  const sessionTypeLabel = (race.sessionType ?? 'race').toLowerCase();
                  const isProcessing =
                    registerMutation.isPending || withdrawMutation.isPending;

                  return (
                    <div
                      key={race.id}
                      className={`p-4 rounded-lg border transition-all duration-200 cursor-pointer hover:scale-[1.02] ${
                        isPast
                          ? 'bg-iron-gray/50 border-charcoal-outline/50 opacity-75'
                          : 'bg-deep-graphite border-charcoal-outline hover:border-primary-blue'
                      }`}
                      onClick={() => router.push(`/races/${race.id}`)}
                    >
                      <div className="flex items-center justify-between gap-4">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1 flex-wrap">
                            <h3 className="text-white font-medium">{trackLabel}</h3>
                            {isUpcoming && !isRegistered && (
                              <span className="px-2 py-0.5 text-xs font-medium bg-primary-blue/10 text-primary-blue rounded border border-primary-blue/30">
                                Upcoming
                              </span>
                            )}
                            {isUpcoming && isRegistered && (
                              <span className="px-2 py-0.5 text-xs font-medium bg-green-500/10 text-green-400 rounded border border-green-500/30">
                                ✓ Registered
                              </span>
                            )}
                            {isPast && (
                              <span className="px-2 py-0.5 text-xs font-medium bg-gray-700/50 text-gray-400 rounded border border-gray-600/50">
                                Completed
                              </span>
                            )}
                          </div>
                          <p className="text-sm text-gray-400">{carLabel}</p>
                          <div className="flex items-center gap-3 mt-2">
                            <p className="text-xs text-gray-500 uppercase">{sessionTypeLabel}</p>
                          </div>
                        </div>
                        
                        <div className="flex items-center gap-3">
                          <div className="text-right">
                            <p className="text-white font-medium">
                              {race.scheduledAt.toLocaleDateString('en-US', {
                                month: 'short',
                                day: 'numeric',
                                year: 'numeric',
                              })}
                            </p>
                            <p className="text-sm text-gray-400">
                              {race.scheduledAt.toLocaleTimeString([], {
                                hour: '2-digit',
                                minute: '2-digit',
                              })}
                            </p>
                            {isPast && race.status === 'completed' && (
                              <p className="text-xs text-primary-blue mt-1">View Results →</p>
                            )}
                          </div>

                          {/* Registration Actions */}
                          {isUpcoming && (
                            <div onClick={(e) => e.stopPropagation()}>
                              {!isRegistered ? (
                                <button
                                  onClick={(e) => handleRegister(race, e)}
                                  disabled={isProcessing}
                                  className="px-3 py-1.5 text-sm font-medium bg-primary-blue hover:bg-primary-blue/80 text-white rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap"
                                >
                                  {registerMutation.isPending ? 'Registering...' : 'Register'}
                                </button>
                              ) : (
                                <button
                                  onClick={(e) => handleWithdraw(race, e)}
                                  disabled={isProcessing}
                                  className="px-3 py-1.5 text-sm font-medium bg-iron-gray hover:bg-charcoal-outline text-gray-300 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap"
                                >
                                  {withdrawMutation.isPending ? 'Withdrawing...' : 'Withdraw'}
                                </button>
                              )}
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        );
      }}
    </StateContainer>
  );
 }
