import React from 'react';
import { Row, Col, Typography, Input, Select, Empty, Spin } from 'antd';
import { useQuery } from '@tanstack/react-query';
import { getCompetitions } from '../../api';
import CompetitionCard from './CompetitionCard';
import { useState } from 'react';

const { Title } = Typography;
const { Search } = Input;
const { Option } = Select;

const CompetitionList = () => {
  const [params, setParams] = useState({ page: 1, page_size: 10 });
  const [search, setSearch] = useState('');
  const [status, setStatus] = useState('all');

  const { data, isLoading, isError } = useQuery({
    queryKey: ['competitions', params, search, status],
    queryFn: () => getCompetitions({
      ...params,
      search: search || undefined,
      status: status !== 'all' ? status : undefined
    }),
    keepPreviousData: true
  });

  const handleSearch = (value) => {
    setSearch(value);
    setParams({ ...params, page: 1 });
  };

  const handleStatusChange = (value) => {
    setStatus(value);
    setParams({ ...params, page: 1 });
  };

  if (isError) return <Empty description="加载失败，请稍后重试" />;

  return (
    <div className="competition-list-container">
      <div style={{ marginBottom: 32, textAlign: 'center' }}>
        <Title level={2} style={{ color: '#fff', marginBottom: 16 }}>赛事中心</Title>
        <div style={{ maxWidth: 800, margin: '0 auto', display: 'flex', gap: 16 }}>
          <Search
            placeholder="搜索比赛名称或简介"
            allowClear
            enterButton="搜索"
            size="large"
            onSearch={handleSearch}
            style={{ flex: 1 }}
          />
          <Select
            defaultValue="all"
            size="large"
            style={{ width: 120 }}
            onChange={handleStatusChange}
          >
            <Option value="all">全部状态</Option>
            <Option value="published">即将开始</Option>
            <Option value="registration">报名中</Option>
            <Option value="submission">提交中</Option>
            <Option value="judging">评审中</Option>
            <Option value="ended">已结束</Option>
          </Select>
        </div>
      </div>

      {isLoading ? (
        <div style={{ textAlign: 'center', padding: '50px 0' }}>
          <Spin size="large" tip="正在加载赛事..." />
        </div>
      ) : (
        <>
          {data?.data?.results?.length > 0 ? (
            <Row gutter={[24, 24]}>
              {data.data.results.map((comp) => (
                <Col key={comp.id} xs={24} sm={12} md={8} lg={6} xl={6} xxl={4}>
                  <CompetitionCard competition={comp} />
                </Col>
              ))}
            </Row>
          ) : (
            <Empty description="暂无相关比赛" image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
        </>
      )}
    </div>
  );
};

export default CompetitionList;