import React, { useState, useCallback } from 'react';
import {
  MessageCircle,
  Image,
  Music,
  Play,
  Download,
  CheckCircle,
  XCircle,
  Loader2,
  FileImage,
  FileAudio,
  X
} from 'lucide-react';
import { open } from '@tauri-apps/plugin-dialog';
import { invoke } from '@tauri-apps/api/core';
import { useNotifications } from './NotificationSystem';
import {
  HedraTaskSubmitRequest,
  TaskResponse
} from '../types/bowongTextVideoAgent';

// 简化的状态接口
interface SimpleHedraState {
  selectedImage: { path: string; name: string } | null;
  selectedAudio: { path: string; name: string } | null;
  prompt: string;
  resolution: '720p' | '540p';
  aspectRatio: '1:1' | '16:9' | '9:16';
  task: {
    status: 'idle' | 'submitting' | 'processing' | 'completed' | 'failed';
    taskId?: string;
    result?: any;
    error?: string;
    progress?: number;
  };
  isProcessing: boolean;
}

interface HedraLipSyncModalProps {
  isOpen: boolean;
  onClose: () => void;
  onTaskCreated?: (recordId: string) => void;
}

/**
 * Hedra 口型合成Modal组件
 */
const HedraLipSyncModal: React.FC<HedraLipSyncModalProps> = ({ 
  isOpen, 
  onClose, 
  onTaskCreated 
}) => {
  const { addNotification } = useNotifications();

  // 组件状态
  const [state, setState] = useState<SimpleHedraState>({
    selectedImage: null,
    selectedAudio: null,
    prompt: '',
    resolution: '720p',
    aspectRatio: '16:9',
    task: { status: 'idle' },
    isProcessing: false
  });

  // 重置状态
  const resetState = useCallback(() => {
    setState({
      selectedImage: null,
      selectedAudio: null,
      prompt: '',
      resolution: '720p',
      aspectRatio: '16:9',
      task: { status: 'idle' },
      isProcessing: false
    });
  }, []);

  // 关闭Modal
  const handleClose = useCallback(() => {
    if (!state.isProcessing) {
      resetState();
      onClose();
    }
  }, [state.isProcessing, resetState, onClose]);

  // 选择图片文件
  const selectImageFile = useCallback(async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [{
          name: 'Image',
          extensions: ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp']
        }]
      });

      if (selected && typeof selected === 'string') {
        const fileName = selected.split(/[/\\]/).pop() || 'unknown';
        setState(prev => ({
          ...prev,
          selectedImage: { path: selected, name: fileName }
        }));
      }
    } catch (error) {
      console.error('选择图片文件失败:', error);
      addNotification({
        type: 'error',
        title: '文件选择失败',
        message: '无法选择图片文件'
      });
    }
  }, [addNotification]);

  // 选择音频文件
  const selectAudioFile = useCallback(async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [{
          name: 'Audio',
          extensions: ['mp3', 'wav', 'aac', 'flac', 'm4a', 'ogg']
        }]
      });

      if (selected && typeof selected === 'string') {
        const fileName = selected.split(/[/\\]/).pop() || 'unknown';
        setState(prev => ({
          ...prev,
          selectedAudio: { path: selected, name: fileName }
        }));
      }
    } catch (error) {
      console.error('选择音频文件失败:', error);
      addNotification({
        type: 'error',
        title: '文件选择失败',
        message: '无法选择音频文件'
      });
    }
  }, [addNotification]);

  // 提交口型合成任务（异步方式）
  const handleSubmitTask = useCallback(async () => {
    if (!state.selectedImage || !state.selectedAudio) {
      addNotification({
        type: 'error',
        title: '文件未选择',
        message: '请先选择图片和音频文件'
      });
      return;
    }

    try {
      setState(prev => ({
        ...prev,
        isProcessing: true,
        task: { status: 'submitting' }
      }));

      // 创建数据库记录
      const recordRequest = {
        image_path: state.selectedImage.path,
        audio_path: state.selectedAudio.path,
        prompt: state.prompt || null
      };

      const record = await invoke<{ id: string }>('create_hedra_lipsync_record', { request: recordRequest });
      console.log('创建记录成功:', record);

      // 使用异步提交任务
      const taskRequest: HedraTaskSubmitRequest = {
        img_file: state.selectedImage.path,
        audio_file: state.selectedAudio.path,
        prompt: state.prompt,
        resolution: state.resolution,
        aspect_ratio: state.aspectRatio
      };

      const taskResponse: TaskResponse = await invoke('hedra_submit_task_async', {
        recordId: record.id,
        params: taskRequest
      });

      if (taskResponse.data) {
        // 更新记录的任务ID和状态
        await invoke('update_hedra_lipsync_record', {
          request: {
            id: record.id,
            task_id: taskResponse.data,
            status: 'processing'
          }
        });

        addNotification({
          type: 'success',
          title: '任务已提交',
          message: `口型合成任务已开始处理，任务ID：${taskResponse.data}`
        });

        // 通知父组件任务创建成功
        if (onTaskCreated) {
          onTaskCreated(record.id);
        }

        // 立即关闭 modal
        onClose();
      } else {
        throw new Error('任务提交失败：未获取到任务ID');
      }
    } catch (error) {
      console.error('口型合成任务失败:', error);
      setState(prev => ({
        ...prev,
        task: { status: 'failed', error: error instanceof Error ? error.message : '未知错误' },
        isProcessing: false
      }));

      addNotification({
        type: 'error',
        title: '任务提交失败',
        message: error instanceof Error ? error.message : '未知错误'
      });
    }
  }, [state.selectedImage, state.selectedAudio, state.prompt, state.resolution, state.aspectRatio, addNotification, onTaskCreated, onClose]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl max-w-4xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        {/* Modal Header */}
        <div className="flex justify-between items-center p-6 border-b">
          <div>
            <h2 className="text-2xl font-bold text-gray-900">创建Hedra口型合成任务</h2>
            <p className="text-gray-600 mt-1">上传图片和音频文件，生成口型同步视频</p>
          </div>
          <button
            onClick={handleClose}
            disabled={state.isProcessing}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors disabled:opacity-50"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* Modal Content */}
        <div className="p-6 space-y-6">
          {/* 文件选择区域 */}
          <div>
            <h3 className="text-lg font-medium text-gray-900 mb-4">文件上传</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* 图片选择 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-3">
                  <Image className="w-4 h-4 inline mr-2" />
                  图片文件 <span className="text-red-500">*</span>
                </label>
                <div
                  onClick={selectImageFile}
                  className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer hover:border-green-400 hover:bg-green-50 transition-colors"
                >
                  {state.selectedImage ? (
                    <div className="space-y-2">
                      <FileImage className="w-8 h-8 text-green-600 mx-auto" />
                      <p className="text-sm font-medium text-green-600">{state.selectedImage.name}</p>
                      <p className="text-xs text-gray-500">点击重新选择</p>
                    </div>
                  ) : (
                    <div className="space-y-2">
                      <FileImage className="w-8 h-8 text-gray-400 mx-auto" />
                      <p className="text-sm text-gray-600">点击选择图片文件</p>
                      <p className="text-xs text-gray-500">支持 PNG, JPG, JPEG, GIF, BMP, WebP</p>
                    </div>
                  )}
                </div>
              </div>

              {/* 音频选择 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-3">
                  <Music className="w-4 h-4 inline mr-2" />
                  音频文件 <span className="text-red-500">*</span>
                </label>
                <div
                  onClick={selectAudioFile}
                  className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer hover:border-green-400 hover:bg-green-50 transition-colors"
                >
                  {state.selectedAudio ? (
                    <div className="space-y-2">
                      <FileAudio className="w-8 h-8 text-green-600 mx-auto" />
                      <p className="text-sm font-medium text-green-600">{state.selectedAudio.name}</p>
                      <p className="text-xs text-gray-500">点击重新选择</p>
                    </div>
                  ) : (
                    <div className="space-y-2">
                      <FileAudio className="w-8 h-8 text-gray-400 mx-auto" />
                      <p className="text-sm text-gray-600">点击选择音频文件</p>
                      <p className="text-xs text-gray-500">支持 MP3, WAV, AAC, FLAC, M4A, OGG</p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* 提示词输入 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">
              <MessageCircle className="w-4 h-4 inline mr-2" />
              提示词 (可选)
            </label>
            <textarea
              value={state.prompt}
              onChange={(e) => setState(prev => ({ ...prev, prompt: e.target.value }))}
              placeholder="输入描述或提示词，帮助生成更好的口型同步效果..."
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent disabled:opacity-50 resize-none"
              rows={3}
            />
          </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">
                  分辨率
                </label>
                <select
                  value={state.resolution}
                  onChange={(e) => setState(prev => ({ ...prev, resolution: e.target.value as '720p' | '540p' }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"
                >
                  <option value="720p">720p (高清)</option>
                  <option value="540p">540p (标清)</option>
                </select>
              </div>

              {/* 宽高比 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  宽高比
                </label>
                <select
                  value={state.aspectRatio}
                  onChange={(e) => setState(prev => ({ ...prev, aspectRatio: e.target.value as '1:1' | '16:9' | '9:16' }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"
                >
                  <option value="16:9">16:9 (横屏)</option>
                  <option value="9:16">9:16 (竖屏)</option>
                  <option value="1:1">1:1 (正方形)</option>
                </select>
              </div>
            </div>
          </div>

          {/* 生成状态显示 */}
          {state.task.status !== 'idle' && (
            <div className="p-4 rounded-lg border">
              <div className="flex items-center gap-3">
                {state.task.status === 'submitting' && (
                  <>
                    <Loader2 className="w-5 h-5 text-blue-600 animate-spin" />
                    <div className="flex-1">
                      <p className="text-sm font-medium text-blue-600">正在提交任务</p>
                      <p className="text-xs text-gray-500">请稍候，正在处理您的请求...</p>
                    </div>
                  </>
                )}
                {state.task.status === 'processing' && (
                  <>
                    <Loader2 className="w-5 h-5 text-yellow-600 animate-spin" />
                    <div className="flex-1">
                      <p className="text-sm font-medium text-yellow-600">正在生成视频</p>
                      <p className="text-xs text-gray-500">
                        {state.task.progress !== undefined
                          ? `处理进度: ${state.task.progress}%`
                          : '正在处理口型同步，请耐心等待...'}
                      </p>
                      {state.task.progress !== undefined && (
                        <div className="w-full bg-gray-200 rounded-full h-2 mt-2">
                          <div
                            className="bg-yellow-600 h-2 rounded-full transition-all duration-300"
                            style={{ width: `${state.task.progress}%` }}
                          ></div>
                        </div>
                      )}
                    </div>
                  </>
                )}
                {state.task.status === 'completed' && (
                  <>
                    <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>
                      {state.task.result && (
                        <button
                          onClick={() => {
                            const link = document.createElement('a');
                            link.href = state.task.result;
                            link.download = `hedra_video_${Date.now()}.mp4`;
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                          }}
                          className="flex items-center gap-2 px-3 py-1.5 mt-2 bg-green-600 text-white text-xs rounded-md hover:bg-green-700 transition-colors"
                        >
                          <Download className="w-3 h-3" />
                          下载视频
                        </button>
                      )}
                    </div>
                  </>
                )}
                {state.task.status === 'failed' && (
                  <>
                    <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">{state.task.error || '任务处理失败，请重试'}</p>
                    </div>
                  </>
                )}
              </div>
            </div>
          )}
        </div>

        {/* Modal Footer */}
        <div className="flex justify-end gap-3 p-6 border-t bg-gray-50">
          <button
            onClick={handleClose}
            disabled={state.isProcessing}
            className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50"
          >
            取消
          </button>
          <button
            onClick={handleSubmitTask}
            disabled={!state.selectedImage || !state.selectedAudio || state.isProcessing}
            className="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center gap-2"
          >
            {state.isProcessing ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                处理中...
              </>
            ) : (
              <>
                <Play className="w-4 h-4" />
                开始生成
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
};

export default HedraLipSyncModal;
