import { useCallback, useEffect, useState } from 'react';
import {
  Button,
  Descriptions,
  Drawer,
  Form,
  Input,
  Select,
  Space,
  Table,
  Tag,
  Typography,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { request, type AdminUserRow, type Paginated } from '../lib/api';

type UserDetail = AdminUserRow & {
  cityPref?: Record<string, unknown> | null;
  mergedInto?: { id: string; userNo: string; phone: string | null; nickname: string | null } | null;
  orders?: Array<{ id: string; orderNo: string; status: string; payAmount: number; createdAt: string }>;
  mergedFromCount?: number;
  orderCount?: number;
  addressCount?: number;
};

export default function UsersPage() {
  const [form] = Form.useForm();
  const [data, setData] = useState<Paginated<AdminUserRow> | null>(null);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [detail, setDetail] = useState<UserDetail | null>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const values = form.getFieldsValue();
      const qs = new URLSearchParams({ page: String(page), pageSize: String(pageSize) });
      if (values.phone) qs.set('phone', values.phone);
      if (values.userNo) qs.set('userNo', values.userNo);
      if (values.deviceKey) qs.set('deviceKey', values.deviceKey);
      if (values.phoneVerified !== undefined && values.phoneVerified !== '') {
        qs.set('phoneVerified', values.phoneVerified);
      }
      if (values.status !== undefined && values.status !== '') {
        qs.set('status', String(values.status));
      }
      const res = await request<Paginated<AdminUserRow>>(`/admin/users?${qs}`);
      setData(res);
    } finally {
      setLoading(false);
    }
  }, [form, page, pageSize]);

  useEffect(() => {
    void load();
  }, [load]);

  async function openDetail(id: string) {
    const res = await request<UserDetail>(`/admin/users/${id}`);
    setDetail(res);
    setDrawerOpen(true);
  }

  const columns: ColumnsType<AdminUserRow> = [
    { title: '用户编号', dataIndex: 'userNo', width: 120 },
    { title: '昵称', dataIndex: 'nickname', width: 100 },
    {
      title: '手机',
      dataIndex: 'phone',
      width: 120,
      render: (v) => v || '—',
    },
    {
      title: '验手机',
      dataIndex: 'phoneVerifiedAt',
      width: 90,
      render: (v) => (v ? <Tag color="green">已验证</Tag> : <Tag color="orange">访客</Tag>),
    },
    {
      title: 'deviceKey',
      dataIndex: 'deviceKey',
      ellipsis: true,
      render: (v) => v || '—',
    },
    {
      title: '合并',
      dataIndex: 'mergedIntoUserId',
      width: 80,
      render: (v) => (v ? <Tag color="blue">已合并</Tag> : '—'),
    },
    { title: '订单数', dataIndex: 'orderCount', width: 80 },
    {
      title: '注册时间',
      dataIndex: 'createdAt',
      width: 170,
      render: (v) => new Date(v).toLocaleString('zh-CN'),
    },
    {
      title: '操作',
      width: 80,
      render: (_, row) => (
        <Button type="link" size="small" onClick={() => openDetail(row.id)}>
          详情
        </Button>
      ),
    },
  ];

  return (
    <div>
      <Typography.Title level={4}>用户监控</Typography.Title>
      <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={() => { setPage(1); void load(); }}>
        <Form.Item name="phone" label="手机号">
          <Input placeholder="模糊搜索" allowClear />
        </Form.Item>
        <Form.Item name="userNo" label="用户编号">
          <Input placeholder="DK..." allowClear />
        </Form.Item>
        <Form.Item name="deviceKey" label="deviceKey">
          <Input placeholder="UUID" allowClear style={{ width: 200 }} />
        </Form.Item>
        <Form.Item name="phoneVerified" label="验手机">
          <Select allowClear style={{ width: 100 }} options={[
            { value: '1', label: '已验证' },
            { value: '0', label: '访客' },
          ]} />
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select allowClear style={{ width: 90 }} options={[
            { value: 1, label: '正常' },
            { value: 0, label: '停用' },
          ]} />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">查询</Button>
            <Button onClick={() => { form.resetFields(); setPage(1); void load(); }}>重置</Button>
          </Space>
        </Form.Item>
      </Form>

      <Table
        rowKey="id"
        loading={loading}
        columns={columns}
        dataSource={data?.items ?? []}
        scroll={{ x: 1100 }}
        pagination={{
          current: page,
          pageSize,
          total: data?.total ?? 0,
          showSizeChanger: true,
          onChange: (p, ps) => {
            setPage(p);
            setPageSize(ps);
          },
        }}
      />

      <Drawer title="用户详情" width={560} open={drawerOpen} onClose={() => setDrawerOpen(false)}>
        {detail && (
          <>
            <Descriptions column={1} bordered size="small">
              <Descriptions.Item label="ID">{detail.id}</Descriptions.Item>
              <Descriptions.Item label="用户编号">{detail.userNo}</Descriptions.Item>
              <Descriptions.Item label="昵称">{detail.nickname || '—'}</Descriptions.Item>
              <Descriptions.Item label="手机号">{detail.phone || '—'}</Descriptions.Item>
              <Descriptions.Item label="验手机时间">
                {detail.phoneVerifiedAt ? new Date(detail.phoneVerifiedAt).toLocaleString('zh-CN') : '未验证'}
              </Descriptions.Item>
              <Descriptions.Item label="deviceKey">{detail.deviceKey || '—'}</Descriptions.Item>
              <Descriptions.Item label="合并至">
                {detail.mergedInto
                  ? `${detail.mergedInto.userNo} (${detail.mergedInto.phone || '无手机'})`
                  : '—'}
              </Descriptions.Item>
              <Descriptions.Item label="被合并访客数">{detail.mergedFromCount ?? 0}</Descriptions.Item>
              <Descriptions.Item label="订单/地址">{detail.orderCount} / {detail.addressCount}</Descriptions.Item>
              <Descriptions.Item label="注册时间">
                {new Date(detail.createdAt).toLocaleString('zh-CN')}
              </Descriptions.Item>
            </Descriptions>
            {detail.orders && detail.orders.length > 0 && (
              <>
                <Typography.Title level={5} style={{ marginTop: 16 }}>最近订单</Typography.Title>
                <Table
                  size="small"
                  rowKey="id"
                  pagination={false}
                  dataSource={detail.orders}
                  columns={[
                    { title: '订单号', dataIndex: 'orderNo' },
                    { title: '状态', dataIndex: 'status' },
                    { title: '金额', dataIndex: 'payAmount', render: (v) => `¥${v}` },
                  ]}
                />
              </>
            )}
          </>
        )}
      </Drawer>
    </div>
  );
}
