import { useState, useCallback, useRef, useEffect } from 'react'
import { listen, UnlistenFn } from '@tauri-apps/api/event'
import { TemplateServiceV2, type BatchImportResult } from '../services/TemplateServiceV2'

// 进度信息接口
export interface ProgressInfo {
  current: number
  total: number
  message: string
  percentage: number
}

// Hook选项
export interface UseTemplateProgressOptions {
  onSuccess?: (result: BatchImportResult) => void
  onError?: (error: Error) => void
  onProgress?: (progress: ProgressInfo) => void
}

// Hook返回值
export interface UseTemplateProgressReturn {
  isExecuting: boolean
  progress: ProgressInfo | null
  result: BatchImportResult | null
  error: Error | null
  logs: string[]
  batchImport: (sourceFolder: string, userId?: string) => Promise<void>
  reset: () => void
}

export const useTemplateProgressV2 = (options: UseTemplateProgressOptions = {}): UseTemplateProgressReturn => {
  const [isExecuting, setIsExecuting] = useState(false)
  const [progress, setProgress] = useState<ProgressInfo | null>(null)
  const [result, setResult] = useState<BatchImportResult | null>(null)
  const [error, setError] = useState<Error | null>(null)
  const [logs, setLogs] = useState<string[]>([])
  
  const unlistenRef = useRef<UnlistenFn | null>(null)
  const { onSuccess, onError, onProgress } = options

  // 清理监听器
  const cleanup = useCallback(async () => {
    if (unlistenRef.current) {
      await unlistenRef.current()
      unlistenRef.current = null
    }
  }, [])

  // 重置状态
  const reset = useCallback(() => {
    setIsExecuting(false)
    setProgress(null)
    setResult(null)
    setError(null)
    setLogs([])
    cleanup()
  }, [cleanup])

  // 添加日志
  const addLog = useCallback((message: string) => {
    const timestamp = new Date().toLocaleTimeString()
    setLogs(prev => [...prev, `[${timestamp}] ${message}`])
  }, [])

  // 更新进度
  const updateProgress = useCallback((current: number, total: number, message: string) => {
    const percentage = total > 0 ? Math.round((current / total) * 100) : 0
    const progressInfo: ProgressInfo = {
      current,
      total,
      message,
      percentage
    }
    
    setProgress(progressInfo)
    addLog(`进度: ${current}/${total} (${percentage}%) - ${message}`)
    
    if (onProgress) {
      onProgress(progressInfo)
    }
  }, [addLog, onProgress])

  // 批量导入模板
  const batchImport = useCallback(async (sourceFolder: string, userId?: string) => {
    try {
      setIsExecuting(true)
      setError(null)
      setResult(null)
      setProgress(null)
      setLogs([])
      
      addLog(`开始批量导入模板: ${sourceFolder}`)
      
      // 监听进度事件
      unlistenRef.current = await listen('template-import-progress', (event: any) => {
        const { current, total, message } = event.payload
        updateProgress(current, total, message)
      })

      // 执行导入
      const importResult = await TemplateServiceV2.batchImportTemplates(sourceFolder, userId)
      
      setResult(importResult)
      addLog(`导入完成: 成功 ${importResult.imported_count} 个，失败 ${importResult.failed_count} 个`)
      
      // 显示详细结果
      if (importResult.imported_templates.length > 0) {
        addLog('成功导入的模板:')
        importResult.imported_templates.forEach(template => {
          addLog(`  ✓ ${template.name} (${template.id})`)
        })
      }
      
      if (importResult.failed_templates.length > 0) {
        addLog('导入失败的模板:')
        importResult.failed_templates.forEach(failed => {
          addLog(`  ✗ ${failed.name}: ${failed.error}`)
        })
      }
      
      if (onSuccess) {
        onSuccess(importResult)
      }
      
    } catch (err) {
      const error = err instanceof Error ? err : new Error(String(err))
      setError(error)
      addLog(`导入失败: ${error.message}`)
      
      if (onError) {
        onError(error)
      }
    } finally {
      setIsExecuting(false)
      cleanup()
    }
  }, [addLog, updateProgress, onSuccess, onError, cleanup])

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      cleanup()
    }
  }, [cleanup])

  return {
    isExecuting,
    progress,
    result,
    error,
    logs,
    batchImport,
    reset
  }
}

// 简化版本的进度Hook，用于其他操作
export const useTemplateOperationV2 = () => {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<Error | null>(null)

  const execute = useCallback(async <T>(operation: () => Promise<T>): Promise<T | null> => {
    try {
      setLoading(true)
      setError(null)
      const result = await operation()
      return result
    } catch (err) {
      const error = err instanceof Error ? err : new Error(String(err))
      setError(error)
      return null
    } finally {
      setLoading(false)
    }
  }, [])

  const reset = useCallback(() => {
    setLoading(false)
    setError(null)
  }, [])

  return {
    loading,
    error,
    execute,
    reset
  }
}

// 模板搜索Hook
export const useTemplateSearchV2 = () => {
  const [searchResults, setSearchResults] = useState<any[]>([])
  const [searching, setSearching] = useState(false)
  const [searchError, setSearchError] = useState<Error | null>(null)

  const search = useCallback(async (
    query: string, 
    includeCloud: boolean = true, 
    limit: number = 50,
    userId?: string
  ) => {
    try {
      setSearching(true)
      setSearchError(null)
      
      if (!query.trim()) {
        setSearchResults([])
        return
      }

      const results = await TemplateServiceV2.searchTemplates(query, includeCloud, limit, userId)
      setSearchResults(results)
    } catch (err) {
      const error = err instanceof Error ? err : new Error(String(err))
      setSearchError(error)
      setSearchResults([])
    } finally {
      setSearching(false)
    }
  }, [])

  const searchByTag = useCallback(async (
    tag: string,
    includeCloud: boolean = true,
    limit: number = 50,
    userId?: string
  ) => {
    try {
      setSearching(true)
      setSearchError(null)
      
      const results = await TemplateServiceV2.getTemplatesByTag(tag, includeCloud, limit, userId)
      setSearchResults(results)
    } catch (err) {
      const error = err instanceof Error ? err : new Error(String(err))
      setSearchError(error)
      setSearchResults([])
    } finally {
      setSearching(false)
    }
  }, [])

  const clearSearch = useCallback(() => {
    setSearchResults([])
    setSearchError(null)
  }, [])

  return {
    searchResults,
    searching,
    searchError,
    search,
    searchByTag,
    clearSearch
  }
}

// 模板统计Hook
export const useTemplateStatsV2 = () => {
  const [stats, setStats] = useState<any>(null)
  const [popularTags, setPopularTags] = useState<any[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<Error | null>(null)

  const loadStats = useCallback(async (userId?: string) => {
    try {
      setLoading(true)
      setError(null)
      
      const [statsResult, tagsResult] = await Promise.all([
        TemplateServiceV2.getTemplateStats(userId),
        TemplateServiceV2.getPopularTags(20, userId)
      ])
      
      setStats(statsResult)
      setPopularTags(tagsResult)
    } catch (err) {
      const error = err instanceof Error ? err : new Error(String(err))
      setError(error)
    } finally {
      setLoading(false)
    }
  }, [])

  const refresh = useCallback((userId?: string) => {
    loadStats(userId)
  }, [loadStats])

  return {
    stats,
    popularTags,
    loading,
    error,
    loadStats,
    refresh
  }
}
