import { auth } from '@clerk/nextjs/server';
import { getOrCreateStripeCustomerId, listPlans } from '@/lib/stripe';
import { redirect } from 'next/navigation';

export default async function BillingPage() {
  const { userId } = await auth();
  if (!userId) redirect('/sign-in');

  const customerId = await getOrCreateStripeCustomerId(userId);
  const plans = listPlans();

  return (
    <div>
      <h1 className="text-2xl font-bold">Billing</h1>
      <p className="mt-2 text-sm text-neutral-600">
        Customer id: <code className="rounded bg-neutral-100 px-1.5 py-0.5">{customerId}</code>
      </p>

      <h2 className="mt-8 text-lg font-semibold">Plans</h2>
      <div className="mt-4 grid gap-4 sm:grid-cols-3">
        {plans.map((plan) => (
          <div key={plan.id} className="rounded-lg border border-neutral-200 p-6">
            <h3 className="text-lg font-semibold">{plan.name}</h3>
            <p className="mt-1 text-3xl font-bold">${plan.priceMonthly}/mo</p>
            <ul className="mt-4 space-y-1 text-sm text-neutral-600">
              {plan.features.map((f) => <li key={f}>• {f}</li>)}
            </ul>
            <form action={`/api/billing/checkout?plan=${plan.id}`} method="POST" className="mt-4">
              <button className="w-full rounded-md bg-neutral-900 px-4 py-2 text-sm text-white hover:bg-neutral-800">
                Subscribe
              </button>
            </form>
          </div>
        ))}
      </div>
    </div>
  );
}
