/**
 * 用户详情抽屉
 */

import { useState, useEffect } from 'react'
import {
  Drawer,
  Descriptions,
  Avatar,
  Tag,
  Spin,
  Typography,
} from 'antd'
import { UserOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import { getUser, getUserRoles } from '@/services/users'
import type { User, UserStatus } from '@/types/user'
import type { Role } from '@/types/auth'
import { UserStatusText, UserStatusColor } from '@/types/user'

const { Title } = Typography

interface UserDetailDrawerProps {
  open: boolean
  userId?: number
  onClose: () => void
}

export function UserDetailDrawer({ open, userId, onClose }: UserDetailDrawerProps) {
  const [loading, setLoading] = useState(false)
  const [user, setUser] = useState<User | null>(null)
  const [roles, setRoles] = useState<Role[]>([])

  useEffect(() => {
    if (open && userId) {
      const fetchData = async () => {
        setLoading(true)
        try {
          const [userData, roleData] = await Promise.all([
            getUser(userId),
            getUserRoles(userId),
          ])
          setUser(userData)
          setRoles(roleData)
        } catch {
          // 获取用户详情失败，忽略
        } finally {
          setLoading(false)
        }
      }
      fetchData()
    }
  }, [open, userId])

  return (
    <Drawer
      title="用户详情"
      placement="right"
      width={520}
      open={open}
      onClose={onClose}
    >
      {loading ? (
        <div style={{ textAlign: 'center', padding: 48 }}>
          <Spin size="large" />
        </div>
      ) : user ? (
        <>
          {/* 头像和基本信息 */}
          <div style={{ textAlign: 'center', marginBottom: 24 }}>
            <Avatar
              size={80}
              icon={<UserOutlined />}
              src={user.avatar}
              style={{ backgroundColor: user.avatar ? undefined : 'var(--color-primary)', marginBottom: 12 }}
            />
            <Title level={5} style={{ margin: 0 }}>
              {user.nickname || user.username}
            </Title>
            <Tag color={UserStatusColor[user.status as UserStatus]} style={{ marginTop: 8 }}>
              {UserStatusText[user.status as UserStatus]}
            </Tag>
          </div>

          {/* 详细信息 */}
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="用户 ID">{user.id}</Descriptions.Item>
            <Descriptions.Item label="用户名">{user.username}</Descriptions.Item>
            <Descriptions.Item label="邮箱">{user.email || '-'}</Descriptions.Item>
            <Descriptions.Item label="手机号">{user.phone || '-'}</Descriptions.Item>
            <Descriptions.Item label="昵称">{user.nickname || '-'}</Descriptions.Item>
            <Descriptions.Item label="性别">
              {user.gender === 1 ? '男' : user.gender === 2 ? '女' : '未知'}
            </Descriptions.Item>
            <Descriptions.Item label="生日">{user.birthday || '-'}</Descriptions.Item>
            <Descriptions.Item label="地区">{user.region || '-'}</Descriptions.Item>
            <Descriptions.Item label="简介">{user.bio || '-'}</Descriptions.Item>
            <Descriptions.Item label="角色">
              {roles.length > 0
                ? roles.map((r) => (
                    <Tag key={r.id} color={r.status === 1 ? 'blue' : 'default'}>
                      {r.name}
                    </Tag>
                  ))
                : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="最后登录时间">
              {user.last_login_at
                ? dayjs(user.last_login_at).format('YYYY-MM-DD HH:mm:ss')
                : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="最后登录 IP">
              {user.last_login_ip || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
              {dayjs(user.created_at).format('YYYY-MM-DD HH:mm:ss')}
            </Descriptions.Item>
            <Descriptions.Item label="更新时间">
              {dayjs(user.updated_at).format('YYYY-MM-DD HH:mm:ss')}
            </Descriptions.Item>
          </Descriptions>
        </>
      ) : (
        <div style={{ textAlign: 'center', padding: 48, color: 'var(--color-text-muted)' }}>
          用户信息不存在
        </div>
      )}
    </Drawer>
  )
}
