"use client";

import { useEffect, useState } from "react";
import { useApiClient } from "../lib/apiClient";
import { useAudio } from "./components/AudioContext";
import LyricsPanel from "./components/LyricsPanel";
import Playbar from "./components/Playbar";
import SongFeed from "./components/SongFeed";
import SongCard from "./SongCard";

// Helper function to randomly intersperse two arrays
function intersperseArrays<T>(array1: T[], array2: T[]): T[] {
  const result: T[] = [];
  const combined = [...array1, ...array2];

  // Shuffle the combined array using Fisher-Yates algorithm
  for (let i = combined.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [combined[i], combined[j]] = [combined[j], combined[i]];
  }

  return combined;
}

// Helper function to limit songs per creator
function limitSongsPerCreator(songs: any[], limit: number): any[] {
  const creatorCounts = new Map<string, number>();
  return songs.filter((song) => {
    const creatorId = song.user_id;
    const currentCount = creatorCounts.get(creatorId) || 0;

    if (currentCount < limit) {
      creatorCounts.set(creatorId, currentCount + 1);
      return true;
    }
    return false;
  });
}

export default function Explore() {
  const [songs, setSongs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const apiClient = useApiClient();
  const { playSong, currentSong } = useAudio();

  useEffect(() => {
    const fetchSongs = async () => {
      try {
        setLoading(true);

        // Fetch trending songs
        const trendingResponse = await apiClient.POST("/api/discover/", {
          body: {
            start_index: 0,
            page_size: 1,
            section_name: "trending_songs",
            section_content: null,
            secondary_section_content: null,
            page: 1,
            section_size: 20,
            disable_shuffle: false,
          },
        });

        // Fetch for you songs
        const forYouResponse = await apiClient.POST("/api/discover/", {
          body: {
            start_index: 0,
            page_size: 1,
            section_name: "new_songs_for_you",
            section_content: null,
            secondary_section_content: null,
            page: 1,
            section_size: null,
            disable_shuffle: false,
          },
        });

        // Fetch following feed songs
        const followingResponse = await apiClient.POST(
          "/api/social/following-feed/",
          {
            body: {
              start_feed_timestamp: null,
              page_size: 20,
              ranking_method: "chronological",
              result_type: "published_songs",
            },
          }
        );

        // Fetch Best of 4.5 playlist songs
        const bestOf45Response = await apiClient.GET(
          "/api/playlist/{playlist_id}/",
          {
            params: {
              path: { playlist_id: "480b0308-492b-4649-9a59-1d7c6782aa04" },
              query: { page: 1 },
            },
          }
        );

        const trendingSongs = (
          trendingResponse.data?.sections?.[0]?.items || []
        ).map((song: any) => ({
          ...song,
          source: "trending" as const,
        }));

        const forYouSongs = (
          forYouResponse.data?.sections?.[0]?.items || []
        ).map((song: any) => ({
          ...song,
          source: "For You" as const,
        }));

        const allFollowingSongs =
          followingResponse.data?.items
            ?.map((item: any) => item.clip_schema)
            .filter(Boolean) || [];

        // Limit to 2 songs per creator
        const followingSongsLimited = limitSongsPerCreator(
          allFollowingSongs,
          2
        ).map((song: any) => ({
          ...song,
          source: "following" as const,
        }));

        // Process Best of 4.5 playlist songs
        const bestOf45Songs = (
          bestOf45Response.data?.playlist_clips || []
        )
          .map((item: any) => item.clip)
          .filter(Boolean)
          .map((song: any) => ({
            ...song,
            source: "Best of 4.5" as const,
          }));

        // Randomly intersperse all four arrays of songs
        const interspersedSongs = intersperseArrays(
          intersperseArrays(
            intersperseArrays(trendingSongs, followingSongsLimited),
            forYouSongs
          ),
          bestOf45Songs
        );

        // Deduplicate songs by ID
        const uniqueSongs = interspersedSongs.filter(
          (song, index, self) =>
            index === self.findIndex((s) => s.id === song.id)
        );

        if (uniqueSongs.length > 0) {
          setSongs(uniqueSongs);
        } else {
          setError("No songs found");
        }
      } catch (err) {
        console.error("Error fetching songs:", err);
        setError("Failed to load songs");
      } finally {
        setLoading(false);
      }
    };

    fetchSongs();
  }, [apiClient]);

  return (
    <>
      <div className="min-h-screen bg-gradient-to-b from-background to-background/95">
        {/* Feed */}
        <div className="max-w-2xl pl-8 pr-4 py-6 pb-32">
          <SongFeed
            songs={songs}
            loading={loading}
            error={error}
            currentSong={currentSong}
            playSong={playSong}
            SongComponent={SongCard}
          />
        </div>
      </div>

      {/* Floating Lyrics Panel */}
      <LyricsPanel />

      <Playbar />
    </>
  );
}