'use client';

import { routes } from '@/lib/routing/RouteConfig';
import { DriversTemplate } from '@/templates/DriversTemplate';
import { EmptyTemplate, ErrorTemplate } from '@/templates/shared/StatusTemplates';
import { useRouter } from 'next/navigation';
import { useMemo, useState } from 'react';
import type { DriversViewData, DriverViewData } from '@/lib/view-data/DriversViewData';

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


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: DriverViewData) =>
      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 (
      <ErrorTemplate 
        viewData={{}} 
        message="Error loading drivers" 
        description="Please try again later" 
      />
    );
  }

  if (!viewData || viewData.drivers.length === 0) {
    if (empty) {
      return (
        <EmptyTemplate 
          viewData={{}} 
          title={empty.title} 
          description={empty.description} 
        />
      );
    }
    return null;
  }

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