import { Plus, RefreshCcw } from "lucide-react";
import type { GetServerSideProps } from "next";
import Head from "next/head";
import { useState } from "react";
import toast from "react-hot-toast";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Status500 } from "~/components/status-page";
import { StringheTable } from "~/components/tables/stringhe-table";
import { Button } from "~/components/ui/button";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
} from "~/components/ui/dialog";
import { FormStringhe } from "~/forms/FormStringhe";
import type { NextPageWithLayout } from "~/pages/_app";
import type { TestiEStringhe } from "~/schemas/public/TestiEStringhe";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { api } from "~/utils/api";

/**
 * Pagina per la gestione dei testi e stringhe: /area-riservata/admin/testi-stringhe
 */
const AdminTestiStringhe: NextPageWithLayout = () => {
	const { data, isLoading, refetch } = api.strings.getStringhe.useQuery();
	const [openEdit, setOpenEdit] = useState(false);
	const [editData, setEditData] = useState<TestiEStringhe | null>(null);

	const handleOpen = (status: boolean) => {
		setOpenEdit(status);
	};
	const handleEdit = (data: TestiEStringhe | null) => {
		setEditData(data);
	};

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

	return (
		<>
			<Head>
				<title>Testi e Stringhe - Infoalloggi.it</title>
			</Head>
			<div className="mx-1 flex-1 overflow-auto">
				<div className="mx-auto pt-4">
					<div className="mx-auto items-start justify-between px-2 md:flex">
						<div className="flex items-center gap-3">
							<h3 className="font-bold text-accent-foreground text-xl sm:text-2xl">
								Testi e Stringhe
							</h3>
							<button
								className="cursor-pointer"
								onClick={async () => await refetch()}
								type="button"
							>
								<RefreshCcw className="size-6" />
							</button>
						</div>

						<div className="mt-3 md:mt-0">
							<EditModal
								initial={editData}
								open={openEdit}
								setOpen={handleOpen}
							/>
						</div>
						<div className="mt-3 md:mt-0">
							<Button
								className="font-semibold"
								onClick={() => {
									handleEdit(null);
									handleOpen(true);
								}}
								variant="outline"
							>
								<Plus className="size-6" />
								Nuovo
							</Button>
						</div>
					</div>

					<StringheTable
						data={data}
						setEditData={handleEdit}
						setOpenEdit={handleOpen}
					/>
				</div>
			</div>
		</>
	);
};

export const getServerSideProps = (async (context) => {
	const access_token = context.req.cookies.access_token;

	const helpers = await TrpcAuthedFetchingIstance({ access_token });
	if (helpers) {
		await helpers.trpc.strings.getStringhe.prefetch();
		return {
			props: {
				trpcState: helpers.trpc.dehydrate(),
			},
		};
	}
	return {
		props: {},
	};
}) satisfies GetServerSideProps;
export default AdminTestiStringhe;

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

const EditModal = ({
	initial,
	open,
	setOpen,
}: {
	initial: TestiEStringhe | null;
	open: boolean;
	setOpen: (status: boolean) => void;
}) => {
	const utils = api.useUtils();
	const { mutate: edit } = api.strings.updateStringa.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success("Successo");
			await utils.strings.getStringhe.invalidate();
			setOpen(false);
		},
	});
	const { mutate: add } = api.strings.newStringa.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success("Successo");
			await utils.strings.getStringhe.invalidate();
			setOpen(false);
		},
	});
	const { mutate: del } = api.strings.deleteStringa.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success("Successo");
			await utils.strings.getStringhe.invalidate();
			setOpen(false);
		},
	});

	return (
		<Dialog onOpenChange={setOpen} open={open}>
			<DialogTrigger asChild />
			<DialogContent className="sm:max-w-8xl">
				<DialogHeader>
					<DialogTitle>
						{!initial ? "Aggiungi Banner" : "Modifica Valori"}
					</DialogTitle>
					<DialogDescription className="sr-only">Edit</DialogDescription>
				</DialogHeader>
				{!initial ? (
					<div className="py-4">
						<FormStringhe
							initialValues={null}
							submitMutation={(fields) => {
								add({
									stringaId: fields.stinga_id,
									stringaValue: fields.stringa_value,
								});
							}}
						/>
					</div>
				) : (
					<div className="py-4">
						<FormStringhe
							del={(v) => del({ stringaId: v })}
							initialValues={{
								...initial,
							}}
							submitMutation={(fields) => {
								edit({
									stringaId: fields.stinga_id,
									stringaValue: fields.stringa_value,
								});
							}}
						/>
					</div>
				)}
			</DialogContent>
		</Dialog>
	);
};
