import Link from "next/link"
import { redirect } from "next/navigation"
import { eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { profiles } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { PLAN_LIMITS } from "@/lib/stripe/plans"
import { BrandingForm } from "@/components/forms/branding-form"
import { Sparkles, ArrowRight } from "lucide-react"
import type { Plan } from "@/types"

export const metadata = { title: "White-Label Branding" }

export default async function BrandingSettingsPage() {
  const user = await getSessionUser()
  if (!user) redirect("/login")

  const profile = await db.query.profiles.findFirst({
    where: eq(profiles.id, user.id),
    columns: {
      plan: true,
      brand_name: true,
      brand_logo_url: true,
      brand_color: true,
      hide_powered_by: true,
    },
  })

  const plan = (profile?.plan ?? "starter") as Plan
  const hasWhiteLabel = PLAN_LIMITS[plan]?.hasWhiteLabel === true

  return (
    <div className="max-w-4xl space-y-6">
      <div>
        <h2 className="text-lg font-semibold text-white">White-Label Branding</h2>
        <p className="text-sm text-white/40">
          Customize how the tenant portal looks with your own brand.
        </p>
      </div>

      {hasWhiteLabel ? (
        <BrandingForm
          brandName={profile?.brand_name ?? null}
          brandLogoUrl={profile?.brand_logo_url ?? null}
          brandColor={profile?.brand_color ?? null}
          hidePoweredBy={profile?.hide_powered_by ?? false}
        />
      ) : (
        <div className="rounded-xl border border-indigo-500/20 bg-indigo-600/5 p-8 text-center">
          <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl bg-indigo-600">
            <Sparkles className="h-6 w-6 text-white" />
          </div>
          <h3 className="text-base font-semibold text-white">White-label is a Landlord feature</h3>
          <p className="mx-auto mt-2 max-w-md text-sm text-white/50">
            Put your own brand name, logo, and accent color on the tenant portal — and remove the
            “Powered by” line. Available on the Landlord and Lifetime plans.
          </p>
          <Link
            href="/settings/billing"
            className="mt-6 inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-indigo-500"
          >
            Upgrade to unlock
            <ArrowRight className="h-4 w-4" />
          </Link>
        </div>
      )}
    </div>
  )
}
