'use client';

import React, { useState, useMemo } from 'react';
import { SponsorLeaguesTemplate, type SortOption, type TierFilter, type AvailabilityFilter } from '@/templates/SponsorLeaguesTemplate';

export default function SponsorLeaguesPageClient({ data }: { data: any }) {
  const [searchQuery, setSearchQuery] = useState('');
  const [tierFilter, setTierFilter] = useState<TierFilter>('all');
  const [availabilityFilter, setAvailabilityFilter] = useState<AvailabilityFilter>('all');
  const [sortBy, setSortBy] = useState<SortOption>('rating');

  const filteredLeagues = useMemo(() => {
    if (!data?.leagues) return [];
    return data.leagues
      .filter((league: any) => {
        if (searchQuery && !league.name.toLowerCase().includes(searchQuery.toLowerCase())) {
          return false;
        }
        if (tierFilter !== 'all' && league.tier !== tierFilter) {
          return false;
        }
        if (availabilityFilter === 'main' && !league.mainSponsorSlot.available) {
          return false;
        }
        if (availabilityFilter === 'secondary' && league.secondarySlots.available === 0) {
          return false;
        }
        return true;
      })
      .sort((a: any, b: any) => {
        switch (sortBy) {
          case 'rating': return b.rating - a.rating;
          case 'drivers': return b.drivers - a.drivers;
          case 'price': return a.mainSponsorSlot.price - b.mainSponsorSlot.price;
          case 'views': return b.avgViewsPerRace - a.avgViewsPerRace;
          default: return 0;
        }
      });
  }, [data?.leagues, searchQuery, tierFilter, availabilityFilter, sortBy]);

  return (
    <SponsorLeaguesTemplate
      viewData={data}
      filteredLeagues={filteredLeagues}
      searchQuery={searchQuery}
      setSearchQuery={setSearchQuery}
      tierFilter={tierFilter}
      setTierFilter={setTierFilter}
      availabilityFilter={availabilityFilter}
      setAvailabilityFilter={setAvailabilityFilter}
      sortBy={sortBy}
      setSortBy={setSortBy}
    />
  );
}
