import { View } from '@tarojs/components'
import { useState } from 'react'
import { navigateTo } from '@tarojs/taro'
import './index.css'
import { useSdk, useUploadVideo } from '../../hooks/index'
import UploadButton from '../../components/UploadButton'
import LoadingOverlay from '../../components/LoadingOverlay'
import ErrorOverlay from '../../components/ErrorOverlay'
import { createPlatformFactory } from '../../platforms'

type PageStep = 'upload' | 'loading' | 'error'

interface AppState {
  step: PageStep;
  error: string | null;
}

export default function Index() {
  const sdk = useSdk()
  const [state, setState] = useState<AppState>({
    step: 'upload',
    error: null
  })

  const [videoPath, setVidePath] = useState<string>()

  useUploadVideo((res) => {
    console.log(res)
    return {
      videoPath: videoPath,
      titleConfig: {
        title: `视频发布`
      },
      success() {
        console.log("视频发布/挂载成功");
      },
      fail() {
        console.log("视频发布/挂载失败");
      },
    }
  })

  const chooseAndGenerateImage = async () => {
    try {
      // 选择图片，选择完成后会自动触发loading状态
      const task_id = await sdk.chooseAndGenerateImage({
        onImageSelected: () => {
          // 选择图片完成后立即显示loading
          setState({ step: 'loading', error: null })
        }
      })

      // 等待生成完成
      await new Promise((resolve) => setTimeout(resolve, 5000))
      const urls = await sdk.getTaskStatus(task_id)

      // 跳转到结果页面
      navigateTo({
        url: `/pages/result/index?images=${encodeURIComponent(JSON.stringify(urls))}`
      })

      // 重置状态
      setState({ step: 'upload', error: null })
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : '生成失败'
      setState({ step: 'error', error: errorMsg })
    }
  }

  

  const resetToUpload = () => {
    setState({ step: 'upload', error: null })
  }

  const renderCurrentStep = () => {
    switch (state.step) {
      case 'upload':
        return <UploadButton onUpload={chooseAndGenerateImage} />
      case 'loading':
        return <LoadingOverlay />
      case 'error':
        return <ErrorOverlay onRetry={resetToUpload} />
      default:
        return <UploadButton onUpload={chooseAndGenerateImage} />
    }
  }

  return (
    <View className='index'>
      {renderCurrentStep()}
    </View>
  )
}
