import { getCookie } from "cookies-next";
import {
	ExternalLink,
	Mail,
	MessagesSquare,
	Paperclip,
	Search,
	ShoppingBag,
	Tickets,
	UserCog,
} from "lucide-react";
import Head from "next/head";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useRouter } from "next/router";
import { type ReactNode, useContext } from "react";
import toast from "react-hot-toast";
import {
	SIDEBAR_COOKIE_NAME,
	Sidebar,
} from "~/components/area-riservata/sidebar";
import { BannerFactory } from "~/components/banners";
import { Footer, MiniFooter } from "~/components/footer";
import { LoadingPage } from "~/components/loading";
import { SiteHeader } from "~/components/navbar/site-header";
import { WhatsAppIcon2 } from "~/components/svgs";
import { Button } from "~/components/ui/button";
import { Separator } from "~/components/ui/separator";
import { UserViewContext, UserViewProvider } from "~/lib/userViewContext";
import { cn } from "~/lib/utils";
import { useTranslation } from "~/providers/I18nProvider";
import {
	EnforcedSessionContext,
	useSession,
} from "~/providers/SessionProvider";
import type { UsersId } from "~/schemas/public/Users";
import type { ValidSession } from "~/server/api/trpc";
import { api } from "~/utils/api";

interface Props {
	bodyClassName?: string;
	containerClassName?: string;
	children: ReactNode;
	noFooter?: boolean;
	footerClassName?: string;
}
export const Layout = ({
	children,
	noFooter,
	bodyClassName,
	containerClassName,
	footerClassName,
}: Props) => {
	const { data: bannerData } = api.settings.getBannerData.useQuery({
		area_riservata: false,
	});

	return (
		<div className={cn("flex min-h-screen w-full flex-col", bodyClassName)}>
			<SiteHeader />
			{bannerData?.map((banner) => (
				<div key={`banner-elem-${banner.idbanner}`}>
					{BannerFactory(banner)}
				</div>
			))}
			<main className={cn("h-full flex-1 grow", containerClassName)}>
				{children}
			</main>

			{!noFooter && <Footer className={footerClassName} />}
			{/* <CookieConsent /> */}
		</div>
	);
};

interface AreaRiservataLayoutProps extends Props {
	ignoreSessionCheck?: boolean;
	noSidebar?: boolean;
}

export const AreaRiservataLayout = ({
	children,
	noSidebar,
	noFooter,
	ignoreSessionCheck,
	bodyClassName,
	containerClassName,
	footerClassName,
}: AreaRiservataLayoutProps) => {
	const { data: bannerData } = api.settings.getBannerData.useQuery({
		area_riservata: true,
	});
	const session = useSession();
	if (!ignoreSessionCheck) {
		if (session.status === "pending")
			return (
				<div
					className={cn(
						"flex h-full min-h-screen flex-col text-clip",
						bodyClassName,
					)}
				>
					<SiteHeader />

					<main
						className={cn(
							"flex h-full flex-1 overflow-auto",
							containerClassName,
						)}
					>
						<div className="flex h-auto w-full flex-col md:flex-row">
							<LoadingPage />
						</div>
					</main>
					{!noFooter && <MiniFooter className={footerClassName} />}
				</div>
			);
		if (session.status !== "success" || !session.user) {
			window.location.reload();
			return (
				<div
					className={cn(
						"flex h-full min-h-screen flex-col text-clip",
						bodyClassName,
					)}
				>
					<SiteHeader />

					<main
						className={cn(
							"flex h-full flex-1 overflow-auto",
							containerClassName,
						)}
					>
						<div className="flex h-auto w-full flex-col md:flex-row">
							<LoadingPage />
						</div>
					</main>
					{!noFooter && <MiniFooter className={footerClassName} />}
				</div>
			);
		}
	}

	return (
		<div
			className={cn(
				"flex h-full min-h-screen flex-col text-clip",
				bodyClassName,
			)}
		>
			<SiteHeader />
			{bannerData?.map((banner) => (
				<div key={`banner-elem-${banner.idbanner}`}>
					{BannerFactory(banner)}
				</div>
			))}
			<main
				className={cn("flex h-full flex-1 overflow-auto", containerClassName)}
			>
				<div className="flex h-auto w-full flex-col md:flex-row">
					{noSidebar ? null : (
						<Sidebar
							defaultOpen={getCookie(SIDEBAR_COOKIE_NAME) === "true"}
							isAdmin={session.user?.isAdmin || false}
						/>
					)}
					<EnforcedSessionContext.Provider value={session as ValidSession}>
						{children}
					</EnforcedSessionContext.Provider>
				</div>
			</main>
			{!noFooter && <MiniFooter className={footerClassName} />}

			{/* <CookieConsent /> */}
		</div>
	);
};

export const AreaRiservataLayoutUserView = ({
	children,
}: {
	children: ReactNode & { props: { userId: UsersId } };
}) => {
	const { t } = useTranslation();

	const props = children.props as { userId: UsersId };

	return (
		<div className="flex h-full min-h-screen flex-col bg-white">
			<SiteHeader />
			<main className="flex h-full flex-1 overflow-auto">
				<UserViewProvider userId={props.userId}>
					<Head>
						<title>{t.heads.area_riservata_titolo}</title>
						<meta
							content={t.heads.area_riservata_description}
							name="description"
						/>
					</Head>
					<div className="flex h-auto w-full flex-col md:flex-row">
						<Sidebar
							defaultOpen={getCookie(SIDEBAR_COOKIE_NAME) === "true"}
							isAdmin
						/>

						<div className="mx-4 my-3 flex-1 overflow-auto">
							<UserViewHeader />

							{children}
						</div>
					</div>
				</UserViewProvider>
			</main>

			<MiniFooter />

			{/* <CookieConsent /> */}
		</div>
	);
};

const UserViewHeader = () => {
	const data = useContext(UserViewContext);
	const pathname = usePathname();
	const router = useRouter();
	const { mutate: swap } = api.auth.swapUser.useMutation({
		onSuccess: async () => {
			toast.success("Utente cambiato con successo");
			await router.push("/area-riservata/dashboard");
			router.reload();
		},
	});
	if (!data) return <div>Errore</div>;
	return (
		<div className="mb-5 flex flex-col space-y-5">
			<div className="flex flex-row flex-wrap items-baseline gap-3">
				<div className="text-3xl">{data.username}</div>
				<div className="text-muted-foreground text-sm">
					{data.email} | {data.telefono}
				</div>

				<Link href={`https://wa.me/${data.telefono}`} target="_blank">
					<Button size="sm" variant="success">
						<WhatsAppIcon2 className="size-4 fill-white" />
						WhatsApp
					</Button>
				</Link>
			</div>
			<div className="flex flex-row flex-wrap gap-2">
				<Link href={`/area-riservata/admin/user-view/edit-user/${data.id}`}>
					<Button
						className="border"
						size="sm"
						variant={pathname.includes("edit-user") ? "secondary" : "outline"}
					>
						<UserCog /> Profilo
					</Button>
				</Link>
				<Link href={`/area-riservata/admin/user-view/servizio/${data.id}`}>
					<Button
						className="border"
						size="sm"
						variant={pathname.includes("servizio") ? "secondary" : "outline"}
					>
						<Tickets /> Servizi
					</Button>
				</Link>

				<Link href={`/area-riservata/admin/user-view/ricerca/${data.id}`}>
					<Button
						className="border"
						size="sm"
						variant={pathname.includes("ricerca") ? "secondary" : "outline"}
					>
						<Search /> Ricerca
					</Button>
				</Link>
				<Link href={`/area-riservata/admin/user-view/comunicazioni/${data.id}`}>
					<Button
						className="border"
						size="sm"
						variant={
							pathname.includes("comunicazioni") ? "secondary" : "outline"
						}
					>
						<Mail /> Comunicazioni
					</Button>
				</Link>

				<Link href={`/area-riservata/admin/user-view/ordini/${data.id}`}>
					<Button
						className="border"
						size="sm"
						variant={pathname.includes("ordini") ? "secondary" : "outline"}
					>
						<ShoppingBag /> Ordini
					</Button>
				</Link>
				<Link href={`/area-riservata/admin/user-view/allegati/${data.id}`}>
					<Button
						className="border"
						size="sm"
						variant={pathname.includes("allegati") ? "secondary" : "outline"}
					>
						<Paperclip /> Allegati
					</Button>
				</Link>

				<Link
					href={
						data.chatid
							? {
									pathname: "/area-riservata/admin/chats",
									query: { chatid: data.chatid },
								}
							: "/area-riservata/admin/chats"
					}
					target="_blank"
				>
					<Button
						className="border"
						size="sm"
						variant={!data.chatid ? "ghost" : "outline"}
					>
						<MessagesSquare /> Chat
					</Button>
				</Link>

				<Button
					className="flex gap-2"
					onClick={() =>
						swap({
							id: data.id,
						})
					}
					size="sm"
				>
					<ExternalLink /> Login
				</Button>
			</div>
			<Separator />
		</div>
	);
};
