import { graphql, useLazyLoadQuery } from "react-relay";
import { useParams } from "react-router-dom";
import type { TopArtistsQuery } from "./__generated__/TopArtistsQuery.graphql";
import Layout from "./Layout";
import { useDateRangeFilter } from "./useDateRangeFilter";
import ArtistItem from "./ArtistItem";

export default function TopArtists() {
  const { period } = useParams<{ period?: string }>();
  const queryVariables = useDateRangeFilter(period);

  const data = useLazyLoadQuery<TopArtistsQuery>(
    graphql`
      query TopArtistsQuery($where: FmTealAlphaFeedPlayWhereInput) {
        fmTealAlphaFeedPlaysAggregated(
          groupBy: [{ field: artists }]
          orderBy: { count: desc }
          limit: 50
          where: $where
        ) {
          artists
          count
        }
      }
    `,
    queryVariables,
    { fetchKey: period || "all", fetchPolicy: "store-or-network" }
  );

  const artists = data.fmTealAlphaFeedPlaysAggregated || [];
  const maxCount = artists.length > 0 ? artists[0].count : 0;

  return (
    <Layout>
      <div className="space-y-1">
        {artists.map((artist, index) => (
          <ArtistItem
            key={`${artist.artists}-${index}`}
            artists={artist.artists || "Unknown Artist"}
            count={artist.count}
            rank={index + 1}
            maxCount={maxCount}
          />
        ))}
      </div>
    </Layout>
  );
}
