import { Button, Popconfirm, Space, Table, Tag, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  PARTNER_PERMISSION_LABELS,
  PARTNER_STAFF_ROLE_LABELS,
  type PartnerPermissionKey,
} from '@dukang/shared-types';

export type PartnerSubAccountRow = {
  id: string;
  phone: string;
  name: string;
  staffRole?: string;
  permissions?: string[];
  status: string;
};

function formatPermissions(permissions?: string[]) {
  return permissions?.map((k) => PARTNER_PERMISSION_LABELS[k as PartnerPermissionKey] || k).join('、') || '—';
}

type Props = {
  subs: PartnerSubAccountRow[];
  onAdd: () => void;
  onEdit: (sub: PartnerSubAccountRow) => void;
  onDelete: (subId: string) => void;
};

export default function PartnerSubAccountList({ subs, onAdd, onEdit, onDelete }: Props) {
  const columns: ColumnsType<PartnerSubAccountRow> = [
    { title: '姓名', dataIndex: 'name', width: 100 },
    { title: '手机', dataIndex: 'phone', width: 120 },
    {
      title: '角色',
      dataIndex: 'staffRole',
      width: 90,
      render: (v) =>
        v ? PARTNER_STAFF_ROLE_LABELS[v as keyof typeof PARTNER_STAFF_ROLE_LABELS] || v : '—',
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: (s) => (
        <Tag color={s === 'ACTIVE' ? 'green' : 'default'}>{s === 'ACTIVE' ? '启用' : '停用'}</Tag>
      ),
    },
    {
      title: '权限',
      dataIndex: 'permissions',
      ellipsis: true,
      render: (p: string[] | undefined) => formatPermissions(p),
    },
    {
      title: '操作',
      width: 120,
      render: (_, row) => (
        <Space size={0}>
          <Button type="link" size="small" onClick={() => onEdit(row)}>
            编辑
          </Button>
          <Popconfirm title="确定删除该子账号？" onConfirm={() => onDelete(row.id)}>
            <Button type="link" size="small" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <Typography.Text type="secondary" style={{ fontSize: 12 }}>
          子账号（{subs.length}）· 仅主账号可添加，不可多级
        </Typography.Text>
        <Button size="small" type="primary" onClick={onAdd}>
          添加子账号
        </Button>
      </div>
      <Table
        size="small"
        rowKey="id"
        pagination={false}
        columns={columns}
        dataSource={subs}
        locale={{ emptyText: '暂无子账号' }}
      />
    </>
  );
}
