import Link from "next/link";
import { redirect } from "next/navigation";
import { ArrowLeft } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { listSavedCards } from "@/lib/appwrite/saved-card-queries";
import { getPaymentByOrderId } from "@/lib/appwrite/subscription-queries";
import { PLAN_CATALOG } from "@/lib/appwrite/subscription-types";
import { requireTenant } from "@/lib/appwrite/tenant-guard";

import { MockPaymentForm } from "./components/mock-payment-form";

export default async function MockCheckoutPage({
  params,
}: {
  params: Promise<{ orderId: string }>;
}) {
  const { orderId } = await params;
  const ctx = await requireTenant();
  if (ctx.role !== "owner") redirect("/settings/billing");

  const payment = await getPaymentByOrderId(ctx.tenantId, orderId);
  if (!payment) redirect("/settings/billing");

  if (payment.status === "success") redirect("/settings/billing?upgraded=1");
  if (payment.status === "failed") redirect("/settings/billing?cancelled=1");

  const plan = PLAN_CATALOG[payment.plan];
  const savedCards = await listSavedCards(ctx.tenantId);

  return (
    <div className="flex-1 space-y-6 px-6 pt-0">
      <div className="flex flex-col gap-1">
        <Link
          href="/settings/billing"
          className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-sm"
        >
          <ArrowLeft className="size-3.5" />
          Plan & Faturalandırma
        </Link>
        <div className="flex items-center gap-3">
          <h1 className="text-2xl font-bold tracking-tight">Ödemeyi tamamla</h1>
          <Badge
            variant="outline"
            className="border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-400"
          >
            Mock Test
          </Badge>
        </div>
        <p className="text-muted-foreground text-sm">
          Sipariş No: <span className="font-mono">{payment.orderId}</span> · Aşağıdaki kart
          formunu doldur — alanlar gerçek zamanlı olarak karta yansır.
        </p>
      </div>

      <Card>
        <CardContent className="py-6">
          <MockPaymentForm
            orderId={payment.orderId}
            amount={payment.amount}
            planName={plan.name}
            planPeriod="30 gün"
            savedCards={savedCards}
          />
        </CardContent>
      </Card>
    </div>
  );
}
