/**
 * 一键混剪悬浮按钮组件
 * 提供快速混剪功能的入口
 */

import React, { useState } from 'react'
import { Scissors, Settings, Play, X, Loader } from 'lucide-react'
import { Project } from '../services/projectService'
import { VideoSegment } from '../services/mediaService'
import { Model } from '../services/modelService'
import { MixEditService, MixEditConfig, MixEditResult } from '../services/mixEditService'
import MixEditConfigModal from './MixEditConfigModal'

interface MixEditFloatingButtonProps {
  project: Project
  materials: VideoSegment[]
  models: Model[]
  onMixEditComplete?: (result: MixEditResult) => void
}

const MixEditFloatingButton: React.FC<MixEditFloatingButtonProps> = ({
  project,
  materials,
  models,
  onMixEditComplete
}) => {
  const [isExpanded, setIsExpanded] = useState(false)
  const [showConfigModal, setShowConfigModal] = useState(false)
  const [isProcessing, setIsProcessing] = useState(false)
  const [processingMessage, setProcessingMessage] = useState('')

  // 快速混剪（使用默认配置）
  const handleQuickMixEdit = async () => {
    if (materials.length === 0) {
      alert('没有可用的素材，请先添加一些视频素材')
      return
    }

    setIsProcessing(true)
    setProcessingMessage('正在准备混剪...')
    setIsExpanded(false)

    try {
      const defaultConfig = MixEditService.getDefaultConfig()
      const result = await MixEditService.startMixEdit(project, defaultConfig, materials, models)
      
      if (result.success) {
        setProcessingMessage('混剪完成！')
        setTimeout(() => {
          setIsProcessing(false)
          onMixEditComplete?.(result)
        }, 1500)
      } else {
        alert(`混剪失败: ${result.message}`)
        setIsProcessing(false)
      }
    } catch (error) {
      console.error('Quick mix edit failed:', error)
      alert(`混剪失败: ${error}`)
      setIsProcessing(false)
    }
  }

  // 自定义混剪
  const handleCustomMixEdit = () => {
    if (materials.length === 0) {
      alert('没有可用的素材，请先添加一些视频素材')
      return
    }
    
    setShowConfigModal(true)
    setIsExpanded(false)
  }

  // 处理自定义混剪配置完成
  const handleConfigComplete = async (config: MixEditConfig) => {
    setShowConfigModal(false)
    setIsProcessing(true)
    setProcessingMessage('正在开始混剪...')

    try {
      const result = await MixEditService.startMixEdit(project, config, materials, models)
      
      if (result.success) {
        setProcessingMessage('混剪完成！')
        setTimeout(() => {
          setIsProcessing(false)
          onMixEditComplete?.(result)
        }, 1500)
      } else {
        alert(`混剪失败: ${result.message}`)
        setIsProcessing(false)
      }
    } catch (error) {
      console.error('Custom mix edit failed:', error)
      alert(`混剪失败: ${error}`)
      setIsProcessing(false)
    }
  }

  // 如果正在处理，显示处理状态
  if (isProcessing) {
    return (
      <div className="fixed bottom-8 right-8 z-50">
        <div className="bg-blue-600 text-white px-6 py-4 rounded-full shadow-lg flex items-center space-x-3">
          <Loader className="w-5 h-5 animate-spin" />
          <span className="font-medium">{processingMessage}</span>
        </div>
      </div>
    )
  }

  return (
    <>
      <div className="fixed bottom-8 right-8 z-50">
        {/* 展开的选项 */}
        {isExpanded && (
          <div className="mb-4 space-y-3">
            {/* 自定义混剪按钮 */}
            <button
              onClick={handleCustomMixEdit}
              className="flex items-center space-x-3 bg-white text-gray-700 px-4 py-3 rounded-full shadow-lg hover:shadow-xl transition-all duration-200 transform hover:scale-105"
            >
              <Settings className="w-5 h-5" />
              <span className="font-medium">自定义混剪</span>
            </button>

            {/* 快速混剪按钮 */}
            <button
              onClick={handleQuickMixEdit}
              className="flex items-center space-x-3 bg-green-600 text-white px-4 py-3 rounded-full shadow-lg hover:shadow-xl transition-all duration-200 transform hover:scale-105"
            >
              <Play className="w-5 h-5" />
              <span className="font-medium">快速混剪</span>
            </button>
          </div>
        )}

        {/* 主按钮 */}
        <button
          onClick={() => setIsExpanded(!isExpanded)}
          className={`w-16 h-16 rounded-full shadow-lg hover:shadow-xl transition-all duration-200 transform hover:scale-105 flex items-center justify-center ${
            isExpanded 
              ? 'bg-gray-600 text-white rotate-45' 
              : 'bg-blue-600 text-white'
          }`}
        >
          {isExpanded ? (
            <X className="w-6 h-6" />
          ) : (
            <Scissors className="w-6 h-6" />
          )}
        </button>

        {/* 提示文字 */}
        {!isExpanded && (
          <div className="absolute bottom-full right-0 mb-2 bg-gray-800 text-white text-xs px-2 py-1 rounded whitespace-nowrap opacity-0 hover:opacity-100 transition-opacity duration-200 pointer-events-none">
            一键混剪
          </div>
        )}
      </div>

      {/* 配置模态框 */}
      {showConfigModal && (
        <MixEditConfigModal
          project={project}
          materials={materials}
          models={models}
          onConfirm={handleConfigComplete}
          onCancel={() => setShowConfigModal(false)}
        />
      )}
    </>
  )
}

export default MixEditFloatingButton
