"use client";

import { useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { CalendarClock, PartyPopper, UserPlus } from "lucide-react";
import { create } from "zustand";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useAuth } from "../auth/auth-context";
import { formatDate, formatQty } from "../lib/format";
import { showQueuedFlash } from "./sample-data-card";
import { trackOnboardingEvent, updateOnboardingMe } from "./useOnboarding";

/**
 * The one big moment (design S10): the first real PO on the board. Everything else gets a toast.
 * Lives in the shell so it survives the navigation to the new PO; shown once per user (`celebrated: ["first_po"]`).
 */
const useCelebrationStore = create(() => ({ celebration: null }));

/** celebration = { po: { poNo, buyer: { name }, totalQuantity, shipDate }, href } */
export function showCelebration(celebration) {
  useCelebrationStore.setState({ celebration });
}

export function CelebrationDialog() {
  const router = useRouter();
  const { can } = useAuth();
  const celebration = useCelebrationStore((state) => state.celebration);
  const po = celebration?.po;
  const close = () => useCelebrationStore.setState({ celebration: null });

  // Toasts queued before a full reload (e.g. after removing the sample) show once the new page is up.
  useEffect(() => { showQueuedFlash(); }, []);

  useEffect(() => {
    if (!celebration) return;
    trackOnboardingEvent("celebration_shown", { key: "first_po" });
    updateOnboardingMe({ celebrated_add: ["first_po"] }).catch(() => {});
  }, [celebration]);

  const plan = () => {
    const href = celebration?.href;
    close();
    if (!href) return;
    const [path, hash] = href.split("#");
    // Usually the PO is already open behind the dialog; jump to its time & action tab.
    if (window.location.pathname === path) window.location.hash = hash || "tna";
    else router.push(href);
  };

  return <Dialog open={Boolean(celebration)} onOpenChange={(open) => { if (!open) close(); }}>
    <DialogContent className="gap-6 sm:max-w-md">
      <div className="grid min-w-0 gap-4 pt-2 text-center">
        <span className="relative mx-auto grid size-16 place-items-center">
          <span className="absolute inset-0 rounded-full bg-success/10 motion-safe:animate-in motion-safe:fade-in motion-safe:zoom-in-50 motion-safe:duration-700" aria-hidden="true" />
          <PartyPopper className="relative size-8 text-success motion-safe:animate-in motion-safe:zoom-in-75 motion-safe:spin-in-12 motion-safe:duration-700" aria-hidden="true" />
        </span>
        <DialogHeader className="gap-2 text-center sm:text-center">
          <DialogTitle className="text-xl tracking-tight">Your first order is on the board</DialogTitle>
          <DialogDescription className="text-sm">
            <span className="font-medium text-foreground">{po?.poNo}</span> for {po?.buyer?.name || "your buyer"} · {formatQty(po?.totalQuantity)} · ships {formatDate(po?.shipDate)}.
          </DialogDescription>
        </DialogHeader>
        <p className="flex items-start gap-2 rounded-lg border bg-muted/40 p-3 text-left text-sm text-muted-foreground motion-safe:animate-in motion-safe:fade-in motion-safe:slide-in-from-bottom-2 motion-safe:duration-700">
          <CalendarClock className="mt-0.5 size-4 shrink-0 text-foreground" aria-hidden="true" />
          <span>Next, give it a time &amp; action plan. That&apos;s how the system warns you before a date slips, not after.</span>
        </p>
      </div>
      {/* Stacked, primary first: both labels are long and must never overflow on a phone. */}
      <div className="grid gap-2">
        <Button onClick={plan} autoFocus className="w-full"><CalendarClock /> Plan this order</Button>
        {can("users.create") && <Button variant="outline" className="w-full" asChild><Link href="/team?new=1" onClick={close}><UserPlus /> Invite the merchandiser who follows it</Link></Button>}
      </div>
    </DialogContent>
  </Dialog>;
}
