import { useNavigate, useOutletContext, useParams } from 'react-router-dom';
import { Button, Space, Table, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  USER_SOURCE_TYPE_LABELS,
  type PromoCodeAttributedUser,
  type UserSourceType,
} from '@dukang/shared-types';
import { fmtTime } from '../../lib/constants';
import { useAdminList } from '../../lib/useAdminList';
import type { PromoCodeDetailContext } from './PromoCodeDetailLayout';

export default function PromoCodeUsersPage() {
  const { id = '' } = useParams();
  const navigate = useNavigate();
  const { detail } = useOutletContext<PromoCodeDetailContext>();

  const { data, loading, page, pageSize, setPage, setPageSize } = useAdminList<PromoCodeAttributedUser>(
    `/admin/promo-codes/${id}/users`,
    () => new URLSearchParams(),
    [id],
  );

  const columns: ColumnsType<PromoCodeAttributedUser> = [
    { title: '用户编号', dataIndex: 'userNo', width: 120 },
    { title: '昵称', dataIndex: 'nickname', width: 100, render: (v) => v || '—' },
    { 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: '来源类型',
      dataIndex: 'sourceType',
      width: 100,
      render: (v: string) => (
        <Tag color={v === 'PROMO_CODE' ? 'blue' : 'default'}>
          {USER_SOURCE_TYPE_LABELS[v as UserSourceType] || v}
        </Tag>
      ),
    },
    {
      title: '来源 ID',
      dataIndex: 'sourceRefId',
      width: 100,
      render: (v) => (v === detail.id ? <Tag color="blue">本码</Tag> : v || '—'),
    },
    {
      title: '首次触达',
      dataIndex: 'firstTouchAt',
      width: 160,
      render: (v) => (v ? fmtTime(v) : '—'),
    },
    { title: '订单数', dataIndex: 'orderCount', width: 80 },
    { title: '注册时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
    {
      title: '操作',
      width: 100,
      fixed: 'right',
      render: (_, row) => (
        <Space size="small">
          <Button type="link" size="small" onClick={() => navigate('/users', { state: { openUserId: row.id } })}>
            查看用户
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <Table
      rowKey="id"
      className="admin-table-nowrap"
      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); },
      }}
    />
  );
}
