import { Download } from "lucide-react";
import Link from "next/link";
import { ExtIcon } from "~/components/area-riservata/allegati";

import { LoadingPage } from "~/components/loading";
import { Button } from "~/components/ui/button";
import { getStorageUrl } from "~/lib/storage_utils";
import type { MessagesMessageid } from "~/schemas/public/Messages";
import { api } from "~/utils/api";

export const ChatAttachments = ({
	messageId,
}: {
	messageId: MessagesMessageid;
}) => {
	const { data, isLoading } = api.chat.getMessageAttachments.useQuery(
		{ messageId },
		{ refetchOnMount: true },
	);

	if (isLoading) {
		return <LoadingPage />;
	}
	if (!data || data.length === 0) {
		return null;
	}

	return (
		<div className="mt-1 flex flex-col items-end gap-1">
			{data.map((file) => (
				<div
					className="flex w-fit items-center justify-end gap-2 rounded-md bg-secondary p-2 text-sm hover:bg-muted/50"
					key={file.id}
				>
					<div className="flex grow basis-full items-center gap-2 md:col-span-8">
						<div className="shrink-0">
							<ExtIcon mimeType={file.mimeType} />
						</div>
						<Link
							aria-label="Allegato"
							className="max-w-md truncate font-medium text-foreground hover:underline"
							href={`/area-riservata/allegato-view/${file.id}`}
							target="_blank"
						>
							{file.originalName}
						</Link>
					</div>

					<div className="flex justify-end gap-1 md:col-span-1">
						<Link
							href={getStorageUrl({
								storageId: file.id,
								params: { mode: "download" },
							})}
						>
							<Button className="flex size-8 gap-1 text-sm" size="icon">
								<Download className="size-4" />
							</Button>
						</Link>
					</div>
				</div>
			))}
		</div>
	);
};
