import {
	ChevronDown,
	CloudSync,
	ExternalLink,
	type LucideIcon,
	Mail,
	MessagesSquare,
	NotebookPen,
	Paperclip,
	Search,
	ShoppingBag,
	UserCog,
	UserPen,
} from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import LoadingButton from "~/components/custom_ui/loading-button";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
} from "~/components/ui/dialog";
import { Textarea } from "~/components/ui/textarea";
import { useMediaQuery } from "~/hooks/use-media-query";
import { useUserViewContext } from "~/lib/userViewContext";
import { cn } from "~/lib/utils";

import { api } from "~/utils/api";
import { Confirm } from "../confirm";
import { WhatsAppIcon2 } from "../svgs";
import { Button } from "../ui/button";
import { Separator } from "../ui/separator";

export const UserViewHeader = () => {
	const data = useUserViewContext();
	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/load-page");
		},
	});
	const utils = api.useUtils();
	const { mutateAsync: sendInvite } = api.invite.sendInvite.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success("Email inviata con successo");
			await utils.comunicazioni.getEmails.invalidate({
				userId: data?.id || "",
			});
		},
	});
	const isDesktop = useMediaQuery("(min-width:  640px)");

	const links: { label: string; slug: string; icon: LucideIcon }[] = [
		{
			label: "Profilo",
			slug: "edit-user",
			icon: UserCog,
		},
		{
			label: "Ricerca",
			slug: "ricerca",
			icon: Search,
		},
		{
			label: "Comunicazioni",
			slug: "comunicazioni",
			icon: Mail,
		},
		{
			label: "Ordini",
			slug: "ordini",
			icon: ShoppingBag,
		},
		{
			label: "Allegati",
			slug: "allegati",
			icon: Paperclip,
		},
	];
	useEffect(() => {
		setUtilOpen(isDesktop);
		setNavOpen(isDesktop);
	}, [isDesktop]);
	const [utilOpen, setUtilOpen] = useState(isDesktop);
	const [navOpen, setNavOpen] = useState(isDesktop);

	if (!data) return <div>Errore</div>;
	return (
		<div className="mb-5 flex flex-col gap-y-3">
			<div className="text-3xl">{data.username}</div>

			<div className="grid grid-cols-2 items-center gap-2 sm:hidden">
				<Button
					className="w-full"
					onClick={() => {
						if (utilOpen) {
							setUtilOpen(false);
							return;
						}
						if (navOpen) {
							setNavOpen(false);
						}
						setUtilOpen(true);
					}}
					size="sm"
					variant="outline"
				>
					Utilità
					<ChevronDown className={cn(utilOpen && "rotate-180")} />
				</Button>
				<Button
					className="w-full"
					onClick={() => {
						if (navOpen) {
							setNavOpen(false);
							return;
						}
						if (utilOpen) {
							setUtilOpen(false);
						}
						setNavOpen(true);
					}}
					size="sm"
					variant="outline"
				>
					Navigazione <ChevronDown className={cn(navOpen && "rotate-180")} />
				</Button>
			</div>

			{utilOpen && (
				<div className="flex flex-row flex-wrap gap-2">
					<Link href={`https://wa.me/${data.telefono}`} target="_blank">
						<Button size="sm" variant="success">
							<WhatsAppIcon2 className="size-4 fill-white" />
							WhatsApp{data.extra_telefono_numero && ` (${data.nome})`}
						</Button>
					</Link>
					{data.extra_telefono_numero && (
						<Link
							href={`https://wa.me/${data.extra_telefono_numero}`}
							target="_blank"
						>
							<Button size="sm" variant="success">
								<WhatsAppIcon2 className="size-4 fill-white" />
								WhatsApp ({data.extra_telefono_titolo})
							</Button>
						</Link>
					)}
					{data.codice_fiscale ? (
						<IntestazioneMaker />
					) : (
						<Button disabled size="sm">
							<UserPen /> Intestazione
						</Button>
					)}
					<Confirm
						description={`Verrà inviata un'email di invito al sito all'indirizzo ${data.email}`}
						onConfirm={async () => {
							await sendInvite({ id: data.id });
						}}
						title="Vuoi mandare l'email di invito al sito?"
					>
						<Button size="sm" variant="info">
							<Mail /> Invita al sito
						</Button>
					</Confirm>
					<NoteUtenteDialog />
					<OverseerButton />
				</div>
			)}

			{navOpen && (
				<div className="flex flex-row flex-wrap gap-2">
					{links.map((link) => (
						<Link
							href={`/area-riservata/admin/user-view/${link.slug}/${data.id}`}
							key={link.slug}
						>
							<Button
								size="sm"
								variant={pathname.includes(link.slug) ? "secondary" : "outline"}
							>
								{<link.icon />} {link.label}
							</Button>
						</Link>
					))}

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

					<Button
						onClick={() =>
							swap({
								id: data.id,
							})
						}
						size="sm"
					>
						<ExternalLink /> Login
					</Button>
				</div>
			)}

			<Separator />
		</div>
	);
};

const OverseerButton = () => {
	const data = useUserViewContext();
	const [overseer, setOverseer] = useState<OverseerCapture | null>(null);
	useEffect(() => {
		if (typeof window !== "undefined" && window.OverseerCapture) {
			setOverseer(window.OverseerCapture);
		}
	}, []);

	const handleSendToOverseer = () => {
		if (overseer) {
			overseer.capture({
				cognome: data.cognome,
				nome: data.nome,
				cf: data.codice_fiscale || undefined,
				telefono: data.telefono,
				email: data.email,
				data_nascita: data.data_nascita?.toISOString() || undefined,
				luogo_nascita: data.luogo_nascita || undefined,
				naz_residenza: data.nazione_residenza || undefined,
				provincia_residenza: data.provincia_residenza || undefined,
				cap_residenza: data.cap_residenza || undefined,
				comune_residenza: data.comune_residenza || undefined,
				indirizzo_residenza: data.via_residenza || undefined,
				civico_residenza: data.civico_residenza || undefined,
			});
		} else {
			console.warn("Overseer extension not installed");
		}
	};

	return (
		<Button
			disabled={!overseer}
			onClick={handleSendToOverseer}
			size="sm"
			variant="outline"
		>
			<CloudSync />
		</Button>
	);
};

const IntestazioneMaker = () => {
	const data = useUserViewContext();
	const { mutate } = api.users.genIntestazione.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: (intestazione) => {
			navigator.clipboard
				.writeText(intestazione)
				.then(() => {
					toast.success("Intestazione copiata negli appunti");
				})
				.catch(() => {
					toast.error("Errore nella copia");
				});
		},
	});

	const isDisabled =
		!data.sesso ||
		!data.cognome ||
		!data.nome ||
		!data.data_nascita ||
		!data.luogo_nascita ||
		!data.comune_residenza ||
		!data.via_residenza;

	return (
		<Button
			disabled={isDisabled}
			onClick={() => mutate({ userId: data.id })}
			size="sm"
		>
			<UserPen /> Intestazione
		</Button>
	);
};

const NoteUtenteDialog = () => {
	const { id, note } = useUserViewContext();
	const [newNote, setNewNote] = useState(note || "");
	const utils = api.useUtils();
	const { mutate, isPending } = api.users.editUser.useMutation({
		onSuccess: async () => {
			toast.success("Note aggiornate con successo");
			await utils.users.invalidate();
		},
		onError: (error) => {
			toast.error(error.message);
		},
	});

	return (
		<Dialog>
			<DialogTrigger asChild>
				<div className="relative inline-flex">
					<Button className="inline-flex" size="sm" variant="orange">
						<NotebookPen className="size-4" /> Note
					</Button>
					{note && note.trim().length > 0 && (
						<span className="absolute top-0 right-0 -mt-1 -mr-1 flex size-3">
							<span className="relative inline-flex size-3 rounded-full bg-green-500"></span>
						</span>
					)}
				</div>
			</DialogTrigger>
			<DialogContent className="sm:max-w-2xl">
				<DialogHeader>
					<DialogTitle>Note Utente</DialogTitle>
					<DialogDescription className="sr-only">note</DialogDescription>
				</DialogHeader>
				<div className="flex w-full flex-col gap-4">
					<Textarea
						className="min-h-64"
						id="note"
						onChange={(e) => setNewNote(e.target.value)}
						placeholder=""
						value={newNote}
					/>
					<LoadingButton
						disabled={newNote === note}
						loading={isPending}
						onClick={() => mutate({ id, data: { note: newNote } })}
						variant="success"
					>
						Salva
					</LoadingButton>
				</div>
			</DialogContent>
		</Dialog>
	);
};
