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

export default function ProfileTopAlbums() {
  const { handle, period } = useParams<{ handle: string; period?: string }>();
  const dateRangeVariables = useDateRangeFilter(period);

  const queryVariables = useMemo(() => {
    return {
      where: {
        ...dateRangeVariables.where,
        actorHandle: { eq: handle },
      },
    };
  }, [handle, dateRangeVariables]);

  const data = useLazyLoadQuery<ProfileTopAlbumsQuery>(
    graphql`
      query ProfileTopAlbumsQuery($where: FmTealAlphaFeedPlayWhereInput) {
        fmTealAlphaFeedPlaysAggregated(
          groupBy: [{ field: releaseMbId }, { field: releaseName }, { field: artists }]
          orderBy: { count: desc }
          limit: 50
          where: $where
        ) {
          releaseMbId
          releaseName
          artists
          count
        }
      }
    `,
    queryVariables,
    { fetchKey: `${handle}-${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, 10);

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

  return (
    <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>
  );
}
