"use client";

import { useState } from "react";
import { AGENT_PRICE_GHS, COURSE_PRICE_GHS, REGISTRATION_PRICE_GHS } from "@/lib/pricing";

export function PayBox({
  kind,
  course,
  title,
  locked,
}: {
  kind: "registration" | "course" | "agent";
  course?: string;
  title: string;
  locked: boolean;
}) {
  const [error, setError] = useState("");
  const [pending, setPending] = useState(false);
  const price =
    kind === "agent" ? AGENT_PRICE_GHS : kind === "registration" ? REGISTRATION_PRICE_GHS : COURSE_PRICE_GHS;

  async function start(demo = false) {
    setError("");
    setPending(true);
    const res = await fetch("/api/paystack/initialize", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ kind, course }),
    });
    const json = await res.json();
    if (!res.ok) {
      setPending(false);
      setError(json.error || "Could not start payment");
      return;
    }
    if (json.authorization_url && !demo) {
      window.location.href = json.authorization_url;
      return;
    }
    if (demo && json.authorization_url && !json.demo) {
      setPending(false);
      setError("Paystack is live on this server. Use Pay with Paystack (MoMo or card).");
      return;
    }
    if (json.demo || demo) {
      const verify = await fetch("/api/paystack/verify", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ reference: json.reference, demo: true }),
      });
      const v = await verify.json();
      setPending(false);
      if (!verify.ok) {
        setError(v.error || "Demo unlock failed");
        return;
      }
      window.location.href =
        v.kind === "agent" ? "/agent" : v.course ? `/courses/${v.course}` : "/dashboard";
      return;
    }
    setPending(false);
    setError("No Paystack URL returned");
  }

  const blurb =
    kind === "registration"
      ? "Opens every blueprint for 72 hours. After that, each course is ₵40 to keep."
      : kind === "course"
        ? "Unlock this blueprint after the 3-day window. Tutor, worksheets, and quizzes stay open."
        : "Human replies in-app plus WhatsApp for 30 days.";

  return (
    <div className="rounded-3xl border border-forest/10 bg-cream p-6">
      <p className="text-xs uppercase tracking-widest text-terra">{title}</p>
      <p className="font-display mt-2 text-4xl text-forest">₵{price}</p>
      <p className="mt-2 text-sm text-forest/70">{blurb}</p>
      {locked ? (
        <p className="mt-6 text-sm font-medium text-forest">Already active on this account.</p>
      ) : (
        <div className="mt-6 space-y-3">
          <button
            disabled={pending}
            onClick={() => start(false)}
            className="w-full rounded-full bg-forest py-3 text-sm font-semibold text-gold-2 disabled:opacity-60"
          >
            {pending ? "Starting Paystack…" : "Pay with Paystack"}
          </button>
          <button
            disabled={pending}
            onClick={() => start(true)}
            className="w-full rounded-full border border-forest/20 py-3 text-sm text-forest disabled:opacity-60"
          >
            Local demo unlock
          </button>
        </div>
      )}
      {error ? <p className="mt-3 text-sm text-terra">{error}</p> : null}
    </div>
  );
}
