"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { buttonClass } from "@/components/ui";

// Prominent open/close banner at the top of the merch dashboard. A closed
// shop (the old default) hides every product from buyers, which is easy to
// miss when the only switch is a checkbox at the bottom of the settings form.
export default function ShopOpenToggle({
  open,
  liveProducts,
  slug,
}: {
  open: boolean;
  liveProducts: number;
  slug: string;
}) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function toggle() {
    setLoading(true);
    setError(null);
    const res = await fetch("/api/dashboard/merch/shop", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ open: !open }),
    });
    const data = await res.json().catch(() => ({}));
    setLoading(false);
    if (!res.ok) {
      setError(data.error ?? "Could not update the shop");
      return;
    }
    router.refresh();
  }

  const visible = open && liveProducts > 0;
  const message = !open
    ? "Your shop is CLOSED — buyers can't see any of your products."
    : liveProducts === 0
      ? "Your shop is open, but it has no live products yet — add one (and keep it marked active) so buyers can see it."
      : `Your shop is live at vibepasstickets.com/shop/${slug} with ${liveProducts} product${liveProducts === 1 ? "" : "s"}.`;

  return (
    <div
      className={`flex flex-wrap items-center justify-between gap-3 rounded-lg border p-4 text-sm ${
        visible ? "pill-ok" : "pill-warn"
      }`}
    >
      <p className="font-medium">{message}</p>
      <div className="flex items-center gap-3">
        {error && <span className="text-red-600">{error}</span>}
        <button
          type="button"
          onClick={toggle}
          disabled={loading}
          className={buttonClass(open ? "secondary" : "primary")}
        >
          {loading ? "Saving…" : open ? "Close shop" : "Open shop to buyers"}
        </button>
      </div>
    </div>
  );
}
