import React, { useState, useCallback } from 'react';
import {
  Mic,
  Upload,
  Wand2,
  CheckCircle,
  XCircle,
  Loader2,
  Music,
  FileAudio,
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { open } from '@tauri-apps/plugin-dialog';
import { Modal } from './Modal';
import { useNotifications } from './NotificationSystem';
import {
  AudioUploadRequest,
  AudioUploadResponse,
  VoiceCloneRequest,
  VoiceCloneResponse,
  VoiceCloneStatus,
  AudioFileInfo,
  VoiceCloneState
} from '../types/voiceClone';

interface VoiceCloneModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: (voiceId: string) => void;
}

/**
 * 声音克隆Modal组件
 * 封装声音克隆功能为独立的弹框组件
 */
export const VoiceCloneModal: React.FC<VoiceCloneModalProps> = ({
  isOpen,
  onClose,
  onSuccess
}) => {
  const { addNotification } = useNotifications();

  // ============= 状态管理 =============
  
  // 音频上传状态
  const [audioFile, setAudioFile] = useState<AudioFileInfo | null>(null);

  // 声音克隆状态
  const [cloneText, setCloneText] = useState('');
  const [customVoiceId, setCustomVoiceId] = useState('');
  const [cloneState, setCloneState] = useState<VoiceCloneState>({
    status: VoiceCloneStatus.IDLE
  });

  // 合并后的状态：是否正在处理（上传+克隆）
  const [isProcessingClone, setIsProcessingClone] = useState(false);

  // ============= 文件选择功能 =============

  const handleFileSelect = useCallback(async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [{
          name: 'Audio Files',
          extensions: ['wav', 'mp3', 'flac', 'm4a', 'aac', 'ogg']
        }]
      });

      if (selected && typeof selected === 'string') {
        const file = new File([], selected.split('/').pop() || 'audio');
        const audioInfo: AudioFileInfo = {
          file,
          name: file.name,
          size: 0, // 实际应该获取文件大小
          type: file.type || 'audio/wav',
          preview_url: selected
        };
        
        setAudioFile(audioInfo);
        addNotification({
          type: 'success',
          title: '文件选择成功',
          message: `已选择音频文件: ${audioInfo.name}`
        });
      }
    } catch (error) {
      console.error('文件选择失败:', error);
      addNotification({
        type: 'error',
        title: '文件选择失败',
        message: `选择文件时出错: ${error}`
      });
    }
  }, [addNotification]);

  // ============= 声音克隆功能 =============

  const handleVoiceClone = useCallback(async () => {
    if (!cloneText.trim()) {
      addNotification({
        type: 'warning',
        title: '请输入克隆文本',
        message: '请输入用于声音克隆的文本内容'
      });
      return;
    }

    if (!audioFile?.preview_url) {
      addNotification({
        type: 'warning',
        title: '请先选择音频文件',
        message: '请先选择参考音频文件'
      });
      return;
    }

    setIsProcessingClone(true);
    setCloneState({
      status: VoiceCloneStatus.PROCESSING,
      progress: '正在上传音频文件...'
    });

    try {
      // 第一步：上传音频文件
      const uploadRequest: AudioUploadRequest = {
        audio_file_path: audioFile.preview_url,
        purpose: 'voice_clone'
      };

      const uploadResponse = await invoke<AudioUploadResponse>('upload_audio_file', { request: uploadRequest });

      if (!uploadResponse.status) {
        throw new Error(uploadResponse.msg || '音频上传失败');
      }

      // 更新进度
      setCloneState({
        status: VoiceCloneStatus.PROCESSING,
        progress: '音频上传成功，正在克隆声音...'
      });

      // 第二步：执行声音克隆
      const finalVoiceId = customVoiceId.trim() || `voice_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;

      const cloneRequest: VoiceCloneRequest = {
        text: cloneText,
        model: 'speech-02-hd',
        need_noise_reduction: true,
        voice_id: finalVoiceId,
        prefix: 'BoWong-',
        audio_file_path: audioFile.preview_url
      };

      const cloneResponse = await invoke<VoiceCloneResponse>('clone_voice', { request: cloneRequest });

      if (cloneResponse.status && cloneResponse.data) {
        setCloneState({
          status: VoiceCloneStatus.SUCCESS,
          result: cloneResponse
        });

        const voiceId = cloneResponse.extra?.voice_id || finalVoiceId;
        addNotification({
          type: 'success',
          title: '声音克隆成功',
          message: `新音色ID: ${voiceId}`
        });

        // 调用成功回调
        if (onSuccess) {
          onSuccess(voiceId);
        }

        // 延迟关闭Modal，让用户看到成功状态
        setTimeout(() => {
          handleClose();
        }, 2000);
      } else {
        throw new Error(cloneResponse.msg || '克隆失败');
      }
    } catch (error) {
      console.error('声音克隆失败:', error);
      setCloneState({
        status: VoiceCloneStatus.ERROR,
        error: String(error)
      });

      addNotification({
        type: 'error',
        title: '声音克隆失败',
        message: `克隆失败: ${error}`
      });
    } finally {
      setIsProcessingClone(false);
    }
  }, [cloneText, audioFile, customVoiceId, addNotification, onSuccess]);

  // ============= Modal控制 =============

  const handleClose = useCallback(() => {
    // 重置状态
    setAudioFile(null);
    setCloneText('');
    setCustomVoiceId('');
    setCloneState({ status: VoiceCloneStatus.IDLE });
    setIsProcessingClone(false);
    onClose();
  }, [onClose]);

  return (
    <Modal
      isOpen={isOpen}
      onClose={handleClose}
      title="声音克隆"
      subtitle="上传参考音频，生成专属音色"
      icon={<Mic className="w-6 h-6 text-white" />}
      size="lg"
      variant="default"
      closeOnBackdropClick={!isProcessingClone}
      closeOnEscape={!isProcessingClone}
    >
      <div className="p-6 space-y-6">
        {/* 音频文件上传 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-3">
            参考音频文件
          </label>
          <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-purple-400 transition-colors">
            {audioFile ? (
              <div className="flex items-center justify-center gap-3">
                <FileAudio className="w-8 h-8 text-purple-600" />
                <div className="text-left">
                  <p className="text-sm font-medium text-gray-900">{audioFile.name}</p>
                  <p className="text-xs text-gray-500">{audioFile.type}</p>
                </div>
              </div>
            ) : (
              <div>
                <Music className="w-8 h-8 text-gray-400 mx-auto mb-2" />
                <p className="text-gray-600 text-sm mb-1">选择参考音频文件</p>
                <p className="text-xs text-gray-500">支持 WAV, MP3, FLAC, M4A, AAC, OGG 格式</p>
              </div>
            )}

            <button
              onClick={handleFileSelect}
              disabled={isProcessingClone}
              className="mt-3 px-4 py-2 text-sm bg-purple-600 text-white rounded-md hover:bg-purple-700 disabled:opacity-50 transition-colors"
            >
              <Upload className="w-4 h-4 inline mr-2" />
              {audioFile ? '重新选择' : '选择文件'}
            </button>
          </div>
        </div>

        {/* 克隆文本输入 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            克隆文本 <span className="text-red-500">*</span>
          </label>
          <textarea
            value={cloneText}
            onChange={(e) => setCloneText(e.target.value)}
            disabled={isProcessingClone}
            placeholder="请输入用于声音克隆的文本内容，建议使用清晰、标准的语音内容..."
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent disabled:opacity-50 resize-none"
            rows={4}
          />
          <p className="text-xs text-gray-500 mt-1">
            建议使用与参考音频相同的语言和风格
          </p>
        </div>

        {/* 自定义音色ID */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            自定义音色ID（可选）
          </label>
          <input
            type="text"
            value={customVoiceId}
            onChange={(e) => setCustomVoiceId(e.target.value)}
            disabled={isProcessingClone}
            placeholder="留空将自动生成唯一ID"
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent disabled:opacity-50"
          />
        </div>

        {/* 克隆状态显示 */}
        {cloneState.status !== VoiceCloneStatus.IDLE && (
          <div className="p-4 rounded-lg border">
            <div className="flex items-center gap-3">
              {cloneState.status === VoiceCloneStatus.SUCCESS && (
                <>
                  <CheckCircle className="w-5 h-5 text-green-600" />
                  <div>
                    <p className="text-sm font-medium text-green-600">克隆成功</p>
                    <p className="text-xs text-gray-500">音色已生成，即将关闭窗口</p>
                  </div>
                </>
              )}
              {cloneState.status === VoiceCloneStatus.ERROR && (
                <>
                  <XCircle className="w-5 h-5 text-red-600" />
                  <div>
                    <p className="text-sm font-medium text-red-600">克隆失败</p>
                    <p className="text-xs text-gray-500">{cloneState.error}</p>
                  </div>
                </>
              )}
              {cloneState.status === VoiceCloneStatus.PROCESSING && (
                <>
                  <Loader2 className="w-5 h-5 animate-spin text-purple-600" />
                  <div>
                    <p className="text-sm font-medium text-purple-600">处理中</p>
                    <p className="text-xs text-gray-500">{cloneState.progress}</p>
                  </div>
                </>
              )}
            </div>
          </div>
        )}

        {/* 操作按钮 */}
        <div className="flex gap-3 pt-4 border-t">
          <button
            onClick={handleClose}
            disabled={isProcessingClone}
            className="flex-1 px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 disabled:opacity-50 transition-colors"
          >
            取消
          </button>
          <button
            onClick={handleVoiceClone}
            disabled={isProcessingClone || !cloneText.trim() || !audioFile}
            className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {isProcessingClone ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                处理中...
              </>
            ) : (
              <>
                <Wand2 className="w-4 h-4" />
                开始克隆
              </>
            )}
          </button>
        </div>
      </div>
    </Modal>
  );
};
