import { useState } from 'react'
import { Shield, Lock, AlertCircle, Loader2, LogIn } from 'lucide-react'
import { api, setToken } from '@/lib/api'
import { setStoredUser } from '@/lib/auth'

interface LoginFormProps {
  onSuccess: () => void
}

export function LoginForm({ onSuccess }: LoginFormProps) {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    if (!username.trim() || !password.trim()) {
      setError('请输入用户名和密码')
      return
    }
    setLoading(true)
    try {
      const res = await api.login({ username: username.trim(), password })
      setToken(res.token)
      setStoredUser(res.user)
      onSuccess()
    } catch (err: any) {
      setError(err?.message || '登录失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <motion.div
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.35, ease: [0.16, 1, 0.3, 1] }}
      className="w-full max-w-md"
    >
      <div className="rounded-card border border-border bg-surface/80 backdrop-blur-sm p-6">
        <div className="flex flex-col items-center text-center">
          <div
            className="rounded-2xl p-4 border border-border"
            style={{ background: 'linear-gradient(135deg, #8B5CF622, transparent)' }}
          >
            <Shield className="h-8 w-8" style={{ color: '#8B5CF6' }} />
          </div>
          <h1 className="mt-5 text-2xl font-bold text-foreground tracking-tight">登录账号</h1>
          <p className="mt-2 text-sm text-secondary leading-relaxed">
            请输入用户名和密码进入系统。
          </p>
        </div>

        <form onSubmit={handleSubmit} className="mt-6 space-y-4">
          <div className="relative">
            <div className="absolute left-3 top-1/2 -translate-y-1/2 text-muted">
              <Shield className="h-4 w-4" />
            </div>
            <input
              type="text"
              autoComplete="username"
              placeholder="用户名"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              className="w-full pl-9 pr-3 py-2.5 rounded-input bg-base border border-border text-sm focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/30 transition-all"
            />
          </div>

          <div className="relative">
            <div className="absolute left-3 top-1/2 -translate-y-1/2 text-muted">
              <Lock className="h-4 w-4" />
            </div>
            <input
              type="password"
              autoComplete="current-password"
              placeholder="密码"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full pl-9 pr-3 py-2.5 rounded-input bg-base border border-border text-sm focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/30 transition-all"
            />
          </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">
              <AlertCircle className="h-3.5 w-3.5 mt-px shrink-0" />
              <span>{error}</span>
            </div>
          )}

          <button
            type="submit"
            disabled={loading}
            className="w-full inline-flex items-center justify-center gap-2 px-5 h-11 rounded-xl bg-accent text-white text-sm font-semibold shadow-lg shadow-accent/20 hover:bg-accent/90 hover:shadow-accent/30 disabled:opacity-60 transition-all"
          >
            {loading ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <LogIn className="h-4 w-4" />
            )}
            {loading ? '处理中…' : '登录'}
          </button>
        </form>

        <div className="mt-5 text-center">
          <span className="text-xs text-secondary">没有账号？请联系管理员创建</span>
        </div>
      </div>
    </motion.div>
  )
}

// 简单内联 motion 组件，避免引入 framer-motion 依赖
const motion = {
  div: ({ children, className, ...props }: any) => {
    return (
      <div
        ref={(el) => {
          if (el && props.initial) {
            el.style.opacity = String(props.initial.opacity ?? 1)
            el.style.transform = `translateY(${props.initial.y ?? 0}px)`
            requestAnimationFrame(() => {
              el.style.transition = `all ${props.transition?.duration ?? 0.3}s ${(props.transition?.ease || [0.16, 1, 0.3, 1]).join(',')}`
              el.style.opacity = String(props.animate?.opacity ?? 1)
              el.style.transform = `translateY(${props.animate?.y ?? 0}px)`
            })
          }
        }}
        className={className}
      >
        {children}
      </div>
    )
  },
}
