import React, { useEffect, useRef } from "react";
import { components } from "../../lib/gen";

// Use the Song type from gen.ts if available, otherwise fallback to local type
export type Song = components["schemas"]["GeneratedClipSchema"] & {
  source?: "trending" | "following" | "profile" | string;
};

interface SongFeedProps<SongType> {
  songs: SongType[];
  loading: boolean;
  error?: string | null;
  currentSong?: SongType | null;
  playSong: (song: SongType, startTime?: number) => void;
  emptyMessage?: string;
  scrollToNextOnEnd?: boolean;
  SongComponent: React.ForwardRefExoticComponent<any>;
}

function SongFeed<SongType>({
  songs,
  loading,
  error,
  currentSong,
  playSong,
  emptyMessage = "No songs found.",
  scrollToNextOnEnd = false,
  SongComponent,
}: SongFeedProps<SongType>) {
  const songRefs = useRef<(HTMLDivElement | null)[]>([]);

  // Optionally scroll to next song when current ends
  useEffect(() => {
    if (!scrollToNextOnEnd) return;
    if (!currentSong) return;
    const idx = songs.findIndex(
      (s) => (s as any).id === (currentSong as any).id
    );
    if (idx !== -1 && idx < songs.length - 1) {
      // Listen for audio end event elsewhere and call this externally if needed
      // This is just a placeholder for scroll logic
    }
  }, [currentSong, songs, scrollToNextOnEnd]);

  return (
    <div className="space-y-6">
      {loading && (
        <div className="flex items-center justify-center py-12">
          <div className="text-foreground/60">Loading songs...</div>
        </div>
      )}
      {error && !loading && (
        <div className="flex items-center justify-center py-12">
          <div className="text-red-500">{error}</div>
        </div>
      )}
      {!loading && !error && songs.length === 0 && (
        <div className="flex items-center justify-center py-12">
          <div className="text-foreground/60">{emptyMessage}</div>
        </div>
      )}
      {!loading &&
        !error &&
        songs.map((song, i) => (
          <SongComponent
            key={(song as any).id}
            song={song}
            ref={(el: HTMLDivElement | null) => {
              songRefs.current[i] = el;
            }}
            isCurrent={(currentSong as any)?.id === (song as any).id}
            playSong={playSong}
          />
        ))}
    </div>
  );
}

export default SongFeed;
