import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth";
import ClientErrorMessage from "@/components/client-error-message";
import { Badge } from "@/components/ui/badge";
import { FloatingLabelInput } from "@/components/ui/floating-label";
import { getProfileById } from "@/queries/users";
import { tryCatch } from "@/utils/tryCatch";

export default async function Profile() {
	const session = await getServerSession(authOptions);
	if (!session?.user) return redirect("/auth/signin?callbackUrl=/profile");
	const [error, profile] = await tryCatch(getProfileById(session?.user.id));
	if (error) {
		if (error.message === "Invalid token.") redirect("/auth/signin");
		return <ClientErrorMessage message={error.message} />;
	}
	return (
		<div>
			<div className="flex justify-between items-center font-bold border rounded-md border-dashed title-bg py-4 px-2 mb-4">
				<h3 className="text-sarLinkOrange text-2xl">Profile</h3>
				<div className="text-sarLinkOrange uppercase font-mono text-sm flex flex-col items-center rounded gap-2 py-2 px-4">
					<span>Profile Status</span>
					{verifiedStatus(profile?.verified ?? false)}
				</div>
			</div>
			<fieldset>
				<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4 max-w-4xl">
					<FloatingLabelInput
						id="floating-name"
						label="Full Name"
						value={`${profile?.first_name} ${profile?.last_name}`}
						readOnly
					/>
					<FloatingLabelInput
						id="floating-id-card"
						label="ID Card"
						value={`${profile?.id_card}`}
						readOnly
					/>
					<FloatingLabelInput
						id="floating-island"
						label="Island"
						value={`${profile?.atoll.name}. ${profile?.island.name}`}
						readOnly
					/>
					<FloatingLabelInput
						id="floating-dob"
						label="Date of Birth"
						value={`${new Date(
							profile?.dob.toString() ?? "",
						).toLocaleDateString("en-US", {
							month: "short",
							day: "2-digit",
							year: "numeric",
						})}`}
						readOnly
					/>
					<FloatingLabelInput
						id="floating-address"
						label="Address"
						value={`${profile?.address}`}
						readOnly
					/>
					<FloatingLabelInput
						id="floating-mobile"
						label="Phone Number"
						value={`${profile?.mobile}`}
						readOnly
					/>
					<FloatingLabelInput
						id="floating-account"
						label="Account Number"
						value={`${profile?.acc_no}`}
						readOnly
					/>
				</div>
			</fieldset>
			{/* <Suspense key={query} fallback={"loading...."}>
        <TopupsTable searchParams={searchParams} />
      </Suspense> */}
		</div>
	);
}

function verifiedStatus(status: boolean) {
	switch (status) {
		case true:
			return <Badge className="bg-green-500 text-white">Verified</Badge>;
		case false:
			return <Badge className="bg-red-500 text-white">Not Verified</Badge>;
		default:
			return <Badge className="bg-yellow-500 text-white">Unknown</Badge>;
	}
}
