"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 };

const INTERVALS = ["day", "week", "month", "year"];

export default function AdminPlansPage() {
  const [plans, setPlans] = useState<Plan[]>([]);
  const [saving, setSaving] = useState<string | null>(null);
  const [showCreate, setShowCreate] = useState(false);
  const [newPlan, setNewPlan] = useState({ tier: "", name: "", price: "1.00", interval: "day", features: "Test feature" });
  const [creating, setCreating] = useState(false);
  const [error, setError] = useState("");

  async function load() {
    const res = await fetch("/api/admin/plans");
    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,
        interval: plan.interval,
        features: JSON.parse(plan.features),
        stripePriceId: plan.stripePriceId,
        active: plan.active,
      }),
    });
    setSaving(null);
    load();
  }

  async function createPlan() {
    setError("");
    setCreating(true);
    const res = await fetch("/api/admin/plans", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        tier: newPlan.tier,
        name: newPlan.name,
        price: parseFloat(newPlan.price),
        interval: newPlan.interval,
        features: newPlan.features.split("\n").filter(Boolean),
        active: true,
      }),
    });
    const data = await res.json();
    setCreating(false);
    if (!res.ok) {
      setError(data.error);
      return;
    }
    setShowCreate(false);
    setNewPlan({ tier: "", name: "", price: "1.00", interval: "day", features: "Test feature" });
    load();
  }

  async function deletePlan(id: string, name: string) {
    if (!confirm(`Permanently delete "${name}"? This can't be undone.`)) return;
    await fetch(`/api/admin/plans/${id}`, { method: "DELETE" });
    load();
  }

  const inputCls = "w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-1.5 text-sm outline-none focus:border-red-600";

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-semibold">Membership Plans</h2>
        <button onClick={() => setShowCreate((s) => !s)} className="btn-primary px-4 py-2 text-sm">
          {showCreate ? "Cancel" : "+ Create Test Plan"}
        </button>
      </div>

      {showCreate && (
        <div className="card p-4 mb-4 border-amber-800/50 bg-amber-950/10">
          <h3 className="font-semibold text-sm mb-3 text-amber-400">New Plan (e.g. a cheap daily-recurring test plan)</h3>
          <div className="grid sm:grid-cols-2 gap-3 mb-3">
            <div>
              <label className="block text-xs text-neutral-500 mb-1">Tier ID (unique, e.g. "test_daily")</label>
              <input value={newPlan.tier} onChange={(e) => setNewPlan((p) => ({ ...p, tier: e.target.value }))} className={inputCls} />
            </div>
            <div>
              <label className="block text-xs text-neutral-500 mb-1">Display Name</label>
              <input value={newPlan.name} onChange={(e) => setNewPlan((p) => ({ ...p, name: e.target.value }))} className={inputCls} />
            </div>
            <div>
              <label className="block text-xs text-neutral-500 mb-1">Price ($)</label>
              <input type="number" step="0.01" value={newPlan.price} onChange={(e) => setNewPlan((p) => ({ ...p, price: e.target.value }))} className={inputCls} />
            </div>
            <div>
              <label className="block text-xs text-neutral-500 mb-1">Recurring interval</label>
              <select value={newPlan.interval} onChange={(e) => setNewPlan((p) => ({ ...p, interval: e.target.value }))} className={inputCls}>
                {INTERVALS.map((i) => <option key={i} value={i}>Every {i}</option>)}
              </select>
              <p className="text-[10px] text-neutral-600 mt-1">Use "day" to test recurring renewal quickly, without waiting a month.</p>
            </div>
          </div>
          {error && <p className="text-red-500 text-xs mb-2">{error}</p>}
          <button onClick={createPlan} disabled={creating} className="btn-primary px-4 py-2 text-sm">
            {creating ? "Creating..." : "Create Plan"}
          </button>
        </div>
      )}

      <div className="space-y-4">
        {plans.map((p) => {
          const features: string[] = JSON.parse(p.features || "[]");
          return (
            <div key={p.id} className={`card p-4 ${!p.active ? "opacity-50" : ""}`}>
              <div className="flex items-center justify-between mb-3">
                <span className="text-xs text-neutral-500">Tier: <code>{p.tier}</code></span>
                <div className="flex items-center gap-3">
                  <label className="flex items-center gap-1.5 text-xs">
                    <input type="checkbox" checked={p.active} onChange={(e) => update(p.id, "active", e.target.checked)} />
                    {p.active ? "Visible on site" : "Hidden (offline)"}
                  </label>
                  <button onClick={() => deletePlan(p.id, p.name)} className="text-xs text-red-500 hover:text-red-400">
                    Delete Permanently
                  </button>
                </div>
              </div>
              <div className="flex gap-4 mb-3">
                <div className="flex-1">
                  <label className="block text-xs text-neutral-500 mb-1">Name</label>
                  <input value={p.name} onChange={(e) => update(p.id, "name", e.target.value)} className={inputCls} />
                </div>
                <div className="w-28">
                  <label className="block text-xs text-neutral-500 mb-1">Price ($)</label>
                  <input type="number" step="0.01" value={p.price} onChange={(e) => update(p.id, "price", parseFloat(e.target.value))} className={inputCls} />
                </div>
                <div className="w-32">
                  <label className="block text-xs text-neutral-500 mb-1">Interval</label>
                  <select value={p.interval} onChange={(e) => update(p.id, "interval", e.target.value)} className={inputCls}>
                    {INTERVALS.map((i) => <option key={i} value={i}>Every {i}</option>)}
                  </select>
                </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={`${inputCls} 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>
  );
}
