'use client';

import React, { useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { DriverRankingsTemplate } from '@/templates/DriverRankingsTemplate';
import { routes } from '@/lib/routing/RouteConfig';
import type { DriverRankingsViewData } from '@/lib/view-data/DriverRankingsViewData';
import { ClientWrapperProps } from '@/lib/contracts/components/ComponentContracts';

export function DriverRankingsPageClient({ viewData }: ClientWrapperProps<DriverRankingsViewData>) {
  const router = useRouter();
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedSkill, setSelectedSkill] = useState<'all' | 'pro' | 'advanced' | 'intermediate' | 'beginner'>('all');
  const [selectedTeam, setSelectedTeam] = useState('all');
  const [sortBy, setSortBy] = useState<'rank' | 'rating' | 'wins' | 'podiums' | 'winRate'>('rank');
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

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

  const handleBackToLeaderboards = () => {
    router.push(routes.leaderboards.root);
  };

  const filteredAndSortedDrivers = useMemo(() => {
    let result = [...viewData.drivers];

    // Search
    if (searchQuery) {
      result = result.filter(driver => 
        driver.name.toLowerCase().includes(searchQuery.toLowerCase())
      );
    }

    // Skill Filter
    if (selectedSkill !== 'all') {
      result = result.filter(driver => driver.skillLevel.toLowerCase() === selectedSkill);
    }

    // Team Filter (Mocked logic since drivers don't have teamId yet)
    if (selectedTeam !== 'all') {
      // For now, just filter some drivers to show it works
      result = result.filter((_, index) => (index % 3).toString() === selectedTeam.replace('team-', ''));
    }

    // Sorting
    result.sort((a, b) => {
      switch (sortBy) {
        case 'rating': return b.rating - a.rating;
        case 'wins': return b.wins - a.wins;
        case 'podiums': return b.podiums - a.podiums;
        case 'winRate': return parseFloat(b.winRate) - parseFloat(a.winRate);
        case 'rank':
        default: return a.rank - b.rank;
      }
    });

    return result;
  }, [viewData.drivers, searchQuery, selectedSkill, selectedTeam, sortBy]);

  const paginatedDrivers = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filteredAndSortedDrivers.slice(startIndex, startIndex + itemsPerPage);
  }, [filteredAndSortedDrivers, currentPage]);

  const totalPages = Math.ceil(filteredAndSortedDrivers.length / itemsPerPage);

  return (
    <DriverRankingsTemplate
      viewData={{
        ...viewData,
        drivers: paginatedDrivers,
        searchQuery,
        selectedSkill,
        selectedTeam,
        sortBy,
        showFilters: false,
      }}
      searchQuery={searchQuery}
      onSearchChange={setSearchQuery}
      onSkillChange={setSelectedSkill}
      onTeamChange={setSelectedTeam}
      onSortChange={setSortBy}
      onPageChange={setCurrentPage}
      currentPage={currentPage}
      totalPages={totalPages}
      totalDrivers={filteredAndSortedDrivers.length}
      onDriverClick={handleDriverClick}
      onBackToLeaderboards={handleBackToLeaderboards}
    />
  );
}
