import type { GetServerSideProps } from "next";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Status500 } from "~/components/status-page";
import { Badge } from "~/components/ui/badge";
import { AnnuncioEditForm } from "~/forms/FormEditAnnuncio";
import { cn, redirectTo500 } from "~/lib/utils";
import type { NextPageWithLayout } from "~/pages/_app";
import type { AnnunciId } from "~/schemas/public/Annunci";
import { generateSSGHelper } from "~/server/utils/ssgHelper";
import { zAnnuncioId } from "~/server/utils/zod_types";
import { api } from "~/utils/api";

type AnnuncioEditProps = {
	id: AnnunciId;
};

/**
 * Pagina di modifica annuncio per admin: /area-riservata/admin/edit-annuncio/[id]
 */
const AnnuncioEdit: NextPageWithLayout<AnnuncioEditProps> = ({
	id,
}: AnnuncioEditProps) => {
	const { data, isLoading } = api.annunci.getAnnuncioById_rawImgUrls.useQuery(
		{
			id,
		},
		{ refetchOnMount: false },
	);

	if (isLoading) return <LoadingPage />;
	if (!data) {
		return <Status500 />;
	}

	return (
		<>
			<AnnuncioEditForm data={data} />
		</>
	);
};

export const getServerSideProps = (async (context) => {
	const annuncioId = context.params?.id && parseInt(String(context.params.id));

	const check = zAnnuncioId.safeParse(annuncioId);
	if (!check.success) {
		return redirectTo500;
	}

	const ssg = generateSSGHelper();

	await ssg.annunci.getAnnuncioById_rawImgUrls.prefetch({ id: check.data });

	return {
		props: {
			id: check.data,
			trpcState: ssg.dehydrate(),
		},
	};
}) satisfies GetServerSideProps<AnnuncioEditProps>;

export default AnnuncioEdit;

AnnuncioEdit.getLayout = function getLayout(page) {
	return <AreaRiservataLayout>{page}</AreaRiservataLayout>;
};

export const StatusBadge = ({ status }: { status: string | null }) => {
	let colore = "";
	switch (status) {
		case "Sospeso":
			colore = "bg-yellow-500 border-yellow-500 text-white";
			break;
		case "Trattativa":
			colore = "bg-purple-500 border-purple-500 text-white";
			break;
		case "Attivo":
			colore = "bg-green-500 border-green-500 text-white";
			break;
		default:
			colore = "bg-neutral-500 border-neutral-500 text-white";
			break;
	}

	return (
		<Badge className={cn("", colore)} variant="outline">
			{status}
		</Badge>
	);
};
