import { useMemo, useState } from "react";
import { Button, Card, Drawer, Table } from "antd";
import type { BasePlayer } from "../types";
import User from "./User";
import BattleTable from "./BattleTable";
import { ExpandOutlined } from "@ant-design/icons";

interface Props {
  index: number;
  players?: (BasePlayer & { id: string })[];
}

export const GroupMember: React.FC<Props> = props => {
  const char = useMemo(() => {
    const baseCode = 'A'.charCodeAt(0);
    let idx = props.index;
    const times = Math.floor(idx / 26);
    const code = 'A'.repeat(times);
    const lastChar = baseCode + (idx % 26);
    return `${code}${String.fromCharCode(lastChar)}`;
  }, []);
  const [open, setOpen] = useState(false);
  const [expanded, setExpanded] = useState(false);
  return (
    <Card
      title={`${char} 组`}
      style={{ minWidth: 300 }}
      extra={<Button type="link" onClick={() => setOpen(true)}>查看对战表</Button>}
    >
      <Table
        size="small"
        rowKey={e => `${e.id}-${e.name}-${e.score}`}
        showHeader={false}
        pagination={false}
        rowHoverable={false}
        dataSource={props.players}
        columns={[
          { dataIndex: '_', render: (_, __, i) => `(${i + 1})` },
          { dataIndex: 'number' },
          { dataIndex: 'name', render: (name, { uid }) => <User name={name} uid={uid} /> },
          { dataIndex: 'score' },
        ]}
      />
      <Drawer
        open={open}
        title={`${char} 组对战表`}
        onClose={() => setOpen(false)}
        size={expanded ? '100vh' : '80vh'}
        placement="bottom"
        extra={<ExpandOutlined onClick={() => setExpanded(!expanded)} />}
      >
        <BattleTable players={props.players ?? []} />
      </Drawer>
    </Card>
  );
}
