'use client';

import { useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { RacesTemplate, type TimeFilter, type RaceStatusFilter } from '@/templates/RacesTemplate';
import type { RacesViewData } from '@/lib/view-data/RacesViewData';

interface RacesPageClientProps {
  viewData: RacesViewData;
}

export function RacesPageClient({ viewData }: RacesPageClientProps) {
  const router = useRouter();
  const [statusFilter, setStatusFilter] = useState<RaceStatusFilter>('all');
  const [leagueFilter, setLeagueFilter] = useState<string>('all');
  const [timeFilter, setTimeFilter] = useState<TimeFilter>('upcoming');
  const [showFilterModal, setShowFilterModal] = useState(false);

  const filteredRaces = useMemo(() => {
    return viewData.races.filter((race) => {
      if (statusFilter !== 'all' && race.status !== statusFilter) return false;
      if (leagueFilter !== 'all' && race.leagueId !== leagueFilter) return false;
      if (timeFilter === 'upcoming' && !race.isUpcoming) return false;
      if (timeFilter === 'live' && !race.isLive) return false;
      if (timeFilter === 'past' && !race.isPast) return false;
      return true;
    });
  }, [viewData.races, statusFilter, leagueFilter, timeFilter]);

  const racesByDate = useMemo(() => {
    const grouped = new Map<string, typeof filteredRaces[0][]>();
    filteredRaces.forEach((race) => {
      const dateKey = race.scheduledAt.split('T')[0]!;
      if (!grouped.has(dateKey)) {
        grouped.set(dateKey, []);
      }
      grouped.get(dateKey)!.push(race);
    });
    return Array.from(grouped.entries()).map(([dateKey, dayRaces]) => ({
      dateKey,
      dateLabel: dayRaces[0]?.scheduledAtLabel || '',
      races: dayRaces,
    }));
  }, [filteredRaces]);

  return (
    <RacesTemplate
      viewData={{
        ...viewData,
        races: filteredRaces,
        racesByDate,
      }}
      statusFilter={statusFilter}
      setStatusFilter={setStatusFilter}
      leagueFilter={leagueFilter}
      setLeagueFilter={setLeagueFilter}
      timeFilter={timeFilter}
      setTimeFilter={setTimeFilter}
      showFilterModal={showFilterModal}
      setShowFilterModal={setShowFilterModal}
      onRaceClick={(id) => router.push(`/races/${id}`)}
      onLeagueClick={(id) => router.push(`/leagues/${id}`)}
      onWithdraw={(id) => console.log('Withdraw', id)}
      onCancel={(id) => console.log('Cancel', id)}
    />
  );
}
