import { redirect } from "next/navigation";
import Link from "next/link";
import { getCurrentUser, createAdminClient } from "@/lib/appwrite/server";
import { getActiveTenantId } from "@/lib/appwrite/tenant";
import { DATABASE_ID, TABLES, type TenantSettings } from "@/lib/appwrite/schema";
import { PLAN_LIMITS } from "@/lib/plans";
import { Query } from "node-appwrite";
import { SignOutForm } from "./sign-out-form";

export default async function PlanLimitPage() {
  const user = await getCurrentUser();
  if (!user) redirect("/sign-in");

  const tenantId = await getActiveTenantId();
  if (!tenantId) redirect("/onboarding");

  const { tablesDB, teams } = createAdminClient();

  const [settingsResult, membershipsResult] = await Promise.all([
    tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.tenantSettings,
      queries: [Query.equal("tenantId", tenantId), Query.limit(1)],
    }),
    teams.listMemberships(tenantId),
  ]);

  const settings = settingsResult.rows[0] as unknown as TenantSettings | undefined;
  const plan = settings?.plan ?? "free";
  const memberLimit = PLAN_LIMITS[plan].teamMembers;

  // If user is owner or plan allows them, redirect back to dashboard
  const myMembership = membershipsResult.memberships.find((m) => m.userId === user.$id);
  const isOwner = myMembership?.roles?.includes("owner");
  const confirmedCount = membershipsResult.memberships.filter((m) => m.confirm).length;

  if (isOwner || memberLimit === Infinity || confirmedCount <= memberLimit) {
    redirect("/dashboard");
  }

  // Find the owner to show their contact
  const ownerMembership = membershipsResult.memberships.find((m) => m.roles?.includes("owner"));

  return (
    <div className="min-h-dvh flex items-center justify-center bg-muted/30 p-4">
      <div className="w-full max-w-md rounded-2xl border bg-card shadow-sm overflow-hidden">
        {/* Header */}
        <div className="bg-gradient-to-br from-slate-800 to-slate-900 px-8 py-8 text-center">
          <div className="mx-auto mb-4 flex size-16 items-center justify-center rounded-full bg-white/10">
            <svg className="size-8 text-amber-400" fill="currentColor" viewBox="0 0 24 24">
              <path d="M12 2a10 10 0 1 0 0 20A10 10 0 0 0 12 2zm0 15a1 1 0 1 1 0-2 1 1 0 0 1 0 2zm1-4a1 1 0 0 1-2 0V7a1 1 0 0 1 2 0v6z" />
            </svg>
          </div>
          <h1 className="text-xl font-bold text-white">Erişim Kısıtlandı</h1>
          <p className="mt-1 text-sm text-slate-400">
            {settings?.officeName ?? "Bu çalışma alanı"} ücretsiz plana geçti
          </p>
        </div>

        {/* Body */}
        <div className="px-8 py-6 space-y-4">
          <p className="text-sm text-muted-foreground leading-relaxed">
            Ücretsiz planda yalnızca <strong>1 kullanıcı</strong> sisteme erişebilir.
            Bu çalışma alanındaki erişiminiz geçici olarak askıya alınmıştır.
          </p>

          <div className="rounded-lg border bg-amber-50 dark:bg-amber-950/30 border-amber-200 dark:border-amber-800 px-4 py-3 text-sm text-amber-800 dark:text-amber-300">
            Yöneticinizden çalışma alanını Pro plana yükseltmesini isteyin ya da
            hesabınızı çalışma alanından çıkarmasını talep edin.
          </div>

          {ownerMembership?.userEmail && (
            <div className="rounded-lg border px-4 py-3 text-sm">
              <p className="text-muted-foreground text-xs mb-1">Çalışma alanı yöneticisi</p>
              <p className="font-medium">{ownerMembership.userName ?? ownerMembership.userEmail}</p>
              <a
                href={`mailto:${ownerMembership.userEmail}`}
                className="text-xs text-primary hover:underline"
              >
                {ownerMembership.userEmail}
              </a>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="border-t px-8 py-4 flex items-center justify-between gap-3 bg-muted/20">
          <SignOutForm />
          <Link
            href="https://kovakcrm.com/fiyatlar"
            className="text-xs text-muted-foreground hover:text-foreground underline-offset-2 hover:underline"
          >
            Plan karşılaştır
          </Link>
        </div>
      </div>
    </div>
  );
}
