import React from 'react';
import {
  PlayIcon,
  ArrowPathIcon,
  EyeIcon,
  TrashIcon,
  ClockIcon,
  CheckCircleIcon,
  XCircleIcon,
  SparklesIcon
} from '@heroicons/react/24/outline';
import { invoke } from '@tauri-apps/api/core';
import { Model } from '../../types/model';
import {
  VideoGenerationTask,
  VideoPromptConfig,
  VideoGenerationStatus,
  TEMPLATE_OPTIONS,
  SCENE_OPTIONS,
  PRODUCT_OPTIONS,
  VIDEO_GENERATION_STATUS_CONFIG
} from '../../types/videoGeneration';
import { LoadingSpinner } from '../LoadingSpinner';

interface ModelVideoTabProps {
  model: Model;
  videoTasks: VideoGenerationTask[];
  selectedPhotos: string[];
  promptConfig: VideoPromptConfig;
  isGenerating: boolean;
  onSelectedPhotosChange: (photos: string[]) => void;
  onPromptConfigChange: (config: VideoPromptConfig) => void;
  onGenerateVideo: () => void;
  onDeleteTask: (taskId: string) => void;
  onRefreshTasks: () => void;
}

/**
 * 模特详情视频生成Tab组件
 * 包含视频生成配置和任务管理
 */
export const ModelVideoTab: React.FC<ModelVideoTabProps> = ({
  model,
  videoTasks,
  selectedPhotos,
  promptConfig,
  isGenerating,
  onSelectedPhotosChange,
  onPromptConfigChange,
  onGenerateVideo,
  onDeleteTask,
  onRefreshTasks
}) => {
  // 获取视频任务状态图标
  const getVideoTaskStatusIcon = (status: VideoGenerationStatus) => {
    switch (status) {
      case VideoGenerationStatus.Pending:
        return ClockIcon;
      case VideoGenerationStatus.Processing:
        return SparklesIcon;
      case VideoGenerationStatus.Completed:
        return CheckCircleIcon;
      case VideoGenerationStatus.Failed:
        return XCircleIcon;
      case VideoGenerationStatus.Cancelled:
        return XCircleIcon;
      default:
        return ClockIcon;
    }
  };

  const handlePhotoToggle = (photoId: string) => {
    const newSelection = selectedPhotos.includes(photoId)
      ? selectedPhotos.filter(id => id !== photoId)
      : [...selectedPhotos, photoId];
    onSelectedPhotosChange(newSelection);
  };

  const handleConfigChange = (field: keyof VideoPromptConfig, value: any) => {
    onPromptConfigChange({
      ...promptConfig,
      [field]: value
    });
  };

  return (
    <div className="animate-fade-in">
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 视频生成配置 */}
        <div className="bg-gradient-to-br from-white to-red-50/30 rounded-2xl shadow-sm border border-gray-200/50 p-6 hover:shadow-md transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
          <div className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-red-100/50 to-red-200/50 rounded-full -translate-y-8 translate-x-8 opacity-50"></div>
          
          <div className="relative z-10">
            <div className="flex items-center mb-4">
              <div className="w-10 h-10 bg-gradient-to-br from-red-500 to-red-600 rounded-xl flex items-center justify-center text-white mr-3">
                <span className="text-lg">🎬</span>
              </div>
              <h3 className="text-lg font-semibold text-gray-900">视频生成配置</h3>
            </div>

            {/* 照片选择 */}
            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                选择照片 ({selectedPhotos.length} 张已选择)
              </label>
              <div className="grid grid-cols-3 gap-2 max-h-48 overflow-y-auto">
                {model.photos.map((photo) => (
                  <div
                    key={photo.id}
                    className={`relative cursor-pointer rounded-lg overflow-hidden border-2 transition-all duration-200 ${
                      selectedPhotos.includes(photo.id)
                        ? 'border-red-500 ring-2 ring-red-200'
                        : 'border-gray-200 hover:border-gray-300'
                    }`}
                    onClick={() => handlePhotoToggle(photo.id)}
                  >
                    <img
                      src={photo.file_path}
                      alt={photo.file_name}
                      className="w-full h-20 object-cover"
                    />
                    {selectedPhotos.includes(photo.id) && (
                      <div className="absolute inset-0 bg-red-500 bg-opacity-20 flex items-center justify-center">
                        <div className="w-6 h-6 bg-red-500 rounded-full flex items-center justify-center">
                          <span className="text-white text-xs font-bold">✓</span>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>

            {/* 生成配置 */}
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">产品</label>
                <select
                  value={promptConfig.product}
                  onChange={(e) => handleConfigChange('product', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-red-500"
                >
                  <option value="">选择产品</option>
                  {PRODUCT_OPTIONS.map(option => (
                    <option key={String(option)} value={String(option)}>{String(option)}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">场景</label>
                <select
                  value={promptConfig.scene}
                  onChange={(e) => handleConfigChange('scene', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-red-500"
                >
                  <option value="">选择场景</option>
                  {SCENE_OPTIONS.map(option => (
                    <option key={String(option)} value={String(option)}>{String(option)}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">模板</label>
                <select
                  value={promptConfig.template}
                  onChange={(e) => handleConfigChange('template', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-red-500"
                >
                  {TEMPLATE_OPTIONS.map(option => (
                    <option key={String(option)} value={String(option)}>{String(option)}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">生成数量</label>
                <input
                  type="number"
                  min="1"
                  max="5"
                  value={promptConfig.duplicate}
                  onChange={(e) => handleConfigChange('duplicate', parseInt(e.target.value) || 1)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-red-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">模特描述</label>
                <textarea
                  value={promptConfig.model_desc}
                  onChange={(e) => handleConfigChange('model_desc', e.target.value)}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-red-500"
                  placeholder="描述模特的特征..."
                />
              </div>

              {/* 生成按钮 */}
              <button
                onClick={onGenerateVideo}
                disabled={isGenerating || selectedPhotos.length === 0}
                className="w-full flex items-center justify-center px-4 py-3 bg-gradient-to-r from-red-500 to-red-600 text-white rounded-xl hover:from-red-600 hover:to-red-700 disabled:opacity-50 disabled:cursor-not-allowed shadow-sm hover:shadow-md transition-all duration-200 font-medium"
              >
                {isGenerating ? (
                  <>
                    <LoadingSpinner size="small" className="mr-2" />
                    生成中...
                  </>
                ) : (
                  <>
                    <PlayIcon className="w-5 h-5 mr-2" />
                    生成视频
                  </>
                )}
              </button>
            </div>
          </div>
        </div>

        {/* 视频生成任务 */}
        <div className="bg-gradient-to-br from-white to-gray-50/30 rounded-2xl shadow-sm border border-gray-200/50 p-6 hover:shadow-md transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
          <div className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-gray-100/50 to-gray-200/50 rounded-full -translate-y-8 translate-x-8 opacity-50"></div>

          <div className="relative z-10">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center">
                <div className="w-10 h-10 bg-gradient-to-br from-gray-500 to-gray-600 rounded-xl flex items-center justify-center text-white mr-3">
                  <span className="text-lg">📋</span>
                </div>
                <h3 className="text-lg font-semibold text-gray-900">生成任务</h3>
              </div>
              <button
                onClick={onRefreshTasks}
                className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors duration-200"
                title="刷新任务列表"
              >
                <ArrowPathIcon className="w-5 h-5" />
              </button>
            </div>

            {videoTasks.length === 0 ? (
              <div className="text-center py-8">
                <div className="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-3">
                  <span className="text-xl">🎬</span>
                </div>
                <p className="text-gray-500 text-sm">还没有视频生成任务</p>
                <p className="text-gray-400 text-xs mt-1">配置参数后点击生成视频开始</p>
              </div>
            ) : (
              <div className="space-y-3 max-h-96 overflow-y-auto">
                {videoTasks.map((task) => {
                  const statusConfig = VIDEO_GENERATION_STATUS_CONFIG[task.status];
                  const StatusIcon = getVideoTaskStatusIcon(task.status);
                  return (
                    <div
                      key={task.id}
                      className="flex items-center justify-between p-3 bg-white rounded-lg border border-gray-200 hover:border-gray-300 transition-colors duration-200"
                    >
                      <div className="flex items-center space-x-3 flex-1">
                        <div className={`w-8 h-8 rounded-full flex items-center justify-center ${statusConfig.bgColor}`}>
                          <StatusIcon className={`w-4 h-4 ${statusConfig.color}`} />
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2">
                            <span className="text-sm font-medium text-gray-900 truncate">
                              {task.prompt_config.product} - {task.prompt_config.scene}
                            </span>
                            <span className={`px-2 py-0.5 text-xs font-medium rounded-full ${statusConfig.bgColor} ${statusConfig.color}`}>
                              {statusConfig.label}
                            </span>
                          </div>
                          <div className="text-xs text-gray-500 mt-1">
                            {new Date(task.created_at).toLocaleString()} • {task.selected_photos.length} 张照片
                          </div>
                        </div>
                      </div>

                      <div className="flex items-center space-x-2">
                        {task.result?.video_urls && task.result.video_urls.length > 0 && (
                          <button
                            onClick={() => {
                              // 打开视频文件
                              if (task.result?.video_paths && task.result.video_paths[0]) {
                                invoke('open_file_in_explorer', { path: task.result.video_paths[0] });
                              }
                            }}
                            className="p-1.5 text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded transition-colors duration-200"
                            title="查看视频"
                          >
                            <EyeIcon className="w-4 h-4" />
                          </button>
                        )}
                        <button
                          onClick={() => onDeleteTask(task.id)}
                          className="p-1.5 text-red-600 hover:text-red-700 hover:bg-red-50 rounded transition-colors duration-200"
                          title="删除任务"
                        >
                          <TrashIcon className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default ModelVideoTab;
