import React, { useState, useCallback } from 'react';
import {
  MessageCircle,
  Image,
  Music,
  Play,
  Download,
  CheckCircle,
  XCircle,
  Loader2,
  AlertCircle,
  FileImage,
  FileAudio
} from 'lucide-react';
import { open } from '@tauri-apps/plugin-dialog';
import { invoke } from '@tauri-apps/api/core';
import { useNotifications } from '../../components/NotificationSystem';
import {
  HedraTaskSubmitRequest,
  HedraTaskStatusParams,
  TaskResponse,
  TaskStatusResponse
} 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;
}

/**
 * Hedra 口型合成工具 - 简化版
 * 直接使用本地文件路径提交任务，无需上传
 */
const SimpleHedraLipSyncTool: React.FC = () => {
  const { addNotification } = useNotifications();

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

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

      if (selected) {
        setState(prev => ({
          ...prev,
          selectedImage: {
            path: selected as string,
            name: (selected as string).split('\\').pop() || (selected as string).split('/').pop() || 'unknown'
          }
        }));

        addNotification({
          type: 'success',
          title: '图片已选择',
          message: `已选择图片文件`
        });
      }
    } catch (error) {
      console.error('选择图片失败:', error);
      addNotification({
        type: 'error',
        title: '选择图片失败',
        message: error instanceof Error ? error.message : '未知错误'
      });
    }
  }, [addNotification]);

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

      if (selected) {
        setState(prev => ({
          ...prev,
          selectedAudio: {
            path: selected as string,
            name: (selected as string).split('\\').pop() || (selected as string).split('/').pop() || 'unknown'
          }
        }));

        addNotification({
          type: 'success',
          title: '音频已选择',
          message: `已选择音频文件`
        });
      }
    } catch (error) {
      console.error('选择音频失败:', error);
      addNotification({
        type: 'error',
        title: '选择音频失败',
        message: error instanceof Error ? error.message : '未知错误'
      });
    }
  }, [addNotification]);

  // 轮询任务状态
  const pollTaskStatus = useCallback(async (taskId: string, recordId?: string) => {
    const maxAttempts = 60; // 最多轮询60次（5分钟）
    let attempts = 0;

    const poll = async () => {
      try {
        attempts++;
        console.log(`轮询任务状态 (${attempts}/${maxAttempts}):`, taskId);

        const params: HedraTaskStatusParams = { task_id: taskId };
        const statusResponse: TaskStatusResponse = await invoke('hedra_query_task_status', { params });

        console.log('任务状态响应:', statusResponse);

        setState(prev => ({
          ...prev,
          task: {
            ...prev.task,
            progress: statusResponse.progress || 0
          }
        }));

        // 更新数据库记录
        if (recordId) {
          // 确定视频URL
          const videoUrl = statusResponse.result?.video_url ||
                          statusResponse.result?.url ||
                          statusResponse.result?.videoUrl ||
                          (typeof statusResponse.result === 'string' ? statusResponse.result : null);

          // 正确映射状态 - 从TaskStatus枚举值映射到数据库字符串
          let mappedStatus: string;
          switch (statusResponse.status) {
            case 'success':
              mappedStatus = 'completed';
              break;
            case 'running':
              mappedStatus = 'processing';
              break;
            case 'failed':
              mappedStatus = 'failed';
              break;
            case 'cancelled':
              mappedStatus = 'cancelled';
              break;
            case 'pending':
            default:
              mappedStatus = 'pending';
              break;
          }

          console.log('轮询状态更新:', {
            originalStatus: statusResponse.status,
            mappedStatus: mappedStatus,
            progress: statusResponse.progress,
            result: statusResponse.result,
            videoUrl: videoUrl,
            error: statusResponse.error
          });

          // 只有真正的错误才保存到error_message，状态信息不保存
          const errorMessage = statusResponse.error && statusResponse.status === 'failed' ? statusResponse.error : null;

          await invoke('update_hedra_lipsync_record', {
            request: {
              id: recordId,
              status: mappedStatus,
              progress: statusResponse.progress || 0,
              result_video_url: videoUrl,
              error_message: errorMessage
            }
          });
        }

        // 检查任务状态
        if (statusResponse.status === 'success') {
          setState(prev => ({
            ...prev,
            task: {
              status: 'completed',
              taskId,
              result: statusResponse.result?.video_url || statusResponse.result?.url || statusResponse.result,
              progress: 100
            },
            isProcessing: false
          }));

          addNotification({
            type: 'success',
            title: '口型合成完成',
            message: '视频生成成功！'
          });
          return;
        } else if (statusResponse.status === 'failed') {
          setState(prev => ({
            ...prev,
            task: {
              status: 'failed',
              taskId,
              error: statusResponse.error || '任务执行失败'
            },
            isProcessing: false
          }));

          addNotification({
            type: 'error',
            title: '口型合成失败',
            message: statusResponse.error || '任务执行失败'
          });
          return;
        }

        // 继续轮询
        if (attempts < maxAttempts) {
          setTimeout(poll, 5000); // 5秒后再次轮询
        } else {
          setState(prev => ({
            ...prev,
            task: {
              status: 'failed',
              taskId,
              error: '任务超时'
            },
            isProcessing: false
          }));

          addNotification({
            type: 'error',
            title: '任务超时',
            message: '任务执行时间过长，请稍后手动查询'
          });
        }
      } catch (error) {
        console.error('查询任务状态失败:', error);
        setState(prev => ({
          ...prev,
          task: {
            status: 'failed',
            taskId,
            error: error instanceof Error ? error.message : '查询状态失败'
          },
          isProcessing: false
        }));

        addNotification({
          type: 'error',
          title: '查询状态失败',
          message: error instanceof Error ? error.message : '未知错误'
        });
      }
    };

    poll();
  }, [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', { params: taskRequest });
      if (taskResponse.data) {
        setState(prev => ({
          ...prev,
          task: {
            status: 'processing',
            taskId: 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}`
        });

        // 开始轮询任务状态
        pollTaskStatus(taskResponse.data, record.id);
      } 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, pollTaskStatus]);

  return (
    <div className="max-w-4xl mx-auto p-6 space-y-6">
      {/* 页面标题 */}
      <div className="text-center">
        <div className="flex items-center justify-center gap-3 mb-4">
          <MessageCircle className="w-8 h-8 text-blue-600" />
          <h1 className="text-3xl font-bold text-gray-900">Hedra 口型合成工具</h1>
        </div>
        <p className="text-gray-600">
          上传图片和音频文件，生成口型同步视频
        </p>
      </div>

      {/* 文件选择区域 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* 图片选择 */}
        <div className="bg-white rounded-lg border-2 border-dashed border-gray-300 p-6">
          <div className="text-center">
            <FileImage className="mx-auto h-12 w-12 text-gray-400" />
            <h3 className="mt-2 text-sm font-medium text-gray-900">选择图片</h3>
            <p className="mt-1 text-sm text-gray-500">支持 PNG, JPG, JPEG, GIF, BMP, WebP</p>

            {state.selectedImage ? (
              <div className="mt-4 p-3 bg-green-50 rounded-lg">
                <div className="flex items-center justify-center gap-2">
                  <CheckCircle className="w-5 h-5 text-green-600" />
                  <span className="text-sm text-green-800">{state.selectedImage.name}</span>
                </div>
              </div>
            ) : (
              <button
                onClick={handleImageSelect}
                className="mt-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
              >
                <Image className="w-4 h-4 mr-2" />
                选择图片
              </button>
            )}
          </div>
        </div>

        {/* 音频选择 */}
        <div className="bg-white rounded-lg border-2 border-dashed border-gray-300 p-6">
          <div className="text-center">
            <FileAudio className="mx-auto h-12 w-12 text-gray-400" />
            <h3 className="mt-2 text-sm font-medium text-gray-900">选择音频</h3>
            <p className="mt-1 text-sm text-gray-500">支持 MP3, WAV, AAC, FLAC, M4A, OGG</p>

            {state.selectedAudio ? (
              <div className="mt-4 p-3 bg-green-50 rounded-lg">
                <div className="flex items-center justify-center gap-2">
                  <CheckCircle className="w-5 h-5 text-green-600" />
                  <span className="text-sm text-green-800">{state.selectedAudio.name}</span>
                </div>
              </div>
            ) : (
              <button
                onClick={handleAudioSelect}
                className="mt-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
              >
                <Music className="w-4 h-4 mr-2" />
                选择音频
              </button>
            )}
          </div>
        </div>
      </div>

      {/* 参数配置区域 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-medium text-gray-900 mb-4">生成参数</h3>

        <div className="space-y-4">
          {/* Prompt 输入 */}
          <div>
            <label htmlFor="prompt" className="block text-sm font-medium text-gray-700 mb-2">
              文本提示词 (可选)
            </label>
            <textarea
              id="prompt"
              value={state.prompt}
              onChange={(e) => {
                console.log('Prompt 输入变化:', e.target.value);
                setState(prev => {
                  const newState = { ...prev, prompt: e.target.value };
                  console.log('更新后的状态:', newState);
                  return newState;
                });
              }}
              placeholder="输入描述视频内容的提示词，例如：一个人在说话，表情自然..."
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              rows={3}
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* 分辨率选择 */}
            <div>
              <label htmlFor="resolution" className="block text-sm font-medium text-gray-700 mb-2">
                分辨率
              </label>
              <select
                id="resolution"
                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-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="720p">720p (高清)</option>
                <option value="540p">540p (标清)</option>
              </select>
            </div>

            {/* 宽高比选择 */}
            <div>
              <label htmlFor="aspectRatio" className="block text-sm font-medium text-gray-700 mb-2">
                宽高比
              </label>
              <select
                id="aspectRatio"
                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-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="1:1">1:1 (正方形)</option>
                <option value="16:9">16:9 (横屏)</option>
                <option value="9:16">9:16 (竖屏)</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      {/* 操作按钮 */}
      <div className="text-center">
        <button
          onClick={handleSubmitTask}
          disabled={!state.selectedImage || !state.selectedAudio || state.isProcessing}
          className="inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-green-600 hover:bg-green-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
        >
          {state.isProcessing ? (
            <>
              <Loader2 className="w-5 h-5 mr-2 animate-spin" />
              处理中...
            </>
          ) : (
            <>
              <Play className="w-5 h-5 mr-2" />
              开始口型合成
            </>
          )}
        </button>
      </div>

      {/* 任务状态显示 */}
      {state.task.status !== 'idle' && (
        <div className="bg-white rounded-lg border p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">任务状态</h3>

          <div className="space-y-4">
            {/* 状态指示器 */}
            <div className="flex items-center gap-3">
              {state.task.status === 'submitting' && (
                <>
                  <Loader2 className="w-5 h-5 text-blue-600 animate-spin" />
                  <span className="text-blue-600">正在提交任务...</span>
                </>
              )}
              {state.task.status === 'processing' && (
                <>
                  <Loader2 className="w-5 h-5 text-yellow-600 animate-spin" />
                  <span className="text-yellow-600">正在处理中...</span>
                </>
              )}
              {state.task.status === 'completed' && (
                <>
                  <CheckCircle className="w-5 h-5 text-green-600" />
                  <span className="text-green-600">处理完成</span>
                </>
              )}
              {state.task.status === 'failed' && (
                <>
                  <XCircle className="w-5 h-5 text-red-600" />
                  <span className="text-red-600">处理失败</span>
                </>
              )}
            </div>

            {/* 任务ID */}
            {state.task.taskId && (
              <div className="text-sm text-gray-600">
                任务ID: {state.task.taskId}
              </div>
            )}

            {/* 进度条 */}
            {state.task.progress !== undefined && state.task.status === 'processing' && (
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div
                  className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${state.task.progress}%` }}
                ></div>
              </div>
            )}

            {/* 错误信息 */}
            {state.task.error && (
              <div className="p-3 bg-red-50 rounded-lg">
                <div className="flex items-center gap-2">
                  <AlertCircle className="w-5 h-5 text-red-600" />
                  <span className="text-sm text-red-800">{state.task.error}</span>
                </div>
              </div>
            )}

            {/* 结果下载 */}
            {state.task.status === 'completed' && state.task.result && (
              <div className="p-4 bg-green-50 rounded-lg">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <CheckCircle className="w-5 h-5 text-green-600" />
                    <span className="text-sm text-green-800">视频生成完成</span>
                  </div>
                  <a
                    href={Array.isArray(state.task.result) ? state.task.result[0] : state.task.result}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center px-3 py-1 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700"
                  >
                    <Download className="w-4 h-4 mr-1" />
                    下载视频
                  </a>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default SimpleHedraLipSyncTool;
