import { RefreshCcw } from "lucide-react";
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 { PrezzarioTable } from "~/components/tables/prezziario-tables";
import { Button } from "~/components/ui/button";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
} from "~/components/ui/dialog";
import { FormPrezzo } from "~/forms/FormPrezzo";
import type { NextPageWithLayout } from "~/pages/_app";
import type {
	Prezziario,
	PrezziarioIdprezziario,
} from "~/schemas/public/Prezziario";
import { generateSSGHelper } from "~/server/utils/ssgHelper";
import { api } from "~/utils/api";

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

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

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

	if (isLoading) return <LoadingPage />;
	if (!data) return <Status500 />;
	return (
		<>
			<Head>
				<title>Prezziario - 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-2xl">Prezziario</h3>
							<button
								className="cursor-pointer"
								onClick={async () => await refetch()}
								type="button"
							>
								<RefreshCcw className="size-6" />
							</button>
						</div>
						<div className="mt-3 md:mt-0">
							<NewPrezzoModal />

							<EditPrezzoModal
								initial={editData}
								open={openEdit}
								setOpen={handleOpen}
							/>
						</div>
					</div>

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

export async function getServerSideProps() {
	const helpers = generateSSGHelper();

	await helpers.prezziario.getPrezziario.prefetch();

	return {
		props: {
			trpcState: helpers.dehydrate(),
		},
	};
}

export default Admin_Prezziario;

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

const NewPrezzoModal = () => {
	const utils = api.useUtils();
	const { mutate } = api.prezziario.addPrezziario.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success("Successo");
			await utils.prezziario.getPrezziario.invalidate();
			setOpen(false);
		},
	});
	const [open, setOpen] = useState(false);
	return (
		<Dialog onOpenChange={setOpen} open={open}>
			<DialogTrigger asChild>
				<Button variant="outline">Aggiungi Servizio</Button>
			</DialogTrigger>
			<DialogContent className="sm:max-w-106.25">
				<DialogHeader>
					<DialogTitle>Aggiungi Servizio</DialogTitle>
					<DialogDescription className="sr-only">Edit</DialogDescription>
				</DialogHeader>
				<div className="py-4">
					<FormPrezzo
						initialValues={{
							desc_en: "translations to be inserted",
							desc_it: "traduzioni da inserire",
							idprezziario: "" as PrezziarioIdprezziario,
							order_type: null,
							service_type: null,
							service_variant: null,
							isActive: true,
							nome_en: "New service",
							nome_it: "Nuovo servizio",
							prezzo_cent: 0,
							sconto: 0,
							testo_condizioni: "",
						}}
						submitMutation={(fields) => {
							mutate({
								data: {
									...fields,
								},
							});
						}}
					/>
				</div>
			</DialogContent>
		</Dialog>
	);
};
const EditPrezzoModal = ({
	initial,
	open,
	setOpen,
}: {
	initial: Prezziario | null;
	open: boolean;
	setOpen: (status: boolean) => void;
}) => {
	const utils = api.useUtils();
	const { mutate } = api.prezziario.updatePrezziario.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success("Successo");
			await utils.prezziario.getPrezziario.invalidate();
			setOpen(false);
		},
	});

	if (!initial) return null;

	return (
		<Dialog onOpenChange={setOpen} open={open}>
			<DialogContent className="sm:max-w-5xl md:max-w-8xl">
				<DialogHeader>
					<DialogTitle>Modifica Servizio</DialogTitle>
					<DialogDescription className="sr-only">
						Modifica i dettagli del servizio
					</DialogDescription>
				</DialogHeader>
				<div className="max-h-[80vh] overflow-auto py-4">
					<FormPrezzo
						initialValues={{
							...initial,
						}}
						submitMutation={(fields) => {
							mutate({
								data: {
									...fields,
								},
								idprezziario: fields.idprezziario,
							});
						}}
					/>
				</div>
			</DialogContent>
		</Dialog>
	);
};
