import React, { useState, useEffect } from 'react'
import { AudioService, AudioFile } from '../services/audioService'
import AudioSearchBar from '../components/AudioSearchBar'
import AudioList from '../components/AudioList'
import AudioUpload from '../components/AudioUpload'
import AudioChartViewer from '../components/AudioChartViewer'

const AudioLibraryPage: React.FC = () => {
  const [audioFiles, setAudioFiles] = useState<AudioFile[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [showUpload, setShowUpload] = useState(false)
  const [showChart, setShowChart] = useState(false)
  const [selectedAudio, setSelectedAudio] = useState<AudioFile | null>(null)

  useEffect(() => {
    loadAudioFiles()
  }, [])

  const loadAudioFiles = async () => {
    try {
      setLoading(true)
      const response = await AudioService.getAllAudioFiles()
      if (response.status && response.data) {
        setAudioFiles(response.data)
      } else {
        console.error('Failed to load audio files:', response.msg)
      }
    } catch (error) {
      console.error('Failed to load audio files:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleDeleteAudio = async (audioId: string) => {
    console.log('handleDeleteAudio called with:', audioId)
    const isOk = confirm('确定要删除这个音频文件吗？')
    console.log('User confirmed deletion:', isOk)
    if (!isOk) {
      console.log('User cancelled deletion, returning early')
      return
    }

    try {
      console.log('Calling AudioService.deleteAudioFile...')
      const response = await AudioService.deleteAudioFile(audioId)
      console.log('Delete response:', response)
      
      if (response.status) {
        console.log('Delete successful, updating audio files list')
        setAudioFiles(audioFiles.filter(audio => audio.id !== audioId))
      } else {
        console.error('删除失败:', response.msg || '未知错误')
        alert('删除失败: ' + (response.msg || '未知错误'))
      }
    } catch (error) {
      console.error('Failed to delete audio file:', error)
      alert('删除失败: ' + (error instanceof Error ? error.message : '未知错误'))
    }
  }

  const handleShowChart = (audio: AudioFile) => {
    setSelectedAudio(audio)
    setShowChart(true)
  }

  const handleUploadComplete = () => {
    loadAudioFiles()
  }

  return (
    <div className="p-6">
      {/* 页面标题 */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">音频库</h1>
        <p className="text-gray-600 mt-2">管理音频文件，支持上传、批量处理、节奏分析和频率图生成</p>
      </div>

      {/* 搜索和操作栏 */}
      <AudioSearchBar
        searchTerm={searchTerm}
        onSearchChange={setSearchTerm}
        onUpload={() => setShowUpload(true)}
      />

      {/* 音频文件列表 */}
      <AudioList
        audioFiles={audioFiles}
        loading={loading}
        searchTerm={searchTerm}
        onDelete={handleDeleteAudio}
        onShowChart={handleShowChart}
        onUpload={() => setShowUpload(true)}
      />

      {/* 上传对话框 */}
      <AudioUpload
        isOpen={showUpload}
        onClose={() => setShowUpload(false)}
        onUploadComplete={handleUploadComplete}
      />

      {/* 频率图查看器 */}
      <AudioChartViewer
        isOpen={showChart}
        audio={selectedAudio}
        onClose={() => {
          setShowChart(false)
          setSelectedAudio(null)
        }}
      />
    </div>
  )
}

export default AudioLibraryPage
