"use client";

import { useState } from "react";
import { api } from "~/trpc/react";

export function LatestPost() {
	const [latestPost] = api.post.getLatest.useSuspenseQuery();
	const trpcUtilities = api.useUtils();
	const [name, setName] = useState("");
	const createPost = api.post.create.useMutation({
		onSuccess: async () => {
			await trpcUtilities.post.invalidate();
			setName("");
		},
	});

	return (
		<div className="w-full max-w-sm">
			{latestPost ? (
				<p className="truncate text-[#999999]">
					your most recent post:{" "}
					<span className="text-white">{latestPost.name}</span>
				</p>
			) : (
				<p className="text-[#666666]">you have no posts yet.</p>
			)}
			<form
				className="mt-3 flex flex-col gap-3"
				onSubmit={(formSubmitEvent) => {
					formSubmitEvent.preventDefault();
					createPost.mutate({ name });
				}}
			>
				<input
					className="w-full border border-[#2a2a2a] bg-[#0f0f0f] px-3 py-2 text-white placeholder:text-[#666666] focus:border-[#666666]"
					onChange={(inputChangeEvent) =>
						setName(inputChangeEvent.target.value)
					}
					placeholder="title"
					type="text"
					value={name}
				/>
				<button
					className="w-full border border-[#2a2a2a] bg-[#0f0f0f] px-4 py-2 text-white transition-colors duration-100 hover:border-[#666666] disabled:text-[#666666] disabled:hover:border-[#2a2a2a]"
					disabled={createPost.isPending}
					type="submit"
				>
					{createPost.isPending ? "submitting ..." : "submit"}
				</button>
			</form>
		</div>
	);
}
