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

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

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

  const albums = [...(data.fmTealAlphaFeedPlaysAggregated || [])];

  // Deduplicate by release name, keeping the one with highest count
  // Prefer entries with artist data
  const seenNames = new Set<string>();
  const dedupedAlbums = albums
    .sort((a, b) => {
      // First sort by count (already sorted from query)
      if (b.count !== a.count) return b.count - a.count;
      // Then prefer entries with artists data
      if (a.artists && !b.artists) return -1;
      if (!a.artists && b.artists) return 1;
      return 0;
    })
    .filter((album) => {
      const name = album.releaseName || "Unknown Album";
      if (seenNames.has(name)) {
        return false;
      }
      seenNames.add(name);
      return true;
    })
    .slice(0, 50);

  const maxCount = dedupedAlbums.length > 0 ? dedupedAlbums[0].count : 0;

  return (
    <Layout>
      <div className="space-y-1">
        {dedupedAlbums.map((album, index) => (
          <AlbumItem
            key={album.releaseMbId || index}
            releaseName={album.releaseName || "Unknown Album"}
            releaseMbId={album.releaseMbId}
            artists={album.artists}
            count={album.count}
            rank={index + 1}
            maxCount={maxCount}
          />
        ))}
      </div>
    </Layout>
  );
}
