'use client';

import type { DriversViewData } from '@/lib/types/view-data/DriversViewData';
import { DriversTemplate } from '@/templates/DriversTemplate';
import { Container } from '@/ui/Container';
import { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { useRouter } from 'next/navigation';
import { useMemo, useState } from 'react';

import { routes } from '@/lib/routing/RouteConfig';

interface DriversPageClientProps {
  viewData: DriversViewData | null;
  error?: string;
  empty?: {
    title: string;
    description: string;
  };
}

/**
 * DriversPageClient
 *
 * Client component that:
 * 1. Manages search state
 * 2. Filters drivers based on search
 * 3. Passes ViewData to Template
 */
export function DriversPageClient({ viewData, error, empty }: DriversPageClientProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const router = useRouter();

  const filteredDrivers = useMemo(() => {
    if (!viewData) return [];
    if (!searchQuery) return viewData.drivers;
    
    const query = searchQuery.toLowerCase();
    return viewData.drivers.filter(driver => 
      driver.name.toLowerCase().includes(query) || 
      driver.nationality.toLowerCase().includes(query)
    );
  }, [viewData, searchQuery]);

  const handleDriverClick = (id: string) => {
    router.push(routes.driver.detail(id));
  };

  const handleViewLeaderboard = () => {
    router.push(routes.leaderboards.drivers);
  };

  // Handle error/empty states
  if (error) {
    return (
      <Container size="lg" py={12}>
        <Stack align="center" gap={4}>
          <Text color="text-red-400">Error loading drivers</Text>
          <Text color="text-gray-400">Please try again later</Text>
        </Stack>
      </Container>
    );
  }

  if (!viewData || viewData.drivers.length === 0) {
    if (empty) {
      return (
        <Container size="lg" py={12}>
          <Stack align="center" gap={2}>
            <Text size="xl" weight="semibold" color="text-white">{empty.title}</Text>
            <Text color="text-gray-400">{empty.description}</Text>
          </Stack>
        </Container>
      );
    }
    return null;
  }

  return (
    <DriversTemplate 
      viewData={viewData}
      searchQuery={searchQuery}
      onSearchChange={setSearchQuery}
      filteredDrivers={filteredDrivers}
      onDriverClick={handleDriverClick}
      onViewLeaderboard={handleViewLeaderboard}
    />
  );
}