"use client";

import { useEffect, useState } from "react";
import { api } from "@/lib/api";

const PRODUCT = { name: "Cold Brew Coffee — 1L", price: 2000 };

export default function StorePage() {
  const [ref, setRef] = useState("");
  const [coupon, setCoupon] = useState("");
  const [result, setResult] = useState<Record<string, unknown> | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    const r = new URLSearchParams(window.location.search).get("ref") || "";
    setRef(r);
    if (r) setCoupon(r);
  }, []);

  const buy = async () => {
    setBusy(true);
    setResult(null);
    try {
      const code = coupon || ref;
      const r = await api.post("/checkout/simulate", {
        code,
        amount: PRODUCT.price,
        via: ref && coupon === ref ? "click" : "coupon",
        customerEmail: "buyer@example.com",
      });
      setResult(r);
    } catch (e) {
      setResult({ attributed: false, reason: (e as Error).message });
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="mx-auto max-w-lg space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Caffeine — Demo store</h1>
        {ref && (
          <p className="mt-1 text-sm text-green-700">
            You arrived via affiliate referral <b>{ref}</b> (click tracked ✓)
          </p>
        )}
      </div>

      <div className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm">
        <div className="flex items-center gap-4">
          <div className="flex h-20 w-20 items-center justify-center rounded-lg bg-amber-100 text-3xl">☕</div>
          <div>
            <h2 className="font-semibold">{PRODUCT.name}</h2>
            <p className="text-xl font-bold">₹{PRODUCT.price.toLocaleString("en-IN")}</p>
          </div>
        </div>

        <label className="mt-5 block">
          <span className="text-sm font-medium">Coupon code (optional)</span>
          <input
            value={coupon}
            onChange={(e) => setCoupon(e.target.value.toUpperCase())}
            placeholder="e.g. SARA10"
            className="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 outline-none focus:border-[var(--brand)]"
          />
        </label>

        <button
          onClick={buy}
          disabled={busy}
          className="mt-4 w-full rounded-lg bg-[var(--brand)] px-4 py-2.5 font-medium text-white disabled:opacity-60"
        >
          {busy ? "Placing order…" : `Buy now — ₹${PRODUCT.price.toLocaleString("en-IN")}`}
        </button>
      </div>

      {result && (
        <div
          className={`rounded-xl border p-4 text-sm ${
            result.attributed
              ? "border-green-200 bg-green-50 text-green-900"
              : "border-gray-200 bg-gray-50 text-gray-700"
          }`}
        >
          {result.attributed ? (
            <>
              ✅ Order placed! Attributed to{" "}
              <b>{(result.affiliate as { name: string }).name}</b>. Commission{" "}
              <b>₹{String(result.commission)}</b> ({String(result.rule)}) credited.
              Their new balance: ₹{String(result.newBalance)}.
              <div className="mt-1 text-xs text-green-700">
                Check the affiliate&apos;s dashboard — earnings just went up.
              </div>
            </>
          ) : (
            <>Order placed, but not attributed: {String(result.reason)}</>
          )}
        </div>
      )}
    </div>
  );
}
