"use client";
import { useEffect, useState } from "react";

type Plan = { id: string; tier: string; name: string; price: number; interval: string; features: string; stripePriceId: string | null; active: boolean };

export default function AdminPlansPage() {
  const [plans, setPlans] = useState<Plan[]>([]);
  const [saving, setSaving] = useState<string | null>(null);

  async function load() {
    const res = await fetch("/api/plans-list");
    setPlans(await res.json());
  }
  useEffect(() => { load(); }, []);

  function update(id: string, key: string, value: any) {
    setPlans((ps) => ps.map((p) => (p.id === id ? { ...p, [key]: value } : p)));
  }

  async function save(plan: Plan) {
    setSaving(plan.id);
    await fetch(`/api/admin/plans/${plan.id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        name: plan.name,
        price: plan.price,
        features: JSON.parse(plan.features),
        stripePriceId: plan.stripePriceId,
        active: plan.active,
      }),
    });
    setSaving(null);
  }

  return (
    <div>
      <h2 className="text-lg font-semibold mb-4">Membership Plans</h2>
      <div className="space-y-4">
        {plans.map((p) => {
          const features: string[] = JSON.parse(p.features || "[]");
          return (
            <div key={p.id} className="card p-4">
              <div className="flex gap-4 mb-3">
                <div className="flex-1">
                  <label className="block text-xs text-neutral-500 mb-1">Name ({p.tier})</label>
                  <input value={p.name} onChange={(e) => update(p.id, "name", e.target.value)}
                    className="w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-1.5 text-sm outline-none focus:border-red-600" />
                </div>
                <div className="w-32">
                  <label className="block text-xs text-neutral-500 mb-1">Price ($/mo)</label>
                  <input type="number" step="0.01" value={p.price} onChange={(e) => update(p.id, "price", parseFloat(e.target.value))}
                    className="w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-1.5 text-sm outline-none focus:border-red-600" />
                </div>
              </div>
              <label className="block text-xs text-neutral-500 mb-1">Features (one per line)</label>
              <textarea
                value={features.join("\n")}
                onChange={(e) => update(p.id, "features", JSON.stringify(e.target.value.split("\n").filter(Boolean)))}
                rows={3}
                className="w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-1.5 text-sm outline-none focus:border-red-600 mb-3"
              />
              <label className="block text-xs text-neutral-500 mb-1">Stripe Price ID (optional, for recurring billing)</label>
              <input value={p.stripePriceId || ""} onChange={(e) => update(p.id, "stripePriceId", e.target.value)}
                placeholder="price_xxxxx"
                className="w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-1.5 text-sm outline-none focus:border-red-600 mb-3" />
              <button onClick={() => save(p)} disabled={saving === p.id} className="btn-primary px-4 py-2 text-sm">
                {saving === p.id ? "Saving..." : "Save"}
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}
