import { Button, Card, Divider, Select, Space, Spin, Typography } from 'antd';
import type React from 'react';
import { clubs } from './clubList';
import { useCallback, useEffect, useState } from 'react';
import { useRequest } from 'ahooks';
import { GlobalOutlined } from '@ant-design/icons';
import type { IEventInfo } from '../../types';

interface Props {
  onGameClick?: (info: IEventInfo) => void;
}

export const GameSelector: React.FC<Props> = props => {
  const requestEvents = useRequest<IEventInfo[], [string]>(
    async (clubId: string) => (await fetch(`/api/events/${clubId}`)).json()
  , { manual: true })
  const [gameList, setGameList] = useState<IEventInfo[]>([]);
  const [isEmpty, setIsEmpty] = useState(false);
  const [clubId, setClubId] = useState(clubs[0].clubId);
  const handleClubChange = useCallback(async (clubId: string) => {
    const list = await requestEvents.runAsync(clubId);
    const activeList = list.filter(e => !e.info.join('').includes('已结束'));
    setGameList(activeList);
    setIsEmpty(activeList.length === 0);
  }, []);
  useEffect(() => {
    const clubId = clubs[0].clubId;
    handleClubChange(clubId);
  }, []);
  return (
    <Space orientation='vertical' style={{ width: '100%' }}>
      <Select
        style={{ width: '100%' }}
        placeholder={'请选择俱乐部'}
        size='large'
        value={clubId}
        options={clubs.map(e => ({ label: e.name, value: e.clubId }))}
        onChange={handleClubChange}
      />
      <Divider />
      {isEmpty && (<Typography.Text type='secondary'>没有未开始的比赛</Typography.Text>)}
      <Spin spinning={requestEvents.loading}>
        {gameList.map(e => (
          <Card
            key={e.matchId}
            title={e.title}
            hoverable
            onClick={() => props.onGameClick?.(e)}
          >
            <Typography.Text type='success'>{e.title}</Typography.Text>
            {e.info.map(e => (
              <div key={e}>
                <Typography.Text type='secondary'>{e}</Typography.Text>
              </div>
            ))}
          </Card>
        ))}
      </Spin>
    </Space>
  );
}