import { useQuery } from "@tanstack/react-query"
import eolasApi from "@/api/eolas-api"
import { convertDate } from "@/utils/convertDate"

const EolasEntries = ({ entries }) => {
	return (
		entries &&
		entries.map((entry, i) => (
			<ul>
				<li className="mb-4">
					<div className="flex justify-between items-center relative gap-3 hover:bg-[#504945]">
						<span className="overflow-hidden whitespace-nowrap text-muted-foreground shrink-0 condensed">
							{convertDate(entry.last_modified)}
						</span>
						<a
							href={`https://eolas.systemsobscure.net/entries/${entry.title}`}
							key={i}
							className="text-right overflow-hidden text-ellipsis whitespace-nowrap min-w-0 flex-1 "
						>
							{entry.title.replace(/_/g, " ")}
						</a>
					</div>
				</li>
			</ul>
		))
	)
}

const EolasListing = () => {
	const { data, isLoading, error } = useQuery({
		queryKey: [`eolas_listing`],
		queryFn: () =>
			eolasApi.get(`entries?limit=5&sort=date`).then((res) => res.data),
	})

	return (
		<div className="container mx-auto p-4 grow">
			<div className="space-my-8">
				<section className="container">
					<h2 className="text-2xl font-semibold mb-4 text-[#d65d0e]! scanlined inline-block px-2">
						{`> recent learning (external)`}
					</h2>

					{isLoading && <div>Loading...</div>}

					{error ? (
						<div className="border-l-2 border-[#cc241d] px-3 bg-[#cc241d]/20">
							Error fetching recent learning
						</div>
					) : (
						<EolasEntries entries={data?.data} />
					)}
				</section>
			</div>
		</div>
	)
}

export default EolasListing
