'use client';

import './style.scss';
import { useState, useEffect } from 'react';
import { fetchApi, throwError, getDateTime } from '@/lib/utils/client';
import type { NewsArticlesResponse } from '@/types/response/news';
import Loading from '@/app/component/Loading';
import Pagination from '@/app/component/Pagination';

function stripHtml(html: string | null): string {
	if (!html) {
		return '';
	}

	const doc = new DOMParser().parseFromString(html, 'text/html');
	return doc.body.textContent || '';
}

export default function View() {
	const [error, setError] = useState<string>('');
	const [loading, setLoading] = useState<boolean>(true);
	const [page, setPage] = useState<number>(1);
	const [data, setData] = useState<NewsArticlesResponse>({
		total: 0,
		list: []
	});

	useEffect(() => {
		if (error) {
			alert(error);
			setError('');
		}
	}, [error]);

	useEffect(() => {
		setLoading(true);
		fetchApi<NewsArticlesResponse>(`/api/news/articles?page=${page}&perPage=20`).then((res) => {
			throwError(res);
			setData(res.data!);
		}).catch(err => {
			setError(err.message);
		}).finally(() => {
			setLoading(false);
		});
	}, [page]);

	return (
		<section id='news'>
			{ loading && <Loading /> }

			<p>NEWS</p>

			<hr />

			{data.list.length > 0 ? (
				data.list.map((row) => (
					<div key={row.id}>
						<article>
							<div>
								<img
									src={row.imageUrl || '/resources/no-image-2.png'}
									alt={row.title}
									onError={(e) => { (e.target as HTMLImageElement).src = '/resources/no-image.png'; }}
								/>
							</div>
							<div>
								<a href={row.link || '#'} target='_blank' rel='noopener noreferrer'>
									{row.title}
								</a>
								<span>
									{/*<em>{row.sourceName || row.feedSourceName}</em>*/}
									{getDateTime(row.publishedAt)}
								</span>
							</div>
							<div className='desc'>
								{stripHtml(row.description)}
							</div>
						</article>
						<hr />
					</div>
				))
			) : (
				!loading && <p className='empty'>뉴스가 없습니다.</p>
			)}

			<br />

			{data.list.length > 0 && (
				<Pagination total={data.total} page={page} perPage={20} onChange={setPage} />
			)}
		</section>
	);
}