'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: unknown }) {
  const [searchQuery, setSearchQuery] = useState('');
  const [tierFilter] = useState<TierFilter>('all');
  const [availabilityFilter] = useState<AvailabilityFilter>('all');
  const [sortBy] = useState<SortOption>('rating');

  const filteredLeagues = useMemo(() => {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const d = data as any;
    if (!d?.leagues) return [];
    return d.leagues
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      .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;
      })
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      .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, searchQuery, tierFilter, availabilityFilter, sortBy]);

  return (
    <SponsorLeaguesTemplate
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      viewData={data as any}
      filteredLeagues={filteredLeagues}
      searchQuery={searchQuery}
      setSearchQuery={setSearchQuery}
    />
  );
}
