'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { DriversTemplate } from '@/templates/DriversTemplate';
import { DriverLeaderboardViewModel } from '@/lib/view-models/DriverLeaderboardViewModel';
import type { DriversLeaderboardDTO } from '@/lib/types/generated/DriversLeaderboardDTO';
import type { DriverLeaderboardItemDTO } from '@/lib/types/generated/DriverLeaderboardItemDTO';

interface DriversPageClientProps {
  pageDto: DriversLeaderboardDTO | null;
  error?: string;
  empty?: {
    title: string;
    description: string;
  };
}

/**
 * DriversPageClient
 * 
 * Client component that:
 * 1. Handles state (search, filter, sort)
 * 2. Calls ViewModel to get computed display data
 * 3. Transforms ViewModel to Template-compatible format
 * 4. Passes data to Template
 */
export function DriversPageClient({ pageDto, error, empty }: DriversPageClientProps) {
  const router = useRouter();
  
  // Client state
  const [searchQuery, setSearchQuery] = useState('');

  // Event handlers
  const onSearchChange = (query: string) => setSearchQuery(query);
  const onDriverClick = (id: string) => router.push(`/drivers/${id}`);
  const onBackToLeaderboards = () => router.push('/leaderboards');

  // Handle error/empty states
  if (error) {
    return (
      <div className="max-w-7xl mx-auto px-4 py-12 text-center">
        <div className="text-red-400 mb-4">Error loading drivers</div>
        <p className="text-gray-400">Please try again later</p>
      </div>
    );
  }

  if (!pageDto || pageDto.drivers.length === 0) {
    if (empty) {
      return (
        <div className="max-w-7xl mx-auto px-4 py-12 text-center">
          <h2 className="text-xl font-semibold text-white mb-2">{empty.title}</h2>
          <p className="text-gray-400">{empty.description}</p>
        </div>
      );
    }
    return null;
  }

  // Transform DTO to ViewModel
  const dtoForViewModel: { drivers: DriverLeaderboardItemDTO[] } = {
    drivers: pageDto.drivers.map(driver => ({
      ...driver,
      avatarUrl: driver.avatarUrl || '',
    })),
  };
  const viewModel = new DriverLeaderboardViewModel(dtoForViewModel);

  // Filter drivers based on search
  let filteredDrivers = viewModel.drivers.filter(driver => {
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      const matchesSearch = 
        driver.name.toLowerCase().includes(query) ||
        driver.nationality.toLowerCase().includes(query);
      if (!matchesSearch) return false;
    }
    return true;
  });

  // Pass to template
  return <DriversTemplate data={viewModel} />;
}