Files
co-lite/solvway-admin-portal/app/components/app/WhatsAppButton.tsx
T

72 lines
2.7 KiB
TypeScript

"use client";
import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { MessageCircle } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { Popover, PopoverAnchor, PopoverContent } from "@/app/components/ui/popover";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { ApiError } from "@/app/lib/clientApi";
import { startChat } from "@/app/lib/services/whatsapp";
import { useT } from "@/app/lib/i18n/MessagesProvider";
type Target = { leadUuid: string } | { eventLeadUuid: string };
/** Starts (or reopens) a WhatsApp chat with a lead. Opens it when the starter owns it; otherwise says who does. */
export function WhatsAppButton({ target, mobile }: { target: Target; mobile: string | null | undefined }) {
const t = useT();
const router = useRouter();
const { id, hasModule } = useAdminAuth();
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState<string | null>(null);
// Set when someone else owns the chat and the user is a WhatsApp Admin, who may open it anyway.
const [openHref, setOpenHref] = useState<string | null>(null);
if (!hasModule("BO_WHATSAPP") || !mobile) return null;
const start = () => {
setBusy(true);
setMessage(null);
setOpenHref(null);
startChat(target)
.then((c) => {
const href = `/whatsapp?c=${encodeURIComponent(c.uuid)}`;
if (c.ownerUserId == null || c.ownerUserId === id) return router.push(href);
setMessage(t("WaOwnedBy", { name: c.ownerName ?? "" }));
if (hasModule("BO_WHATSAPP_ADMIN")) setOpenHref(href);
})
.catch((err: unknown) => {
const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined;
setMessage(t(code === "WHATSAPP_NOT_CONFIGURED" ? "WaNotConfigured" : "WaStartFailed"));
})
.finally(() => setBusy(false));
};
return (
<Popover open={message !== null} onOpenChange={(open) => !open && setMessage(null)}>
<PopoverAnchor asChild>
<Button
variant="ghost"
size="icon-sm"
aria-label={t("BO_WHATSAPP")}
title={t("BO_WHATSAPP")}
disabled={busy}
onClick={start}
className="text-muted-foreground hover:text-foreground"
>
<MessageCircle aria-hidden="true" className="size-4" />
</Button>
</PopoverAnchor>
<PopoverContent className="w-64 text-sm">
<p role="status">{message}</p>
{openHref && (
<Link href={openHref} className="mt-2 inline-block font-medium text-primary underline-offset-4 hover:underline">
{t("WaOpenChat")}
</Link>
)}
</PopoverContent>
</Popover>
);
}