"use client";

import type { dockerRouterType } from "@/server/api/routers/docker";
import { api } from "@/trpc/react";
import type { JSX } from "react";

function DockerRow({
	containerInfo,
}: {
	containerInfo: dockerRouterType["list"][number];
}) {
	const { data: latest, isError, isLoading } = api.docker.latest.useQuery({ id: containerInfo.container.id });
	const outdated = containerInfo.image.current.hash !== latest?.latest.hash;

	let latestFragment: JSX.Element | null = null;
	if (isError) {
		latestFragment = (
			<>
				<td>{"Error"}</td>
				<td>{"Error"}</td>
			</>
		);
	} else if (isLoading) {
		latestFragment = (
			<>
				<td>
					<span className="loading loading-dots loading-lg" />
				</td>
				<td>
					<span className="loading loading-dots loading-lg" />
				</td>
			</>
		);
	} else if (latest) {
		latestFragment = (
			<>
				<td>{latest?.latest.tag}</td>
				<td>{latest?.latest.hash}</td>
			</>
		);
	}

	return (
		<tr key={containerInfo.container.name} className={`${outdated ? "bg-base-200" : null}`}>
			<td className={`border-l-8 ${isLoading ? "border-l-warning/80" : outdated ? "border-l-error/80" : "border-l-info/80"}`}>{containerInfo.container.name}</td>
			<td>{containerInfo.image.name}</td>
			<td>{containerInfo.image.current.tag}</td>
			<td>{containerInfo.image.current.hash}</td>
			{latestFragment}
		</tr>
	);
}

export function DockerTable() {
	const { data: list, isLoading: listLoading } = api.docker.list.useQuery();
	return (
		<div className="overflow-x-auto rounded-md border border-base-content/15 bg-base-100">
			{!listLoading ? (
				<table className="table-s table">
					<thead>
						<tr>
							<th>Name</th>
							<th>Image</th>
							<th>Tag</th>
							<th>Short Hash</th>
							<th>Tag</th>
							<th>Short Hash</th>
						</tr>
					</thead>
					<tbody>
						{list
							? list
									.sort((ca, cb) => {
										if (ca.container.name && cb.container.name) {
											if (ca.container.name < cb.container.name) {
												return -1;
											}
											if (ca.container.name > cb.container.name) {
												return 1;
											}
										}
										return 0;
									})
									.map((containerInfo) => <DockerRow key={containerInfo.container.name} containerInfo={containerInfo} />)
							: null}
					</tbody>
				</table>
			) : (
				<>Loading data...</>
			)}
		</div>
	);
}
