'use client'

import { useState } from 'react'
import type { FormEvent } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { ArrowLeft } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend } from '@/lib/backend'
import { AdminUserForm, adminUserDraftPayload, emptyAdminUserDraft } from '../UserForm'

export default function AdminCreateUserPage() {
  const router = useRouter()
  const [draft, setDraft] = useState(emptyAdminUserDraft)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  async function saveUser(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!draft.phone.trim() && !draft.wechatId.trim()) {
      setError('新增用户至少需要手机号或微信号')
      return
    }
    setSaving(true)
    setError('')
    try {
      const created = await backend.createAdminUser(adminUserDraftPayload(draft))
      router.push(`/admin/users/${encodeURIComponent(created.passportNo || created.id)}`)
    } catch (err) {
      setError(err instanceof Error ? err.message : '用户创建失败')
    } finally {
      setSaving(false)
    }
  }

  return (
    <AdminShell title="新增用户" description="创建用户档案、联系方式、机构资料、发票信息和账号状态。">
      <div className="mb-4 flex justify-end">
        <Link href="/admin/users" className="inline-flex h-10 items-center gap-2 rounded-[4px] border border-line px-4 text-sm font-bold text-muted hover:border-brand hover:text-brand">
          <ArrowLeft className="h-4 w-4" />
          返回用户列表
        </Link>
      </div>

      {error && (
        <div className="mb-3 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">
          {error}
        </div>
      )}

      <section className="border border-line bg-white p-5">
        <AdminUserForm draft={draft} setDraft={setDraft} saving={saving} submitLabel="创建用户" onSubmit={saveUser} />
      </section>
    </AdminShell>
  )
}
