import classNames from 'classnames';
import React, { useState, useRef, useEffect } from 'react';
import { FaPlay, FaVolumeUp, FaVolumeOff } from 'react-icons/fa';
import { PlaylistItem } from '../api/player';

export enum PlayState {
  NotPlaying, 
  Playing,
  Paused,
}

export interface SongRowProps {
  song: PlaylistItem;
  playState: PlayState;
  onDelete: () => void;
  onPlay: () => void;
}

const SongRow: React.FC<SongRowProps> = ({ song, playState, onDelete, onPlay }) => {
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const buttonRef = useRef<HTMLButtonElement>(null);
  
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (buttonRef.current && !buttonRef.current.contains(event.target as Node)) {
        setShowDeleteConfirm(false);
      }
    };
    
    if (showDeleteConfirm) {
      document.addEventListener('click', handleClickOutside);
    }
    
    return () => {
      document.removeEventListener('click', handleClickOutside);
    };
  }, [showDeleteConfirm]);
  
  return (
    <div className={classNames("flex flex-row w-full h-[100px] px-2 py-5 items-center border-b gap-2 transition-colors", {
      "bg-black/10": (playState === PlayState.Playing || playState === PlayState.Paused),
      "bg-black/30": playState === PlayState.NotPlaying,
    })}>
      <div className="flex flex-row gap-2">
        <button 
          className="text-white/40 hover:text-white transition-colors px-3 py-1 rounded"
          onClick={onPlay}
        >
          {
            playState === PlayState.Playing ? <FaVolumeUp size={12} /> 
            : playState === PlayState.Paused ? <FaVolumeOff size={12} /> 
            : <FaPlay size={12} />
          }
        </button>
      </div>
      
      <div className="flex-grow min-w-0">
        { 
          song.title ? (
            <div>
              <div className="text-white text-md truncate text-bold">
                {song.title}
              </div>
              <div className="text-white/80 text-xs truncate">
                {song.filename}
              </div>
            </div>
          ) : (
          <div className="text-white text-md truncate text-bold">
            {song.filename}
          </div>
          )
        }
      </div>
      
      <div className="flex flex-row gap-2">
        <button
          ref={buttonRef}
          className="text-red-500 px-3 py-1 bg-red-500/10 rounded"
          onClick={(e) => {
            e.stopPropagation();
            if (showDeleteConfirm) {
              setShowDeleteConfirm(false);
              onDelete();
            } else {
              setShowDeleteConfirm(true);
            }
          }}
        >
          {showDeleteConfirm ? 'Delete' : '×'}
        </button>
      </div>
    </div>
  );
};

export default SongRow;
