import React, { useState } from 'react'
import { X, Download, ExternalLink, Play, Folder } from 'lucide-react'
import { invoke } from '@tauri-apps/api/core'

interface VideoResult {
  status?: boolean
  video_path?: string
  video_url?: string
  msg?: string
}

interface BatchResult {
  status: boolean
  success_count: number
  failed_count: number
  results: Array<{
    image_path: string
    prompt: string
    result: VideoResult
  }>
  msg: string
}

interface AIVideoResultPreviewProps {
  isOpen: boolean
  onClose: () => void
  result: VideoResult | BatchResult
  jobType: 'single' | 'batch'
  prompt?: string
  imagePath?: string
}

const AIVideoResultPreview: React.FC<AIVideoResultPreviewProps> = ({ 
  isOpen, 
  onClose, 
  result, 
  jobType,
  prompt,
  imagePath
}) => {
  const [selectedVideoIndex, setSelectedVideoIndex] = useState(0)
  const [videoError, setVideoError] = useState(false)

  if (!isOpen) return null

  const handleVideoError = () => setVideoError(true)

  const handleOpenFolder = async (videoPath: string) => {
    try {
      // Extract folder path
      const folderPath = videoPath.substring(0, videoPath.lastIndexOf('\\') || videoPath.lastIndexOf('/'))
      console.log('Opening folder:', folderPath)

      // Try to open folder using Tauri command
      try {
        await invoke('open_folder', { folderPath })
        console.log('Folder opened successfully')
      } catch (tauriError) {
        console.error('Failed to open folder via Tauri:', tauriError)
        // Fallback to showing path
        alert(`视频已保存到: ${videoPath}\n\n文件夹: ${folderPath}`)
      }
    } catch (error) {
      console.error('Failed to open folder:', error)
      alert(`无法打开文件夹: ${error}`)
    }
  }

  const handleOpenUrl = (url: string) => {
    window.open(url, '_blank')
  }

  // Render single video result
  const renderSingleVideo = (videoResult: VideoResult, videoPrompt?: string, videoImagePath?: string) => (
    <div className="space-y-4">
      {/* Video Player */}
      <div className="relative bg-black rounded-lg overflow-hidden">
        {videoError ? (
          <div className="aspect-video flex items-center justify-center text-white">
            <div className="text-center">
              <div className="text-red-400 mb-2">视频加载失败</div>
              <div className="text-sm text-gray-400">
                请尝试下载到本地查看
              </div>
            </div>
          </div>
        ) : (
          <video
            className="w-full aspect-video"
            controls
            preload="metadata"
            onError={handleVideoError}
            poster={videoImagePath}
          >
            <source src={videoResult.video_url} type="video/mp4" />
            您的浏览器不支持视频播放。
          </video>
        )}
      </div>

      {/* Video Info */}
      <div className="space-y-3">
        {videoPrompt && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              生成提示词
            </label>
            <div className="text-sm text-gray-600 bg-gray-50 p-3 rounded">
              {videoPrompt}
            </div>
          </div>
        )}

        {videoResult.video_path && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              本地路径
            </label>
            <div className="text-sm text-gray-600 bg-gray-50 p-3 rounded font-mono">
              {videoResult.video_path}
            </div>
          </div>
        )}

        {videoResult.msg && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              状态信息
            </label>
            <div className="text-sm text-green-600 bg-green-50 p-3 rounded">
              {videoResult.msg}
            </div>
          </div>
        )}
      </div>

      {/* Actions */}
      <div className="flex gap-3 pt-4 border-t">
        {videoResult.video_path && (
          <button
            onClick={() => handleOpenFolder(videoResult.video_path!)}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Folder size={16} />
            打开文件夹
          </button>
        )}
      </div>
    </div>
  )

  // Render batch results
  const renderBatchResults = (batchResult: BatchResult) => {
    const successResults = batchResult.results.filter(r => r.result.status)
    
    if (successResults.length === 0) {
      return (
        <div className="text-center py-8">
          <div className="text-gray-500">没有成功生成的视频</div>
        </div>
      )
    }

    const currentResult = successResults[selectedVideoIndex]

    return (
      <div className="space-y-4">
        {/* Batch Summary */}
        <div className="bg-blue-50 p-4 rounded-lg">
          <div className="text-sm font-medium text-blue-900 mb-2">批量处理结果</div>
          <div className="text-sm text-blue-700">
            总共处理: {batchResult.results.length} 个 | 
            成功: {batchResult.success_count} 个 | 
            失败: {batchResult.failed_count} 个
          </div>
        </div>

        {/* Video Selector */}
        {successResults.length > 1 && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              选择视频 ({selectedVideoIndex + 1}/{successResults.length})
            </label>
            <div className="flex gap-2 overflow-x-auto pb-2">
              {successResults.map((_, index) => (
                <button
                  key={index}
                  onClick={() => setSelectedVideoIndex(index)}
                  className={`flex-shrink-0 px-3 py-2 text-sm rounded-lg border ${
                    selectedVideoIndex === index
                      ? 'bg-blue-600 text-white border-blue-600'
                      : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'
                  }`}
                >
                  视频 {index + 1}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Current Video */}
        {currentResult && renderSingleVideo(
          currentResult.result, 
          currentResult.prompt, 
          currentResult.image_path
        )}
      </div>
    )
  }

  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">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b">
          <h3 className="text-lg font-semibold text-gray-900">
            {jobType === 'batch' ? '批量生成结果' : '视频生成结果'}
          </h3>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X size={24} />
          </button>
        </div>

        {/* Content */}
        <div className="p-6">
          {jobType === 'batch' ? 
            renderBatchResults(result as BatchResult) : 
            renderSingleVideo(result as VideoResult, prompt, imagePath)
          }
          
          {/* Close Button */}
          <div className="flex justify-end mt-6 pt-4 border-t">
            <button
              onClick={onClose}
              className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
            >
              关闭
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

export default AIVideoResultPreview
