'use client'

import { useRef, useState } from 'react'
import { useEmojis } from '@/hooks/useEmojis'

interface UploadItemResult {
  name: string
  status: 'pending' | 'uploading' | 'success' | 'error'
  message?: string
}

interface BulkEmojiUploadProps {
  avatarId: string
  onSuccess: () => void
}

export function BulkEmojiUpload({ avatarId, onSuccess }: BulkEmojiUploadProps) {
  const inputRef = useRef<HTMLInputElement | null>(null)
  const { uploadEmojiFile, createEmoji } = useEmojis()
  const [uploading, setUploading] = useState(false)
  const [results, setResults] = useState<UploadItemResult[]>([])
  const [summary, setSummary] = useState<string | null>(null)

  const updateItem = (name: string, patch: Partial<UploadItemResult>) => {
    setResults(current =>
      current.map(item => (item.name === name ? { ...item, ...patch } : item)),
    )
  }

  const handleFilesSelected = async (files: FileList | null) => {
    if (!files || files.length === 0) {
      return
    }

    const selectedFiles = Array.from(files).filter(file => file.name.toLowerCase().endsWith('.webm'))
    if (selectedFiles.length === 0) {
      setSummary('请选择至少一个 webm 文件')
      return
    }

    setUploading(true)
    setSummary(null)
    setResults(selectedFiles.map(file => ({ name: file.name, status: 'pending' })))

    let successCount = 0

    for (const [index, file] of selectedFiles.entries()) {
      try {
        updateItem(file.name, { status: 'uploading', message: '上传中...' })
        const uploaded = await uploadEmojiFile(file)
        await createEmoji(avatarId, uploaded.label, uploaded.url, undefined, index)
        updateItem(file.name, { status: 'success', message: uploaded.label })
        successCount += 1
      } catch (error) {
        updateItem(file.name, {
          status: 'error',
          message: error instanceof Error ? error.message : '上传失败',
        })
      }
    }

    setUploading(false)
    setSummary(`成功 ${successCount} 个，失败 ${selectedFiles.length - successCount} 个`)

    if (successCount > 0) {
      onSuccess()
    }

    if (inputRef.current) {
      inputRef.current.value = ''
    }
  }

  return (
    <div className="rounded-lg border border-slate-200 bg-white p-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h2 className="text-lg font-semibold text-slate-900">批量添加表情</h2>
          <p className="mt-1 text-sm text-slate-500">
            一次选择多个 webm 文件，文件名会自动作为表情标签
          </p>
        </div>
        <label className="inline-flex cursor-pointer items-center justify-center rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800">
          {uploading ? '上传中...' : '选择 webm 文件'}
          <input
            ref={inputRef}
            type="file"
            accept=".webm,video/webm"
            multiple
            className="hidden"
            disabled={uploading}
            onChange={event => void handleFilesSelected(event.target.files)}
          />
        </label>
      </div>

      {summary && (
        <div className="mt-4 rounded-lg bg-slate-100 px-3 py-2 text-sm text-slate-700">
          {summary}
        </div>
      )}

      {results.length > 0 && (
        <div className="mt-4 space-y-2">
          {results.map(item => (
            <div
              key={item.name}
              className="flex items-center justify-between rounded-lg border border-slate-200 px-3 py-2 text-sm"
            >
              <span className="truncate pr-4 text-slate-700">{item.name}</span>
              <span
                className={
                  item.status === 'success'
                    ? 'text-emerald-600'
                    : item.status === 'error'
                      ? 'text-red-600'
                      : 'text-slate-500'
                }
              >
                {item.message || item.status}
              </span>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
