import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import AudioPlayer from 'react-h5-audio-player';
import 'react-h5-audio-player/lib/styles.css';
import { path } from 'path-browserify';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faMusic, faFileAudio } from '@fortawesome/free-solid-svg-icons';
import './style.css';

/**
 * 音频播放器组件
 * @param {Object} props 组件属性
 * @param {string} props.audioPath 音频文件路径
 * @param {string} props.label 显示的标签
 * @param {function} props.onPlay 播放事件回调
 * @param {function} props.onPause 暂停事件回调
 */
const AudioPlayerComponent = ({ audioPath, label, onPlay, onPause }) => {
  const [audioFile, setAudioFile] = useState(null);
  const [audioInfo, setAudioInfo] = useState({
    fileName: '',
    fileSize: ''
  });
  
  useEffect(() => {
    if (audioPath) {
      // 设置文件路径
      setAudioFile(audioPath);
      
      // 提取文件名
      const fileName = path.basename(audioPath);
      
      // 获取文件大小信息
      try {
        // 通过Electron的fs模块获取文件信息
        window.electron.ipcRenderer.invoke('get-file-stats', audioPath)
          .then(stats => {
            if (stats) {
              setAudioInfo({
                fileName,
                fileSize: formatFileSize(stats.size)
              });
            }
          })
          .catch(err => {
            console.error('获取音频文件信息时出错:', err);
          });
      } catch (error) {
        console.error('处理音频文件路径时出错:', error);
      }
    }
  }, [audioPath]);
  
  /**
   * 格式化文件大小
   * @param {number} bytes 文件大小（字节）
   * @returns {string} 格式化后的文件大小
   */
  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 字节';
    
    const sizes = ['字节', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return parseFloat((bytes / Math.pow(1024, i)).toFixed(2)) + ' ' + sizes[i];
  };
  
  if (!audioFile) {
    return (
      <div className="audio-player-placeholder">
        <FontAwesomeIcon icon={faMusic} size="lg" />
        <span>未找到音频文件</span>
      </div>
    );
  }
  
  return (
    <div className="audio-player-container">
      <div className="audio-info">
        <FontAwesomeIcon icon={faFileAudio} size="lg" />
        <div className="audio-details">
          {label && <div className="audio-label">{label}</div>}
          <div className="audio-filename">{audioInfo.fileName}</div>
          <div className="audio-filesize">{audioInfo.fileSize}</div>
        </div>
      </div>
      
      <div className="audio-player-wrapper">
        <AudioPlayer
          src={`file://${audioFile}`}
          showJumpControls={true}
          showSkipControls={false}
          layout="horizontal"
          customAdditionalControls={[]}
          onPlay={onPlay}
          onPause={onPause}
          autoPlayAfterSrcChange={false}
        />
      </div>
    </div>
  );
};

AudioPlayerComponent.propTypes = {
  audioPath: PropTypes.string,
  label: PropTypes.string,
  onPlay: PropTypes.func,
  onPause: PropTypes.func
};

AudioPlayerComponent.defaultProps = {
  label: '项目音频',
  onPlay: () => {},
  onPause: () => {}
};

export default AudioPlayerComponent; 