import React, {useState, useEffect} from 'react';
import axios from 'axios';
import Loader from './Loader';

/* eslint-disable */
/**
 * @return {jsx} The root component
 */
export default function ArticleTable() {
	const [articleTable, setArticleTable] = useState([])
	const [clickedOnDelete, setClickedOnDelete] = useState(false);
	const [busy, setBusy] = useState(true);

	useEffect(() => {
		setBusy(true)
		axios.get('/api/articletable', {
			withCredentials: true,
		}).then((articles: any) => {
			var $articles: any = [];
			articles.data.forEach((article: any) => {
				$articles.push(
					<tr key={article.id}>
						<td>{article.title}</td>
						<td>{article.id}</td>
						<td>{new Date(article.createdAt).toLocaleDateString()}</td>
						<td>
							<a className="btn btn-info" href={'/admin/edit' + article.id}>Edit</a>
							<button className="btn btn-danger" onClick={() => deleteArticle(article.id)}>Delete</button>
						</td>
					</tr>);
			});
			setArticleTable($articles);
			setBusy(false);
		});
	}, [clickedOnDelete]);

	function deleteArticle(id: string) {
		axios.delete('/admin/' + id, {
			withCredentials: true,
		}).then(() => {
			setClickedOnDelete(!clickedOnDelete);
		});
	}

	return (
		<div>
			{busy ? (
				<Loader />
				) : (
					<table className="table table-dark">
						<thead>
							<tr>
								<th>Title</th>
								<th>Tags</th>
								<th>Creation Date</th>
								<th>Actions</th>
							</tr>
						</thead>
						<tbody>
							{articleTable}
						</tbody>
					</table>
			)}
		</div>
	);
}
/* eslint-enable */
