'use client'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import AssetImport from '@/components/assets/AssetImport'
import { ArrowLeft } from 'lucide-react'

export default function ImportPage() {
  const router = useRouter()
  const [authorized, setAuthorized] = useState(false)

  useEffect(() => {
    fetch('/api/auth/me').then(r => r.json()).then(d => {
      const perms: string[] = d.user?.permissions || []
      if (!perms.includes('*') && !perms.includes('assets:import')) router.replace('/assets')
      else setAuthorized(true)
    }).catch(() => router.replace('/assets'))
  }, [router])

  if (!authorized) return <div className="py-20 text-center text-slate-500 dark:text-slate-400">验证权限中...</div>

  async function handleImport(file: File) {
    const formData = new FormData()
    formData.append('file', file)
    const res = await fetch('/api/assets/import', { method: 'POST', body: formData })
    const data = await res.json()
    if (!res.ok) throw new Error(data.error || '导入失败')
    return data as { created: number; updated: number; errors: string[] }
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <Link href="/assets" className="p-2 rounded-lg text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"><ArrowLeft size={20} /></Link>
        <h1 className="text-2xl font-bold text-slate-900 dark:text-white">导入资产</h1>
      </div>
      <div className="bg-white dark:bg-slate-900 rounded-lg border border-slate-200 dark:border-slate-700 p-6">
        <AssetImport onImport={handleImport} />
      </div>
    </div>
  )
}
