import { useEffect, useState } from 'react'
import { Progress, Button, Tag, Alert, message, Space } from 'antd'
import { CheckCircleOutlined, LoadingOutlined, CloseCircleOutlined, RightOutlined, WarningOutlined } from '@ant-design/icons'
import { InstallConfig, InstallProgress, InstalledVersion } from '../types'

interface InstallingProps {
  config: InstallConfig
  onComplete: () => void
  installedVersion?: InstalledVersion
  isUpgrade?: boolean
}

interface StepProgress {
  step: string
  label: string
  status: 'pending' | 'running' | 'success' | 'failed' | 'warning'
  progress: number
  message?: string
  details?: string
  startTime?: number
  endTime?: number
}

// 升级安装步骤（有备份步骤）
const UPGRADE_STEPS = [
  { key: 'uninstall', label: '备份老版本', description: '将老版本程序文件移至 backup 目录' },
  { key: 'copy', label: '复制新版本', description: '复制新版本程序文件到安装目录' },
  { key: 'dbcheck', label: '检测数据库变更', description: '检查是否需要执行数据库迁移' },
  { key: 'migration', label: '数据库迁移', description: '执行 SQLite 数据库迁移脚本' },
  { key: 'config', label: '生成配置文件', description: '合并用户配置与模板配置' },
  { key: 'shortcut', label: '创建快捷方式', description: '创建桌面和开始菜单快捷方式' },
  { key: 'registry', label: '写入注册表', description: '注册安装信息到系统' },
]

// 首次安装步骤（无备份步骤，但有数据库初始化）
const INSTALL_STEPS = [
  { key: 'copy', label: '复制文件', description: '复制应用程序文件到安装目录' },
  { key: 'dbcheck', label: '检测数据库变更', description: '检查数据库初始化脚本' },
  { key: 'migration', label: '数据库初始化', description: '执行数据库初始化脚本' },
  { key: 'config', label: '生成配置文件', description: '创建默认配置文件' },
  { key: 'shortcut', label: '创建快捷方式', description: '创建桌面和开始菜单快捷方式' },
  { key: 'registry', label: '写入注册表', description: '注册安装信息到系统' },
]

// 合并所有步骤定义（用于查找步骤详情）
const ALL_STEPS = [...UPGRADE_STEPS, ...INSTALL_STEPS.filter(s => !UPGRADE_STEPS.find(u => u.key === s.key))]

export default function Installing({ config, onComplete, isUpgrade }: InstallingProps) {
  // 根据 isUpgrade 选择步骤列表
  const currentSteps = isUpgrade ? UPGRADE_STEPS : INSTALL_STEPS

  const [steps, setSteps] = useState<StepProgress[]>(
    currentSteps.map(s => ({
      step: s.key,
      label: s.label,
      status: 'pending',
      progress: 0
    }))
  )
  const [installError, setInstallError] = useState<string | null>(null)
  const [installComplete, setInstallComplete] = useState(false)
  const [expandedSteps, setExpandedSteps] = useState<string[]>([])
  const [failedStep, setFailedStep] = useState<string | null>(null)  // 记录失败的步骤
  const [isRetrying, setIsRetrying] = useState(false)  // 是否正在重试

  useEffect(() => {
    let isMounted = true

    // 监听安装进度
    window.electronAPI.onInstallProgress((progress: InstallProgress) => {
      if (!isMounted) return

      console.log('[Install Progress]', progress)

      setSteps(prev => prev.map(s => {
        if (s.step === progress.step) {
          return {
            ...s,
            status: progress.status,
            progress: progress.progress || 0,
            message: progress.message,
            details: progress.details,
            endTime: progress.status !== 'running' ? Date.now() : undefined,
            startTime: s.startTime || (progress.status === 'running' ? Date.now() : undefined)
          }
        }
        return s
      }))

      if (progress.status === 'failed') {
        setInstallError(progress.message || `${progress.step} 失败`)
        setFailedStep(progress.step)  // 记录失败步骤
      }

      // 只有在没有错误且 registry 成功时才完成
      if (progress.status === 'success' && progress.step === 'registry' && !installError) {
        setInstallComplete(true)
        // 不自动跳转，让用户点击完成
      }
    })

    // 启动安装（非重试时才执行）
    if (!isRetrying) {
      console.log('Starting installation with config:', config)
      window.electronAPI.startInstallation(config).then(result => {
        if (!isMounted) return
        console.log('Installation result:', result)

        if (!result.success) {
          setInstallError(result.error || '安装失败')
          message.error(result.error || '安装失败')
        }
      }).catch(err => {
        if (!isMounted) return
        console.error('Installation error:', err)
        setInstallError(err.message || '安装过程出错')
      })
    }

    return () => {
      isMounted = false
    }
  }, [config, isRetrying])

  // 重试安装
  const handleRetry = async () => {
    console.log('Retrying installation...')
    setIsRetrying(true)
    setInstallError(null)
    setFailedStep(null)
    setInstallComplete(false)

    // 重置步骤状态（保留已成功的不变，只重置失败及之后的步骤）
    setSteps(prev => prev.map(s => {
      if (s.status === 'failed' || s.status === 'pending') {
        return { ...s, status: 'pending', progress: 0, message: undefined, details: undefined }
      }
      return s
    }))

    // 重新启动安装
    window.electronAPI.startInstallation(config).then(result => {
      if (!result.success) {
        setInstallError(result.error || '安装失败')
        message.error(result.error || '安装失败')
      }
      setIsRetrying(false)
    }).catch(err => {
      console.error('Retry error:', err)
      setInstallError(err.message || '安装过程出错')
      setIsRetrying(false)
    })
  }

  const getStepIcon = (status: string) => {
    switch (status) {
      case 'success': return <CheckCircleOutlined style={{ color: '#52c41a', fontSize: 18 }} />
      case 'running': return <LoadingOutlined style={{ color: '#10b981', fontSize: 18 }} spin />
      case 'failed': return <CloseCircleOutlined style={{ color: '#ff4d4f', fontSize: 18 }} />
      case 'warning': return <WarningOutlined style={{ color: '#faad14', fontSize: 18 }} />
      default: return <span style={{ color: '#d9d9d9', fontSize: 18 }}>○</span>
    }
  }

  const getStepTag = (status: string) => {
    switch (status) {
      case 'success': return <Tag color="success">完成</Tag>
      case 'running': return <Tag color="processing">进行中</Tag>
      case 'failed': return <Tag color="error">失败</Tag>
      case 'warning': return <Tag color="warning">注意</Tag>
      default: return <Tag color="default">等待中</Tag>
    }
  }

  const toggleStepExpand = (stepKey: string) => {
    setExpandedSteps(prev =>
      prev.includes(stepKey)
        ? prev.filter(s => s !== stepKey)
        : [...prev, stepKey]
    )
  }

  const handleClose = () => {
    window.electronAPI.closeWindow()
  }

  const handleComplete = () => {
    onComplete()
  }

  // 计算总体进度
  const completedSteps = steps.filter(s => s.status === 'success' || s.status === 'warning').length
  const totalProgress = Math.round((completedSteps / steps.length) * 100)

  // 数据库迁移提示：有迁移内容时显示
  const migrationStep = steps.find(s => s.step === 'migration')
  const showMigrationAlert = installComplete && !installError && migrationStep && migrationStep.details

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
      <h2 style={{ fontSize: 22, marginBottom: 8, color: '#333' }}>
        {installError ? (isUpgrade ? '升级失败' : '安装失败') :
         installComplete ? (isUpgrade ? '升级完成' : '安装完成') :
         (isUpgrade ? '正在升级...' : '正在安装...')}
      </h2>
      <p style={{ color: '#666', marginBottom: 20 }}>
        {installError ? '安装过程中遇到错误，请检查后重试' :
         installComplete ? '所有步骤已完成，请点击完成按钮继续' :
         '请稍候，安装程序正在配置您的系统'}
      </p>

      {/* 总体进度条 */}
      {!installError && (
        <div style={{ marginBottom: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
            <span>总体进度</span>
            <span>{completedSteps} / {steps.length} 步骤</span>
          </div>
          <Progress
            percent={totalProgress}
            status={installComplete ? 'success' : 'active'}
            strokeColor={{
              '0%': '#10b981',
              '100%': '#059669',
            }}
          />
        </div>
      )}

      {/* 数据库迁移提示 */}
      {showMigrationAlert && migrationStep && (
        <Alert
          type='success'
          showIcon
          style={{ marginBottom: 20 }}
          message='SQLite 数据库已自动迁移'
          description={
            <div>
              <p style={{ marginBottom: 8 }}>{migrationStep.message}</p>
              <pre style={{
                margin: 0,
                padding: 8,
                background: '#f6ffed',
                borderRadius: 4,
                fontSize: 12,
                fontFamily: 'Consolas, Monaco, monospace',
                whiteSpace: 'pre-wrap',
                wordBreak: 'break-word',
              }}>
                {migrationStep.details}
              </pre>
            </div>
          }
        />
      )}

      {/* 安装成功提示 */}
      {installComplete && !installError && (
        <Alert
          type="success"
          showIcon
          style={{ marginBottom: 20 }}
          message={isUpgrade ? '升级成功' : '安装成功'}
          description={
            <div>
              <p style={{ marginBottom: 8 }}>安装目录：{config.installDir}</p>
              <p style={{ marginBottom: 0 }}>请点击"完成"关闭安装程序，然后通过桌面快捷方式启动 Colink。</p>
            </div>
          }
        />
      )}

      {/* 安装错误提示 */}
      {installError && (
        <Alert
          type="error"
          showIcon
          style={{ marginBottom: 20 }}
          message="安装失败"
          description={
            <div>
              <p style={{ marginBottom: 8 }}>{installError}</p>
              {failedStep && (
                <div style={{ marginBottom: 8, color: '#666' }}>
                  <strong>处理建议：</strong>
                  {failedStep === 'uninstall' && '请检查是否有进程占用文件，可在任务管理器中结束 Colink.exe 和 colink-server.exe'}
                  {failedStep === 'copy' && '请检查磁盘空间是否充足，或是否有程序占用目标文件'}
                  {failedStep === 'migration' && '请检查数据库文件是否正常，可尝试手动执行数据库迁移脚本'}
                  {failedStep === 'config' && '请检查安装目录权限，确保可写入配置文件'}
                  {failedStep === 'shortcut' && '请检查桌面和开始菜单目录权限'}
                  {failedStep === 'registry' && '请检查注册表写入权限，可能需要管理员权限运行'}
                  {!['uninstall', 'copy', 'migration', 'config', 'shortcut', 'registry'].includes(failedStep) && '请检查错误信息，处理后点击重试'}
                </div>
              )}
              <p style={{ marginBottom: 0, color: '#999' }}>处理完成后，点击"重试"按钮继续安装</p>
            </div>
          }
        />
      )}

      {/* 步骤列表 */}
      <div style={{ flex: 1, overflow: 'auto' }}>
        {steps.map((step, index) => {
          const stepDef = ALL_STEPS.find(s => s.key === step.step)
          const isExpanded = expandedSteps.includes(step.step)
          const hasDetails = step.details || step.message || step.status === 'failed'

          return (
            <div
              key={step.step}
              style={{
                border: '1px solid #f0f0f0',
                borderRadius: 8,
                marginBottom: 8,
                overflow: 'hidden',
                background: step.status === 'running' ? '#f6ffed' : '#fff',
              }}
            >
              {/* 步骤头部 */}
              <div
                onClick={() => hasDetails && toggleStepExpand(step.step)}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 12,
                  padding: '12px 16px',
                  cursor: hasDetails ? 'pointer' : 'default',
                  transition: 'background 0.2s',
                }}
              >
                <div style={{ width: 24 }}>{getStepIcon(step.status)}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 500 }}>{step.label}</div>
                  {step.status === 'running' && step.message && (
                    <div style={{ fontSize: 12, color: '#666', marginTop: 2 }}>{step.message}</div>
                  )}
                </div>
                {step.status === 'running' && (
                  <div style={{ width: 120 }}>
                    <Progress percent={step.progress} size="small" />
                  </div>
                )}
                {getStepTag(step.status)}
                {hasDetails && (
                  <RightOutlined
                    style={{
                      fontSize: 12,
                      color: '#999',
                      transform: isExpanded ? 'rotate(90deg)' : 'rotate(0deg)',
                      transition: 'transform 0.2s'
                    }}
                  />
                )}
              </div>

              {/* 展开的详情 */}
              {isExpanded && hasDetails && (
                <div style={{
                  padding: '12px 16px',
                  background: '#fafafa',
                  borderTop: '1px solid #f0f0f0',
                }}>
                  {stepDef?.description && (
                    <div style={{ marginBottom: 8, color: '#666', fontSize: 13 }}>
                      {stepDef.description}
                    </div>
                  )}
                  {step.details && (
                    <pre style={{
                      margin: 0,
                      padding: 8,
                      background: '#fff',
                      borderRadius: 4,
                      fontSize: 12,
                      fontFamily: 'Consolas, Monaco, monospace',
                      whiteSpace: 'pre-wrap',
                      wordBreak: 'break-word',
                      border: '1px solid #e8e8e8',
                    }}>
                      {step.details}
                    </pre>
                  )}
                  {step.status === 'failed' && step.message && (
                    <div style={{ color: '#ff4d4f', fontSize: 13, marginTop: 8 }}>
                      错误信息：{step.message}
                    </div>
                  )}
                  {step.endTime && step.startTime && (
                    <div style={{ color: '#999', fontSize: 12, marginTop: 8 }}>
                      耗时：{((step.endTime - step.startTime) / 1000).toFixed(1)}s
                    </div>
                  )}
                </div>
              )}
            </div>
          )
        })}
      </div>

      {/* 底部按钮 */}
      <div style={{ marginTop: 24, textAlign: 'right' }}>
        {installError ? (
          <Space>
            <Button onClick={handleClose}>
              关闭
            </Button>
            <Button type="primary" onClick={handleRetry} loading={isRetrying}>
              重试
            </Button>
          </Space>
        ) : installComplete ? (
          <Button type="primary" size="large" onClick={handleComplete}>
            完成
          </Button>
        ) : null}
      </div>
    </div>
  )
}