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

export default function ProfileTopArtists() {
  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<ProfileTopArtistsQuery>(
    graphql`
      query ProfileTopArtistsQuery($where: FmTealAlphaFeedPlayWhereInput) {
        fmTealAlphaFeedPlaysAggregated(
          groupBy: [{ field: artists }]
          orderBy: { count: desc }
          limit: 50
          where: $where
        ) {
          artists
          count
        }
      }
    `,
    queryVariables,
    { fetchKey: `${handle}-${period || "all"}`, fetchPolicy: "store-or-network" }
  );

  const processedArtists = useMemo(() => {
    const artistCounts: { [key: string]: number } = {};

    (data.fmTealAlphaFeedPlaysAggregated || []).forEach((row) => {
      if (!row.artists) return;

      let names: string[] = [];

      try {
        const parsed = typeof row.artists === 'string' ? JSON.parse(row.artists) : row.artists;

        if (Array.isArray(parsed)) {
          names = parsed.map((a: { artistName: string }) => a.artistName.trim());
        } else if (typeof parsed === 'string') {
          names = parsed.split(',').map(s => s.trim());
        }
      } catch (e) {
        if (typeof row.artists === 'string') {
          names = row.artists.split(',').map(s => s.trim());
        }
      }

      names.forEach(name => {
        if (name) {
          artistCounts[name] = (artistCounts[name] || 0) + row.count;
        }
      });
    });

    return Object.entries(artistCounts)
      .map(([name, count]) => ({ artists: name, count }))
      .sort((a, b) => b.count - a.count)
      .slice(0, 10);
  }, [data.fmTealAlphaFeedPlaysAggregated]);

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

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