import React, { useEffect, useRef } from "react";
import SongRow, { PlayState } from "./SongRow";
import { PlaylistItem } from "../api/player";

interface SongTableProps {
  songs: PlaylistItem[];
  isPlaying: boolean;
  onDelete: (index: number) => void;
  onSkipTo: (index: number) => void;
}

const SongTable: React.FC<SongTableProps> = ({ songs, isPlaying, onDelete, onSkipTo }) => {
  const nowPlayingIndex = songs.findIndex(song => song.playing ?? false);
  const songTableRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const songTable = songTableRef.current;
    if (songTable) {
      songTable.scrollTop = nowPlayingIndex * 100;
    }
  }, [nowPlayingIndex]);

  return (
    <div className="flex flex-col w-full h-full overflow-y-auto border-y" ref={songTableRef}>
      {songs.map((song, index) => (
        <SongRow 
          key={index} 
          song={song} 
          playState={
            (song.playing ?? false) ? (isPlaying ? PlayState.Playing : PlayState.Paused)
            : PlayState.NotPlaying
          }
          onDelete={() => onDelete(index)} 
          onPlay={() => onSkipTo(index)} 
        />
      ))}
    </div>
  );
};

export default SongTable;