'use client';

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

interface DriversPageClientProps {
  viewData: DriversViewData | null;
  error?: string;
  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 => 
      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}
    />
  );
}
