import React, { useState, useEffect } from 'react'
import { invoke } from '@tauri-apps/api/core'
import { useNavigate } from 'react-router-dom'
import { TemplateService } from '../services/tauri'
import { useTemplateProgress } from '../hooks/useProgressCommand'
import type { TemplateInfo } from '../hooks/useProgressCommand'
import {
  SearchAndFilters,
  TemplateGrid,
  ImportProgressModal
} from '../components/template'

// 这些接口已移动到 TemplateDetailPage.tsx

const TemplateManagePage: React.FC = () => {
  const navigate = useNavigate()

  // State
  const [templates, setTemplates] = useState<TemplateInfo[]>([])
  const [loading, setLoading] = useState(false)
  const [searchTerm, setSearchTerm] = useState('')
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid')
  const [showImportModal, setShowImportModal] = useState(false)

  // Use the progress hook for template operations
  const {
    isExecuting: importing,
    progress: importProgress,
    result: importResult,
    logs: importLogs,
    batchImport,
    reset: resetImport
  } = useTemplateProgress({
    onSuccess: async (result) => {
      if (result.status && result.imported_count > 0) {
        await loadTemplates() // Reload templates after successful import
      }
    }
  })

  // Load templates on component mount
  useEffect(() => {
    loadTemplates()
  }, [])

  // Helper functions
  const formatDuration = (duration: number) => {
    const seconds = Math.floor(duration / 1000000)
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
  }



  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN')
  }

  // Filter templates based on search term
  const filteredTemplates = templates.filter(template =>
    template.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    template.description.toLowerCase().includes(searchTerm.toLowerCase())
  )

  // API functions
  const loadTemplates = async () => {
    try {
      setLoading(true)
      const result = await TemplateService.getTemplates()
      if (result.status) {
        setTemplates(result.templates || [])
      } else {
        console.error('Failed to load templates:', result.msg)
        setTemplates([])
      }
    } catch (error) {
      console.error('Error loading templates:', error)
      setTemplates([])
    } finally {
      setLoading(false)
    }
  }

  // 导航到模板详情页面
  const viewTemplateDetail = (template: TemplateInfo) => {
    navigate(`/templates/${template.id}`)
  }

  const handleBatchImport = async () => {
    try {
      const folderResult = await invoke<string>('select_folder')
      if (!folderResult) return

      setShowImportModal(true)
      await batchImport(folderResult)
    } catch (error) {
      console.error('Import failed:', error)
    }
  }

  const handleDeleteTemplate = async (templateId: string) => {
    if (!confirm('确定要删除这个模板吗？此操作不可撤销。')) return

    try {
      const result = await TemplateService.deleteTemplate(templateId)
      if (result.status) {
        setTemplates(templates.filter(t => t.id !== templateId))
      } else {
        alert('删除失败: ' + result.msg)
      }
    } catch (error) {
      console.error('Delete failed:', error)
      alert('删除失败: ' + (error instanceof Error ? error.message : 'Unknown error'))
    }
  }

  const handleCloseImportModal = () => {
    setShowImportModal(false)
    resetImport()
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900">模板管理</h1>
          <p className="text-gray-600">管理和导入视频编辑模板</p>
        </div>

        {/* Search and Filters */}
        <SearchAndFilters
          searchTerm={searchTerm}
          setSearchTerm={setSearchTerm}
          viewMode={viewMode}
          setViewMode={setViewMode}
          onBatchImport={handleBatchImport}
          loading={loading}
        />

        {/* Template Grid */}
        <TemplateGrid
          templates={filteredTemplates}
          viewMode={viewMode}
          loading={loading}
          onView={viewTemplateDetail}
          onDelete={handleDeleteTemplate}
          formatDuration={formatDuration}
          formatDate={formatDate}
        />

        {/* Import Progress Modal */}
        <ImportProgressModal
          isOpen={showImportModal}
          isExecuting={importing}
          progress={importProgress}
          result={importResult}
          logs={importLogs}
          onClose={handleCloseImportModal}
        />
      </div>
    </div>
  )
}

export default TemplateManagePage
