"use client";
import { useState } from "react";
import QrCodeCard from "@/components/QrCodeCard";

const QUICK_LINKS = ["/", "/shop", "/community", "/blog", "/tips", "/subscription/plans", "/about", "/contact"];

export default function AdminQrCodesPage() {
  const [mode, setMode] = useState<"site" | "custom">("site");
  const [path, setPath] = useState("/");
  const [customUrl, setCustomUrl] = useState("https://");
  const [generated, setGenerated] = useState<{ type: "site"; path: string } | { type: "custom"; url: string } | null>({ type: "site", path: "/" });

  function generate() {
    if (mode === "site") {
      setGenerated({ type: "site", path: path || "/" });
    } else {
      const url = customUrl.trim();
      if (!url.startsWith("http://") && !url.startsWith("https://")) return;
      setGenerated({ type: "custom", url });
    }
  }

  const qrSrc = generated
    ? generated.type === "site"
      ? `/api/qr?path=${encodeURIComponent(generated.path)}`
      : `/api/qr?url=${encodeURIComponent(generated.url)}`
    : null;

  const qrLabel = generated
    ? generated.type === "site"
      ? generated.path
      : generated.url
    : "";

  const downloadName = generated
    ? generated.type === "site"
      ? `qr-${generated.path.replace(/\//g, "-").replace(/^-/, "") || "home"}.png`
      : `qr-${(new URL(generated.url).hostname)}.png`
    : "qr.png";

  return (
    <div className="max-w-lg">
      <h2 className="text-lg font-semibold mb-1">QR Codes</h2>
      <p className="text-neutral-500 text-sm mb-5">
        Generate a scannable QR code for any site page or any external URL — great for print materials, flyers, or in-person events.
      </p>

      <div className="card p-5 mb-5">
        {/* Mode toggle */}
        <div className="flex gap-0 mb-4 bg-neutral-900 border border-neutral-800 rounded-lg p-1 w-fit">
          <button
            type="button"
            onClick={() => setMode("site")}
            className={`px-4 py-1.5 rounded-md text-sm font-medium transition-colors ${mode === "site" ? "bg-red-600 text-white" : "text-neutral-400 hover:text-white"}`}
          >
            🌐 Site page
          </button>
          <button
            type="button"
            onClick={() => setMode("custom")}
            className={`px-4 py-1.5 rounded-md text-sm font-medium transition-colors ${mode === "custom" ? "bg-red-600 text-white" : "text-neutral-400 hover:text-white"}`}
          >
            🔗 Custom URL
          </button>
        </div>

        {mode === "site" ? (
          <>
            <label className="block text-sm mb-1.5 text-neutral-400">Page path</label>
            <div className="flex gap-2 mb-3">
              <input
                value={path}
                onChange={(e) => setPath(e.target.value)}
                placeholder="/shop/some-product"
                className="flex-1 bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600"
              />
              <button onClick={generate} className="btn-primary px-4 py-2 text-sm shrink-0">Generate</button>
            </div>
            <p className="text-xs text-neutral-500 mb-2">Quick picks:</p>
            <div className="flex flex-wrap gap-1.5">
              {QUICK_LINKS.map((l) => (
                <button
                  key={l}
                  onClick={() => { setPath(l); setGenerated({ type: "site", path: l }); }}
                  className={`text-xs px-2.5 py-1 rounded-full transition-colors ${path === l && generated?.type === "site" ? "bg-red-600 text-white" : "bg-neutral-800 hover:bg-neutral-700 text-neutral-300"}`}
                >
                  {l}
                </button>
              ))}
            </div>
          </>
        ) : (
          <>
            <label className="block text-sm mb-1.5 text-neutral-400">Full URL</label>
            <div className="flex gap-2">
              <input
                value={customUrl}
                onChange={(e) => setCustomUrl(e.target.value)}
                placeholder="https://youtube.com/your-channel"
                className="flex-1 bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600"
              />
              <button onClick={generate} className="btn-primary px-4 py-2 text-sm shrink-0">Generate</button>
            </div>
            <p className="text-xs text-neutral-500 mt-2">Any valid URL — social media, external sites, donation pages, etc.</p>
          </>
        )}
      </div>

      {qrSrc && (
        <div className="card p-5 text-center">
          <img src={qrSrc} alt={`QR code for ${qrLabel}`} className="w-40 h-40 mx-auto rounded-md bg-white p-1 mb-3" />
          <p className="text-xs text-neutral-400 break-all mb-3 max-w-xs mx-auto">{qrLabel}</p>
          <a href={qrSrc} download={downloadName} className="btn-secondary inline-block px-4 py-2 text-sm">
            ⬇ Download QR Code
          </a>
        </div>
      )}
    </div>
  );
}
