import { useEffect, useState } from 'react'
import { User, Loader2, AlertCircle } from 'lucide-react'
import { api, UserInfo } from '@/lib/api'
import { roleLabel } from '@/lib/auth'

export function Profile() {
  const [user, setUser] = useState<UserInfo | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    api.me()
      .then(setUser)
      .catch((err: any) => setError(err?.message || '加载失败'))
      .finally(() => setLoading(false))
  }, [])

  if (loading) {
    return (
      <div className="h-full flex items-center justify-center">
        <Loader2 className="h-6 w-6 animate-spin text-accent" />
      </div>
    )
  }

  return (
    <div className="max-w-xl space-y-6">
      <div className="flex items-center gap-3">
        <div className="p-2 rounded-btn bg-accent/10 text-accent">
          <User className="h-5 w-5" />
        </div>
        <h1 className="text-xl font-bold text-foreground">个人中心</h1>
      </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>
      )}

      <div className="rounded-card border border-border bg-surface p-5 space-y-4">
        <div className="grid grid-cols-[6rem_1fr] gap-4 items-center">
          <span className="text-sm text-secondary">用户名</span>
          <span className="text-sm font-medium text-foreground">{user?.username}</span>
        </div>
        <div className="grid grid-cols-[6rem_1fr] gap-4 items-center">
          <span className="text-sm text-secondary">角色</span>
          <span className="text-sm font-medium text-foreground">{user ? roleLabel(user.role) : '-'}</span>
        </div>
        <div className="grid grid-cols-[6rem_1fr] gap-4 items-center">
          <span className="text-sm text-secondary">邮箱</span>
          <span className="text-sm font-medium text-foreground">{user?.email || '未设置'}</span>
        </div>
        <div className="grid grid-cols-[6rem_1fr] gap-4 items-center">
          <span className="text-sm text-secondary">状态</span>
          <span className="text-sm font-medium text-foreground">{user?.status === 'active' ? '启用' : '禁用'}</span>
        </div>
        <div className="grid grid-cols-[6rem_1fr] gap-4 items-center">
          <span className="text-sm text-secondary">注册时间</span>
          <span className="text-sm font-medium text-foreground">{user ? new Date(user.created_at).toLocaleString() : '-'}</span>
        </div>
      </div>

      <div className="rounded-card border border-border bg-surface p-5">
        <h2 className="text-sm font-semibold text-foreground mb-3">关于</h2>
        <p className="text-sm text-secondary leading-relaxed">
          本系统为 A 股复盘工具的用户权限管理模块。不同角色拥有不同的操作权限，系统管理员可在「用户管理」中分配角色。
        </p>
      </div>
    </div>
  )
}
