import { useState } from 'react'
import { X, UserPlus, AlertCircle, Loader2 } from 'lucide-react'
import { api } from '@/lib/api'
import { RoleName, roleLabel } from '@/lib/auth'
import { cn } from '@/lib/cn'

interface CreateUserDialogProps {
  open: boolean
  onClose: () => void
  onSuccess: () => void
  allowedRoles: RoleName[]
}

export function CreateUserDialog({ open, onClose, onSuccess, allowedRoles }: CreateUserDialogProps) {
  const [form, setForm] = useState({
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
    role: (allowedRoles[0] || 'user') as RoleName,
  })
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  if (!open) return null

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')

    if (!form.username.trim()) {
      setError('请输入用户名')
      return
    }
    if (form.password.length < 6) {
      setError('密码长度至少 6 位')
      return
    }
    if (form.password !== form.confirmPassword) {
      setError('两次输入的密码不一致')
      return
    }
    if (!allowedRoles.includes(form.role as RoleName)) {
      setError('没有权限分配该角色')
      return
    }

    setLoading(true)
    try {
      await api.createUser({
        username: form.username.trim(),
        email: form.email.trim() || undefined,
        password: form.password,
        role: form.role,
      })
      setForm({ username: '', email: '', password: '', confirmPassword: '', role: (allowedRoles[0] || 'user') as RoleName })
      onSuccess()
    } catch (err: any) {
      setError(err?.message || '创建失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/60" onClick={onClose} />
      <div className="relative w-full max-w-md rounded-card border border-border bg-surface p-6 shadow-xl">
        <div className="flex items-center justify-between mb-5">
          <div className="flex items-center gap-2">
            <div className="p-1.5 rounded-btn bg-accent/10 text-accent">
              <UserPlus className="h-4 w-4" />
            </div>
            <h2 className="text-base font-semibold text-foreground">创建用户</h2>
          </div>
          <button
            onClick={onClose}
            className="p-1.5 rounded-btn text-secondary hover:bg-elevated hover:text-foreground transition-colors"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        {error && (
          <div className="flex items-start gap-2 rounded-btn border border-danger/30 bg-danger/10 px-3 py-2.5 text-xs text-danger mb-4">
            <AlertCircle className="h-3.5 w-3.5 mt-px shrink-0" />
            <span>{error}</span>
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-xs text-secondary mb-1">用户名</label>
            <input
              required
              placeholder="用户名"
              value={form.username}
              onChange={(e) => setForm({ ...form, username: e.target.value })}
              className="w-full rounded-input bg-base border border-border px-3 py-2 text-sm focus:outline-none focus:border-accent"
            />
          </div>

          <div>
            <label className="block text-xs text-secondary mb-1">邮箱（可选）</label>
            <input
              type="email"
              placeholder="邮箱"
              value={form.email}
              onChange={(e) => setForm({ ...form, email: e.target.value })}
              className="w-full rounded-input bg-base border border-border px-3 py-2 text-sm focus:outline-none focus:border-accent"
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs text-secondary mb-1">密码</label>
              <input
                required
                type="password"
                placeholder="密码"
                value={form.password}
                onChange={(e) => setForm({ ...form, password: e.target.value })}
                className="w-full rounded-input bg-base border border-border px-3 py-2 text-sm focus:outline-none focus:border-accent"
              />
            </div>
            <div>
              <label className="block text-xs text-secondary mb-1">确认密码</label>
              <input
                required
                type="password"
                placeholder="确认密码"
                value={form.confirmPassword}
                onChange={(e) => setForm({ ...form, confirmPassword: e.target.value })}
                className="w-full rounded-input bg-base border border-border px-3 py-2 text-sm focus:outline-none focus:border-accent"
              />
            </div>
          </div>

          <div>
            <label className="block text-xs text-secondary mb-1">角色</label>
            <select
              value={form.role}
              onChange={(e) => setForm({ ...form, role: e.target.value as RoleName })}
              className="w-full rounded-input bg-base border border-border px-3 py-2 text-sm focus:outline-none focus:border-accent"
            >
              {allowedRoles.map((r) => (
                <option key={r} value={r}>
                  {roleLabel(r)}
                </option>
              ))}
            </select>
          </div>

          <div className="flex items-center justify-end gap-2 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded-btn text-sm text-secondary hover:bg-elevated hover:text-foreground transition-colors"
            >
              取消
            </button>
            <button
              type="submit"
              disabled={loading}
              className={cn(
                'inline-flex items-center gap-2 px-4 py-2 rounded-btn bg-accent text-white text-sm font-medium hover:bg-accent/90 transition-colors',
                loading && 'opacity-60',
              )}
            >
              {loading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
              创建
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
