"use client";
import { useEffect, useState } from "react";
import { Clock, PlayCircle, FastForward } from "lucide-react";

type TestClock = { id: string; name: string; status: string; frozenTime: number };

export default function TestBillingPage() {
  const [clocks, setClocks] = useState<TestClock[]>([]);
  const [creating, setCreating] = useState(false);
  const [advancing, setAdvancing] = useState<string | null>(null);
  const [error, setError] = useState("");
  const [lastCreated, setLastCreated] = useState<any>(null);

  async function loadClocks() {
    const res = await fetch("/api/admin/test-billing/list");
    const data = await res.json();
    if (res.ok) setClocks(data.clocks);
  }

  useEffect(() => {
    loadClocks();
  }, []);

  async function createTestSubscription() {
    setCreating(true);
    setError("");
    const res = await fetch("/api/admin/test-billing/create", { method: "POST" });
    const data = await res.json();
    setCreating(false);
    if (!res.ok) {
      setError(data.error);
      return;
    }
    setLastCreated(data);
    loadClocks();
  }

  async function advanceClock(id: string, seconds: number) {
    setAdvancing(id);
    setError("");
    const res = await fetch("/api/admin/test-billing/advance", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ testClockId: id, advanceSeconds: seconds }),
    });
    const data = await res.json();
    setAdvancing(null);
    if (!res.ok) {
      setError(data.error);
      return;
    }
    loadClocks();
  }

  return (
    <div className="max-w-3xl">
      <h2 className="text-lg font-semibold mb-1">Test Recurring Billing</h2>
      <p className="text-xs text-neutral-500 mb-6">
        Stripe doesn't support hourly subscriptions — real recurring billing is always at least
        daily/monthly/etc. This uses Stripe's "Test Clocks" feature instead: create a real $1/month
        test subscription, then fast-forward its clock to instantly trigger the next billing cycle —
        seconds instead of waiting a month. If your webhook is configured, you'll see the renewal
        appear in the Funding Dashboard right after advancing.
      </p>

      {error && <p className="text-red-500 text-sm mb-4">{error}</p>}

      <div className="card p-5 mb-6">
        <h3 className="font-semibold mb-2 flex items-center gap-2">
          <PlayCircle size={16} /> 1. Create a Test Subscription
        </h3>
        <p className="text-xs text-neutral-500 mb-3">
          Creates a test customer with a test card attached, subscribed to a $1/month test price.
        </p>
        <button onClick={createTestSubscription} disabled={creating} className="btn-primary px-4 py-2 text-sm">
          {creating ? "Creating..." : "Create Test Subscription"}
        </button>
        {lastCreated && (
          <div className="mt-3 text-xs text-green-500 space-y-0.5">
            <p>✓ Created — Test Clock: {lastCreated.testClockId}</p>
            <p>Subscription: {lastCreated.subscriptionId}</p>
          </div>
        )}
      </div>

      <div className="card p-5">
        <h3 className="font-semibold mb-3 flex items-center gap-2">
          <Clock size={16} /> 2. Active Test Clocks — Fast-Forward Time
        </h3>
        {clocks.length === 0 ? (
          <p className="text-neutral-500 text-sm">No test clocks yet — create one above first.</p>
        ) : (
          <div className="space-y-3">
            {clocks.map((c) => (
              <div key={c.id} className="border border-neutral-800 rounded-lg p-3">
                <div className="flex items-center justify-between mb-2">
                  <div>
                    <p className="text-sm font-semibold">{c.name}</p>
                    <p className="text-xs text-neutral-500">
                      Status: <span className={c.status === "ready" ? "text-green-500" : "text-amber-500"}>{c.status}</span>
                      {" · "}Simulated time: {new Date(c.frozenTime * 1000).toLocaleString()}
                    </p>
                  </div>
                </div>
                <div className="flex gap-2 flex-wrap">
                  <button
                    onClick={() => advanceClock(c.id, 3600)}
                    disabled={advancing === c.id || c.status !== "ready"}
                    className="btn-secondary px-3 py-1.5 text-xs flex items-center gap-1"
                  >
                    <FastForward size={12} /> +1 Hour
                  </button>
                  <button
                    onClick={() => advanceClock(c.id, 86400)}
                    disabled={advancing === c.id || c.status !== "ready"}
                    className="btn-secondary px-3 py-1.5 text-xs flex items-center gap-1"
                  >
                    <FastForward size={12} /> +1 Day
                  </button>
                  <button
                    onClick={() => advanceClock(c.id, 32 * 86400)}
                    disabled={advancing === c.id || c.status !== "ready"}
                    className="btn-secondary px-3 py-1.5 text-xs flex items-center gap-1"
                  >
                    <FastForward size={12} /> +1 Month (trigger renewal)
                  </button>
                </div>
                {advancing === c.id && <p className="text-xs text-amber-500 mt-2">Advancing — Stripe is processing this in the background, refresh in a few seconds...</p>}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
