import { useState } from 'react'
import { Upload, CheckCircle, AlertCircle } from 'lucide-react'
import type { CheckedAccount } from '../../types'
import { Button, Progress } from '../common'

interface PoolActionsProps {
  selectedAccounts: CheckedAccount[]
  onPool: (accounts: CheckedAccount[]) => Promise<{ success: number; failed: number }>
  disabled?: boolean
}

export default function PoolActions({
  selectedAccounts,
  onPool,
  disabled = false,
}: PoolActionsProps) {
  const [pooling, setPooling] = useState(false)
  const [progress, setProgress] = useState({ current: 0, total: 0 })
  const [result, setResult] = useState<{ success: number; failed: number } | null>(null)

  const activeSelected = selectedAccounts.filter((acc) => acc.status === 'active')
  const hasNonActive = selectedAccounts.some((acc) => acc.status !== 'active')

  const handlePool = async () => {
    if (selectedAccounts.length === 0) return

    setPooling(true)
    setProgress({ current: 0, total: selectedAccounts.length })
    setResult(null)

    try {
      const poolResult = await onPool(selectedAccounts)
      setResult(poolResult)
    } catch (error) {
      console.error('Pool error:', error)
      setResult({ success: 0, failed: selectedAccounts.length })
    } finally {
      setPooling(false)
    }
  }

  if (selectedAccounts.length === 0) {
    return (
      <div className="text-center py-4 text-slate-500 dark:text-slate-400">
        请先选择要入库的账号
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* Warning for non-active accounts */}
      {hasNonActive && (
        <div className="flex items-start gap-2 p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
          <AlertCircle className="h-5 w-5 text-yellow-600 dark:text-yellow-400 mt-0.5" />
          <div className="text-sm">
            <p className="font-medium text-yellow-800 dark:text-yellow-200">
              选中的账号包含非正常状态
            </p>
            <p className="text-yellow-700 dark:text-yellow-300">
              建议只入库状态为"正常"的账号，非正常账号可能无法正常使用
            </p>
          </div>
        </div>
      )}

      {/* Summary */}
      <div className="flex items-center justify-between p-4 bg-slate-50 dark:bg-slate-800 rounded-lg">
        <div>
          <p className="text-sm text-slate-600 dark:text-slate-400">即将入库</p>
          <p className="text-2xl font-bold text-slate-900 dark:text-slate-100">
            {selectedAccounts.length} 个账号
          </p>
          {activeSelected.length !== selectedAccounts.length && (
            <p className="text-xs text-slate-500 dark:text-slate-400">
              其中 {activeSelected.length} 个正常账号
            </p>
          )}
        </div>
        <Button
          onClick={handlePool}
          disabled={disabled || pooling}
          loading={pooling}
          icon={pooling ? undefined : <Upload className="h-4 w-4" />}
        >
          {pooling ? '入库中...' : '入库选中'}
        </Button>
      </div>

      {/* Progress */}
      {pooling && (
        <div>
          <Progress
            value={progress.current}
            max={progress.total}
            color="blue"
            showLabel
            label="入库进度"
          />
        </div>
      )}

      {/* Result */}
      {result && (
        <div
          className={`flex items-center gap-3 p-4 rounded-lg ${
            result.failed === 0
              ? 'bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800'
              : 'bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800'
          }`}
        >
          {result.failed === 0 ? (
            <CheckCircle className="h-6 w-6 text-green-600 dark:text-green-400" />
          ) : (
            <AlertCircle className="h-6 w-6 text-yellow-600 dark:text-yellow-400" />
          )}
          <div>
            <p
              className={`font-medium ${
                result.failed === 0
                  ? 'text-green-800 dark:text-green-200'
                  : 'text-yellow-800 dark:text-yellow-200'
              }`}
            >
              入库完成
            </p>
            <p
              className={`text-sm ${
                result.failed === 0
                  ? 'text-green-700 dark:text-green-300'
                  : 'text-yellow-700 dark:text-yellow-300'
              }`}
            >
              成功 {result.success} 个，失败 {result.failed} 个
            </p>
          </div>
        </div>
      )}
    </div>
  )
}
