export const dynamic = "force-dynamic";

import type { Metadata } from "next";
import { redirect } from "next/navigation";
import Link from "next/link";
import { CheckCircle, Receipt } from '@/lib/icons';

import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { getEffectivePlan, getPlanUsage } from "@/lib/appwrite/plan-limits";
import { isPayTREnabled } from "@/lib/payments/paytr";
import { CurrentPlanCard } from "./components/current-plan-card";
import { UpgradeSection } from "./components/upgrade-section";

export const metadata: Metadata = {
  title: "KovakEmlak — Plan & Faturalama",
};

export default async function BillingPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string>>;
}) {
  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    redirect("/onboarding");
  }

  if (ctx.role !== "owner") redirect("/dashboard");

  const params = await searchParams;
  const upgraded = params.upgraded === "1";

  const plan = getEffectivePlan(ctx);
  const { usage } = await getPlanUsage(ctx);
  const paytrEnabled = isPayTREnabled();

  const officeName = ctx.settings?.officeName ?? "Ofis";

  return (
    <div className="flex-1 space-y-6 px-6 pt-4">
      <div className="flex items-start justify-between gap-4">
        <div className="flex flex-col gap-1">
          <p className="text-muted-foreground text-sm">{officeName}</p>
          <h1 className="text-2xl font-bold tracking-tight">Plan & Faturalama</h1>
          <p className="text-muted-foreground text-sm">
            Mevcut planınızı görüntüleyin ve yönetin.
          </p>
        </div>
        <Link
          href="/settings/billing/invoices"
          className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0 mt-1"
        >
          <Receipt className="h-4 w-4" />
          Faturalar
        </Link>
      </div>

      {upgraded && (
        <div className="flex items-center gap-2 rounded-md border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-700 dark:text-green-400">
          <CheckCircle className="h-4 w-4 shrink-0" />
          Tebrikler! Planınız başarıyla yükseltildi.
        </div>
      )}

      <CurrentPlanCard
        plan={plan}
        period={ctx.settings?.planPeriod ?? null}
        expiresAt={ctx.settings?.planExpiresAt ?? null}
        usage={usage}
      />

      <UpgradeSection
        currentPlan={plan}
        currentPeriod={ctx.settings?.planPeriod ?? null}
        planExpiresAt={ctx.settings?.planExpiresAt ?? null}
        paytrEnabled={paytrEnabled}
      />
    </div>
  );
}
