import React, { useState, useCallback } from 'react';
import {
  Volume2,
  Download,
  CheckCircle,
  XCircle,
  Loader2,
  Settings,
  Users,
  ChevronDown
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { Modal } from './Modal';
import { useNotifications } from './NotificationSystem';
import { VoiceSelector } from './VoiceSelector';
import {
  SpeechGenerationRequest,
  SpeechGenerationResponse,
  SpeechGenerationStatus,
  SpeechGenerationState,
  VoiceInfo,
} from '../types/voiceClone';
import { SystemVoice } from '../types/systemVoice';

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

/**
 * 语音合成Modal组件
 * 封装语音合成功能为独立的弹框组件
 */
export const SpeechGenerationModal: React.FC<SpeechGenerationModalProps> = ({
  isOpen,
  onClose,
  onSuccess
}) => {
  const { addNotification } = useNotifications();

  // ============= 状态管理 =============

  // 音色选择状态
  const [selectedVoice, setSelectedVoice] = useState<{
    id: string;
    name: string;
    source: 'system' | 'custom';
    data: VoiceInfo | SystemVoice;
  } | null>(null);
  const [showVoiceSelector, setShowVoiceSelector] = useState(false);

  // 语音生成状态
  const [speechRequest, setSpeechRequest] = useState<SpeechGenerationRequest>({
    text: '',
    voice_id: '',
    speed: 1.0,
    vol: 1.0,
    emotion: 'calm'
  });
  const [speechState, setSpeechState] = useState<SpeechGenerationState>({
    status: SpeechGenerationStatus.IDLE
  });

  // ============= 音色选择功能 =============

  const handleVoiceSelect = useCallback((voiceId: string, voiceInfo: VoiceInfo | SystemVoice, source: 'system' | 'custom') => {
    const voiceName = voiceInfo.voice_name;

    setSelectedVoice({
      id: voiceId,
      name: voiceName || voiceId,
      source,
      data: voiceInfo
    });

    setSpeechRequest(prev => ({
      ...prev,
      voice_id: voiceId
    }));

    setShowVoiceSelector(false);
  }, []);

  // ============= 语音生成功能 =============

  const handleGenerateSpeech = useCallback(async () => {
    if (!speechRequest.text.trim()) {
      addNotification({
        type: 'warning',
        title: '请输入要合成的文本',
        message: '请输入要转换为语音的文本内容'
      });
      return;
    }

    if (!speechRequest.voice_id) {
      addNotification({
        type: 'warning',
        title: '请选择音色',
        message: '请选择要使用的音色'
      });
      return;
    }

    setSpeechState({
      status: SpeechGenerationStatus.GENERATING,
      progress: '正在生成语音...'
    });

    try {
      const response = await invoke<SpeechGenerationResponse>('generate_speech', { 
        request: speechRequest 
      });

      if (response.status && response.data) {
        setSpeechState({
          status: SpeechGenerationStatus.SUCCESS,
          result: response
        });
        
        addNotification({
          type: 'success',
          title: '语音生成成功',
          message: '语音已成功生成，可以播放或下载'
        });

        // 调用成功回调
        if (onSuccess) {
          onSuccess(response.data);
        }
      } else {
        throw new Error(response.msg || '生成失败');
      }
    } catch (error) {
      console.error('语音生成失败:', error);
      setSpeechState({
        status: SpeechGenerationStatus.ERROR,
        error: String(error)
      });
      
      addNotification({
        type: 'error',
        title: '语音生成失败',
        message: `生成失败: ${error}`
      });
    }
  }, [speechRequest, addNotification, onSuccess]);

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

  const handleClose = useCallback(() => {
    // 重置状态
    setSpeechRequest({
      text: '',
      voice_id: '',
      speed: 1.0,
      vol: 1.0,
      emotion: 'calm'
    });
    setSpeechState({ status: SpeechGenerationStatus.IDLE });
    setSelectedVoice(null);
    setShowVoiceSelector(false);
    onClose();
  }, [onClose]);

  return (
    <Modal
      isOpen={isOpen}
      onClose={handleClose}
      title="语音合成"
      subtitle="将文本转换为语音"
      icon={<Volume2 className="w-6 h-6 text-white" />}
      size="lg"
      variant="default"
      closeOnBackdropClick={speechState.status !== SpeechGenerationStatus.GENERATING}
      closeOnEscape={speechState.status !== SpeechGenerationStatus.GENERATING}
    >
      <div className="p-6 space-y-6">
        {/* 文本输入 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            合成文本 <span className="text-red-500">*</span>
          </label>
          <textarea
            value={speechRequest.text}
            onChange={(e) => setSpeechRequest(prev => ({ ...prev, text: e.target.value }))}
            disabled={speechState.status === SpeechGenerationStatus.GENERATING}
            placeholder="请输入要转换为语音的文本内容..."
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50 resize-none"
            rows={4}
          />
        </div>

        {/* 音色选择 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            选择音色 <span className="text-red-500">*</span>
          </label>

          <button
            onClick={() => setShowVoiceSelector(true)}
            disabled={speechState.status === SpeechGenerationStatus.GENERATING}
            className="w-full flex items-center justify-between px-4 py-3 border border-gray-300 rounded-lg hover:border-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50 transition-colors"
          >
            <div className="flex items-center gap-3">
              {selectedVoice ? (
                <>
                  {selectedVoice.source === 'system' ? (
                    <Settings className="w-4 h-4 text-blue-600" />
                  ) : (
                    <Users className="w-4 h-4 text-orange-600" />
                  )}
                  <div className="text-left">
                    <p className="font-medium text-gray-900">{selectedVoice.name}</p>
                    <p className="text-sm text-gray-500">
                      {selectedVoice.source === 'system' ? '系统音色' : '自定义音色'}
                    </p>
                  </div>
                </>
              ) : (
                <>
                  <Volume2 className="w-4 h-4 text-gray-400" />
                  <span className="text-gray-500">点击选择音色</span>
                </>
              )}
            </div>
            <ChevronDown className="w-4 h-4 text-gray-400" />
          </button>
        </div>

        {/* 参数控制 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-3">
            语音参数
          </label>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                语速: {speechRequest.speed}
              </label>
              <input
                type="range"
                min="0.5"
                max="2"
                step="0.1"
                value={speechRequest.speed}
                onChange={(e) => setSpeechRequest(prev => ({
                  ...prev,
                  speed: parseFloat(e.target.value)
                }))}
                disabled={speechState.status === SpeechGenerationStatus.GENERATING}
                className="w-full"
              />
              <div className="flex justify-between text-xs text-gray-500 mt-1">
                <span>0.5x</span>
                <span>2.0x</span>
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                音量: {speechRequest.vol}
              </label>
              <input
                type="range"
                min="0.1"
                max="2"
                step="0.1"
                value={speechRequest.vol}
                onChange={(e) => setSpeechRequest(prev => ({
                  ...prev,
                  vol: parseFloat(e.target.value)
                }))}
                disabled={speechState.status === SpeechGenerationStatus.GENERATING}
                className="w-full"
              />
              <div className="flex justify-between text-xs text-gray-500 mt-1">
                <span>0.1x</span>
                <span>2.0x</span>
              </div>
            </div>
          </div>
        </div>

        {/* 情感选择 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            情感风格
          </label>
          <select
            value={speechRequest.emotion || 'calm'}
            onChange={(e) => setSpeechRequest(prev => ({ ...prev, emotion: e.target.value as 'happy' | 'sad' | 'angry' | 'fearful' | 'disgusted' | 'surprised' | 'calm' }))}
            disabled={speechState.status === SpeechGenerationStatus.GENERATING}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50"
          >
            <option value="calm">平静</option>
            <option value="happy">快乐</option>
            <option value="sad">悲伤</option>
            <option value="angry">愤怒</option>
            <option value="excited">兴奋</option>
            <option value="gentle">温柔</option>
          </select>
        </div>

        {/* 生成状态显示 */}
        {speechState.status !== SpeechGenerationStatus.IDLE && (
          <div className="p-4 rounded-lg border">
            <div className="flex items-center gap-3">
              {speechState.status === SpeechGenerationStatus.SUCCESS && (
                <>
                  <CheckCircle className="w-5 h-5 text-green-600" />
                  <div className="flex-1">
                    <p className="text-sm font-medium text-green-600">生成成功</p>
                    <p className="text-xs text-gray-500">语音已生成完成</p>
                  </div>
                </>
              )}
              {speechState.status === SpeechGenerationStatus.ERROR && (
                <>
                  <XCircle className="w-5 h-5 text-red-600" />
                  <div className="flex-1">
                    <p className="text-sm font-medium text-red-600">生成失败</p>
                    <p className="text-xs text-gray-500">{speechState.error}</p>
                  </div>
                </>
              )}
              {speechState.status === SpeechGenerationStatus.GENERATING && (
                <>
                  <Loader2 className="w-5 h-5 animate-spin text-blue-600" />
                  <div className="flex-1">
                    <p className="text-sm font-medium text-blue-600">生成中</p>
                    <p className="text-xs text-gray-500">{speechState.progress}</p>
                  </div>
                </>
              )}
            </div>

            {/* 音频播放器 */}
            {speechState.result?.data && speechState.status === SpeechGenerationStatus.SUCCESS && (
              <div className="mt-4 p-3 bg-gray-50 rounded-lg">
                <div className="flex items-center justify-between mb-2">
                  <span className="text-sm font-medium text-gray-700">生成的语音</span>
                  <button
                    onClick={() => {
                      // 下载音频文件
                      const link = document.createElement('a');
                      link.href = speechState.result!.data!;
                      link.download = 'generated_speech.wav';
                      link.click();
                    }}
                    className="flex items-center gap-1 px-2 py-1 text-xs bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
                  >
                    <Download className="w-3 h-3" />
                    下载
                  </button>
                </div>

                <audio
                  controls
                  src={speechState.result.data}
                  className="w-full"
                >
                  您的浏览器不支持音频播放
                </audio>
              </div>
            )}
          </div>
        )}

        {/* 操作按钮 */}
        <div className="flex gap-3 pt-4 border-t">
          <button
            onClick={handleClose}
            disabled={speechState.status === SpeechGenerationStatus.GENERATING}
            className="flex-1 px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 disabled:opacity-50 transition-colors"
          >
            {speechState.status === SpeechGenerationStatus.SUCCESS ? '完成' : '取消'}
          </button>
          <button
            onClick={handleGenerateSpeech}
            disabled={
              speechState.status === SpeechGenerationStatus.GENERATING ||
              !speechRequest.text.trim() ||
              !speechRequest.voice_id
            }
            className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {speechState.status === SpeechGenerationStatus.GENERATING ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                生成中...
              </>
            ) : (
              <>
                <Volume2 className="w-4 h-4" />
                生成语音
              </>
            )}
          </button>
        </div>
      </div>

      {/* 音色选择器弹框 */}
      <VoiceSelector
        isOpen={showVoiceSelector}
        onClose={() => setShowVoiceSelector(false)}
        onSelect={handleVoiceSelect}
        selectedVoiceId={selectedVoice?.id}
      />
    </Modal>
  );
};
