import { PageWrapper } from '@/components/shared/state/PageWrapper';
import DriverRankingsTemplate from '@/templates/DriverRankingsTemplate';
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
import { DRIVER_SERVICE_TOKEN } from '@/lib/di/tokens';
import { DriverService } from '@/lib/services/drivers/DriverService';
import { Users } from 'lucide-react';
import { redirect , useRouter } from 'next/navigation';
import type { DriverLeaderboardViewModel } from '@/lib/view-models/DriverLeaderboardViewModel';
import { useState } from 'react';

// ============================================================================
// TYPES
// ============================================================================

type SkillLevel = 'pro' | 'advanced' | 'intermediate' | 'beginner';
type SortBy = 'rank' | 'rating' | 'wins' | 'podiums' | 'winRate';

// ============================================================================
// WRAPPER COMPONENT (Client-side state management)
// ============================================================================

function DriverRankingsPageWrapper({ data }: { data: DriverLeaderboardViewModel | null }) {
  const router = useRouter();
  
  // Client-side state for filtering and sorting
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedSkill, setSelectedSkill] = useState<'all' | SkillLevel>('all');
  const [sortBy, setSortBy] = useState<SortBy>('rank');
  const [showFilters, setShowFilters] = useState(false);

  if (!data || !data.drivers) {
    return null;
  }

  const handleDriverClick = (driverId: string) => {
    if (driverId.startsWith('demo-')) return;
    router.push(`/drivers/${driverId}`);
  };

  const handleBackToLeaderboards = () => {
    router.push('/leaderboards');
  };

  return (
    <DriverRankingsTemplate
      drivers={data.drivers}
      searchQuery={searchQuery}
      selectedSkill={selectedSkill}
      sortBy={sortBy}
      showFilters={showFilters}
      onSearchChange={setSearchQuery}
      onSkillChange={setSelectedSkill}
      onSortChange={setSortBy}
      onToggleFilters={() => setShowFilters(!showFilters)}
      onDriverClick={handleDriverClick}
      onBackToLeaderboards={handleBackToLeaderboards}
    />
  );
}

// ============================================================================
// MAIN PAGE COMPONENT
// ============================================================================

export default async function DriverLeaderboardPage() {
  // Fetch data using PageDataFetcher
  const driverData = await PageDataFetcher.fetch<DriverService, 'getDriverLeaderboard'>(
    DRIVER_SERVICE_TOKEN,
    'getDriverLeaderboard'
  );

  // Prepare data for template
  const data: DriverLeaderboardViewModel | null = driverData as DriverLeaderboardViewModel | null;

  const hasData = (driverData as any)?.drivers?.length > 0;

  // Handle loading state (should be fast since we're using async/await)
  const isLoading = false;
  const error = null;
  const retry = async () => {
    // In server components, we can't retry without a reload
    redirect('/leaderboards/drivers');
  };

  return (
    <PageWrapper
      data={hasData ? data : null}
      isLoading={isLoading}
      error={error}
      retry={retry}
      Template={DriverRankingsPageWrapper}
      loading={{ variant: 'full-screen', message: 'Loading driver rankings...' }}
      errorConfig={{ variant: 'full-screen' }}
      empty={{
        icon: Users,
        title: 'No drivers found',
        description: 'There are no drivers in the system yet.',
      }}
    />
  );
}