import React, { useState, useEffect, useRef } from 'react';
import { Upload, Trash2, Play, Pause, Music } from 'lucide-react';
import { bgmApi } from '../api/client';

export default function BGMPage() {
  const [bgmList, setBgmList] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [playingId, setPlayingId] = useState(null);
  const audioRef = useRef(null);
  const fileInputRef = useRef(null);

  const fetchBgmList = async () => {
    setIsLoading(true);
    try {
      const res = await bgmApi.list();
      setBgmList(res.data);
    } catch (err) {
      console.error('Failed to fetch BGM list:', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchBgmList();
  }, []);

  const handleUpload = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    try {
      await bgmApi.upload(file);
      await fetchBgmList();
    } catch (err) {
      console.error('Failed to upload BGM:', err);
      alert('업로드 실패: ' + (err.response?.data?.detail || err.message));
    } finally {
      setUploading(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  const handleDelete = async (bgmId) => {
    if (!confirm('이 BGM을 삭제하시겠습니까?')) return;

    try {
      await bgmApi.delete(bgmId);
      setBgmList(bgmList.filter((b) => b.id !== bgmId));
      if (playingId === bgmId) {
        setPlayingId(null);
        if (audioRef.current) {
          audioRef.current.pause();
        }
      }
    } catch (err) {
      console.error('Failed to delete BGM:', err);
    }
  };

  const handlePlay = (bgm) => {
    if (playingId === bgm.id) {
      // Stop playing
      if (audioRef.current) {
        audioRef.current.pause();
      }
      setPlayingId(null);
    } else {
      // Start playing
      if (audioRef.current) {
        audioRef.current.src = bgm.path;
        audioRef.current.play();
      }
      setPlayingId(bgm.id);
    }
  };

  const formatDuration = (seconds) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${String(secs).padStart(2, '0')}`;
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-2xl font-bold">BGM 관리</h2>
        <label className="btn-primary flex items-center gap-2 cursor-pointer">
          <Upload size={18} />
          {uploading ? '업로드 중...' : 'BGM 업로드'}
          <input
            ref={fileInputRef}
            type="file"
            accept=".mp3,.wav,.m4a,.ogg"
            onChange={handleUpload}
            className="hidden"
            disabled={uploading}
          />
        </label>
      </div>

      <audio
        ref={audioRef}
        onEnded={() => setPlayingId(null)}
        className="hidden"
      />

      {isLoading ? (
        <div className="card text-center py-12 text-gray-500">
          로딩 중...
        </div>
      ) : bgmList.length === 0 ? (
        <div className="card text-center py-12 text-gray-500">
          <Music size={48} className="mx-auto mb-4 opacity-50" />
          <p>등록된 BGM이 없습니다.</p>
          <p className="text-sm mt-2">MP3, WAV 파일을 업로드하세요.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {bgmList.map((bgm) => (
            <div
              key={bgm.id}
              className="card flex items-center gap-4 hover:border-gray-700 transition-colors"
            >
              <button
                onClick={() => handlePlay(bgm)}
                className={`w-12 h-12 rounded-full flex items-center justify-center transition-colors ${
                  playingId === bgm.id
                    ? 'bg-red-600 text-white'
                    : 'bg-gray-800 text-gray-400 hover:text-white'
                }`}
              >
                {playingId === bgm.id ? (
                  <Pause size={20} />
                ) : (
                  <Play size={20} className="ml-1" />
                )}
              </button>

              <div className="flex-1 min-w-0">
                <h3 className="font-medium truncate">{bgm.name}</h3>
                <p className="text-sm text-gray-500">
                  {formatDuration(bgm.duration)}
                </p>
              </div>

              <button
                onClick={() => handleDelete(bgm.id)}
                className="p-2 text-gray-500 hover:text-red-500 transition-colors"
                title="삭제"
              >
                <Trash2 size={18} />
              </button>
            </div>
          ))}
        </div>
      )}

      <div className="card bg-gray-800/50">
        <h3 className="font-medium mb-2">지원 형식</h3>
        <p className="text-sm text-gray-400">
          MP3, WAV, M4A, OGG 형식의 오디오 파일을 업로드할 수 있습니다.
          저작권에 유의하여 사용하세요.
        </p>
      </div>
    </div>
  );
}
