import { Pagination } from 'antd';
import axios from 'axios';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { NavigateFunction, useNavigate } from "react-router-dom";
import './App.css';
import A from './Components/CustomA';

export default function App() {
	const navigate: NavigateFunction = useNavigate();
	const [current, setCurrent] = useState(1);
	const [totalDataLength, setTotalDataLength] = useState(50)
	const [data, setData] = useState<any[][]>([[]])
	const [showData, setShowData] = useState([])

	function onChange(page: number): void {
		setCurrent(page);
	}

	function onClickPlay(data: any): void {
		navigate(`/play/${data.id}`);
	}

	function getList(): void {
		if (data[current]) {
			setShowData(data[current])
			return;
		}

		const reqData = JSON.stringify({
			"page": current
		});

		const config = {
			method: 'post',
			maxBodyLength: Infinity,
			url: 'https://jianmiau.tk:21880/Badminton/gethistory',
			headers: {
				'Content-Type': 'application/json'
			},
			data: reqData
		};

		axios.request(config)
			.then((response) => {
				setData((value: any[][]) => {
					value[current] = response.data;
					setShowData(response.data)
					return value;
				});
			})
			.catch((error) => {
				console.log(error);
			});
	}

	function getListPage(): void {
		const config = {
			method: 'post',
			maxBodyLength: Infinity,
			url: 'https://jianmiau.tk:21880/Badminton/gethistorypage',
			headers: {
				'Content-Type': 'application/json'
			},
		};

		axios.request(config)
			.then((response) => {
				setTotalDataLength(response.data[0].count);
			})
			.catch((error) => {
				console.error(error);
			});
	}

	useEffect(() => {
		document.title = "羽球團"
		getListPage();
	}, [])

	useEffect(() => {
		getList();
	}, [current])

	return <>
		{showData.length
			? <>
				<table>
					<thead>
						<tr>
							<th>時間</th>
							<th>分數</th>
							<th>人員</th>
							<th></th>
						</tr>
					</thead>
					<tbody>
						{showData.map((value: any, idx: number) => {
							const score: number[] = JSON.parse(value.score);
							const team: string[] = JSON.parse(value.team);
							return <tr key={idx}>
								<td>{dayjs(value.time * 1000).format("YYYY-MM-DD HH:mm:ss")}</td>
								<td>{score[0]}：{score[1]}</td>
								<td>{team[0][0].padEnd(5, "　")}{team[0][1].padEnd(5, "　")} vs 　　{team[1][0].padEnd(5, "　")}{team[1][1]}</td>
								<td>
									<A href="#" onClick={() => onClickPlay(value)}>詳細</A></td>
							</tr>
						})}
					</tbody>
				</table>
				<Pagination current={current} onChange={onChange} total={totalDataLength} hideOnSinglePage />
			</>
			: <></>
		}
	</>
}