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 { FlagsTable } from "~/components/tables/flags-table";
import { Button } from "~/components/ui/button";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
} from "~/components/ui/dialog";
import { FormFlags } from "~/forms/FormFlags";
import type { NextPageWithLayout } from "~/pages/_app";
import type { Flags } from "~/schemas/public/Flags";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { api } from "~/utils/api";

/**
 * Pagina di gestione flags per admin: /area-riservata/admin/flags
 */
const AdminFlags: NextPageWithLayout = () => {
	const { data, isLoading, refetch } = api.flags.GetFlags.useQuery();
	const [openEdit, setOpenEdit] = useState(false);
	const [editData, setEditData] = useState<Flags | null>(null);

	const handleOpen = (status: boolean) => {
		setOpenEdit(status);
	};

	const handleEdit = (data: Flags | null) => {
		setEditData(data);
	};

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

	return (
		<>
			<Head>
				<title>Flags - Infoalloggi.it</title>
			</Head>
			<div className="mx-1 flex-1 overflow-auto">
				<div className="mx-auto pt-4">
					<div className="mx-3 items-start justify-between md:flex">
						<div className="flex max-w-lg items-center gap-3">
							<h3 className="font-bold text-accent-foreground text-xl sm:text-2xl">
								Impostazioni
							</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>

					<FlagsTable
						data={data}
						setEditData={handleEdit}
						setOpenEdit={handleOpen}
					/>
				</div>
			</div>
		</>
	);
};
export default AdminFlags;

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

	const helpers = await TrpcAuthedFetchingIstance({ access_token });
	if (helpers) {
		await helpers.trpc.flags.GetFlags.prefetch();
		return {
			props: {
				trpcState: helpers.trpc.dehydrate(),
			},
		};
	}
	return {
		props: {},
	};
}) satisfies GetServerSideProps;

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

const EditModal = ({
	initial,
	open,
	setOpen,
}: {
	initial: Flags | null;
	open: boolean;
	setOpen: (status: boolean) => void;
}) => {
	const utils = api.useUtils();
	const { mutate: edit } = api.flags.EditFlag.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success("Successo");
			await utils.flags.GetFlags.invalidate();
			setOpen(false);
		},
	});
	const { mutate: add } = api.flags.AddFlag.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success("Successo");
			await utils.flags.GetFlags.invalidate();
			setOpen(false);
		},
	});
	const { mutate: remove } = api.flags.RemoveFlag.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success("Successo");
			await utils.flags.GetFlags.invalidate();
			setOpen(false);
		},
	});

	return (
		<Dialog onOpenChange={setOpen} open={open}>
			<DialogContent className="sm:max-w-106.25">
				<DialogHeader>
					<DialogTitle>{initial ? "Modifica" : "Aggiungi"}</DialogTitle>
					<DialogDescription>
						{initial ? "Modifica i valori" : "Aggiungi un nuovo valore"}
					</DialogDescription>
				</DialogHeader>
				<div className="py-4">
					<FormFlags
						handleRemove={(id) =>
							remove({
								id,
							})
						}
						initialValues={initial}
						submitMutation={(fields) => {
							if (initial) {
								edit({
									id: initial.id,
									value: fields.value,
								});
							} else {
								add({
									id: fields.id,
									value: fields.value,
								});
							}
						}}
					/>
				</div>
			</DialogContent>
		</Dialog>
	);
};
