import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"
import { Link, useNavigate } from "react-router-dom"
import {
  CheckCircleOutlined,
  CrownOutlined,
  ReloadOutlined,
  SearchOutlined,
  StopOutlined,
  TeamOutlined,
  UserOutlined,
} from "@ant-design/icons"
import { Avatar, Button, Card, Col, Input, Row, Select, Space, Statistic, Table, Tag, Typography, type TableColumnsType } from "antd"
import { toast } from "../../utils/toast"
import { listUsers, type AdminUser } from "../api/user"

const { Title, Paragraph, Text } = Typography

const ROLE_META: Record<AdminUser["role"], { label: string; color: string; icon: ReactNode }> = {
  super_admin: { label: "超级管理员", color: "purple", icon: <CrownOutlined /> },
  admin: { label: "管理员", color: "blue", icon: <CrownOutlined /> },
  user: { label: "普通用户", color: "default", icon: <UserOutlined /> },
}

const STATUS_META: Record<AdminUser["status"], { label: string; color: string }> = {
  active: { label: "正常", color: "success" },
  inactive: { label: "未激活", color: "warning" },
  banned: { label: "已封禁", color: "error" },
}

function fmtBalance(cents: number) {
  return `¥${(cents / 100).toFixed(2)}`
}

function fmtDate(value: string | null) {
  if (!value) return "-"
  return new Date(value).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  })
}

export default function AdminUsers() {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(true)
  const [users, setUsers] = useState<AdminUser[]>([])
  const [keyword, setKeyword] = useState("")
  const [filterRole, setFilterRole] = useState<string>("")
  const [filterStatus, setFilterStatus] = useState<string>("")

  const reload = useCallback(async (silent = false) => {
    if (!silent) setLoading(true)
    try {
      const res = await listUsers({
        keyword: keyword || undefined,
        role: filterRole || undefined,
        status: filterStatus || undefined,
        limit: 200,
      })
      setUsers(res.data?.items ?? [])
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail ?? "加载失败")
    } finally {
      setLoading(false)
    }
  }, [keyword, filterRole, filterStatus])

  useEffect(() => {
    void reload()
  }, [reload])

  const stats = useMemo(() => {
    const total = users.length
    const active = users.filter((u) => u.status === "active").length
    const banned = users.filter((u) => u.status === "banned").length
    const admins = users.filter((u) => u.role !== "user").length
    return { total, active, banned, admins }
  }, [users])

  const columns: TableColumnsType<AdminUser> = [
    {
      title: "用户",
      dataIndex: "username",
      width: 280,
      render: (_value, record) => (
        <Space size={12}>
          <Avatar src={record.avatar || undefined} icon={<UserOutlined />}>
            {(record.nickname || record.username).charAt(0).toUpperCase()}
          </Avatar>
          <Space orientation="vertical" size={0}>
            <Link to={`/admin/users/${record.id}`}>{record.nickname || record.username}</Link>
            <Text type="secondary" style={{ fontSize: 12 }}>@{record.username} · ID {record.id}</Text>
          </Space>
        </Space>
      ),
    },
    {
      title: "联系方式",
      key: "contact",
      width: 260,
      render: (_value, record) => (
        <Space orientation="vertical" size={0}>
          <Text>{record.email || "-"}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.phone || "-"}</Text>
        </Space>
      ),
    },
    {
      title: "实名认证",
      dataIndex: "id_card_verified",
      width: 120,
      render: (value: AdminUser["id_card_verified"]) => {
        const map: Record<string, { label: string; color: string }> = {
          verified: { label: "已认证", color: "success" },
          pending: { label: "认证中", color: "processing" },
          rejected: { label: "已拒绝", color: "error" },
          unverified: { label: "未认证", color: "default" },
        }
        const meta = map[value || "unverified"]
        return <Tag color={meta.color}>{meta.label}</Tag>
      },
    },
    {
      title: "角色",
      dataIndex: "role",
      width: 140,
      render: (value: AdminUser["role"]) => {
        const meta = ROLE_META[value]
        return <Tag color={meta.color} icon={meta.icon}>{meta.label}</Tag>
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 110,
      render: (value: AdminUser["status"]) => {
        const meta = STATUS_META[value]
        return <Tag color={meta.color}>{meta.label}</Tag>
      },
    },
    {
      title: "余额",
      dataIndex: "balance",
      width: 130,
      align: "right",
      render: (value: number) => <Text strong>{fmtBalance(value)}</Text>,
    },
    {
      title: "注册时间",
      dataIndex: "created_at",
      width: 180,
      render: fmtDate,
    },
    {
      title: "最近登录",
      dataIndex: "last_login_at",
      width: 180,
      render: fmtDate,
    },
  ]

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row gutter={[16, 16]} align="bottom" justify="space-between">
        <Col>
          <Title level={3} style={{ margin: 0 }}>用户管理</Title>
          <Paragraph type="secondary" style={{ marginTop: 8, marginBottom: 0 }}>
            管理注册用户、账户状态、角色权限与余额。
          </Paragraph>
        </Col>
        <Col>
          <Button icon={<ReloadOutlined />} loading={loading} onClick={() => reload()}>
            刷新
          </Button>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="总用户数" value={stats.total} prefix={<TeamOutlined />} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="正常用户" value={stats.active} prefix={<CheckCircleOutlined />} styles={{ content: { color: "#52c41a" } }} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="管理员" value={stats.admins} prefix={<CrownOutlined />} styles={{ content: { color: "#722ed1" } }} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="已封禁" value={stats.banned} prefix={<StopOutlined />} styles={{ content: { color: "#ff4d4f" } }} /></Card>
        </Col>
      </Row>

      <Card variant="outlined">
        <Space wrap style={{ width: "100%", justifyContent: "space-between" }}>
          <Space wrap>
            <Input.Search
              allowClear
              value={keyword}
              onChange={(event) => setKeyword(event.target.value)}
              onSearch={() => reload()}
              placeholder="搜索用户名 / 邮箱 / 手机号"
              prefix={<SearchOutlined />}
              style={{ width: 300 }}
            />
            <Select
              value={filterRole}
              onChange={setFilterRole}
              style={{ width: 150 }}
              options={[
                { value: "", label: "全部角色" },
                { value: "user", label: "普通用户" },
                { value: "admin", label: "管理员" },
                { value: "super_admin", label: "超级管理员" },
              ]}
            />
            <Select
              value={filterStatus}
              onChange={setFilterStatus}
              style={{ width: 140 }}
              options={[
                { value: "", label: "全部状态" },
                { value: "active", label: "正常" },
                { value: "inactive", label: "未激活" },
                { value: "banned", label: "已封禁" },
              ]}
            />
          </Space>
          <Text type="secondary">共 {users.length} 条</Text>
        </Space>
      </Card>

      <Card variant="outlined" title="用户列表">
        <Table
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={users}
          pagination={{ pageSize: 10, showSizeChanger: false }}
          scroll={{ x: 1280 }}
          onRow={(record) => ({
            onClick: () => navigate(`/admin/users/${record.id}`),
            style: { cursor: "pointer" },
          })}
        />
      </Card>
    </Space>
  )
}
