import { ShellPage } from "@/components/page-templates";
import { Button, SectionCard } from "@/components/ui";

import { prisma } from "@/lib/prisma";
import { getSession } from "@/lib/auth";
import { updateTenantProfile } from "@/lib/admin-crud";
import { redirect } from "next/navigation";

export default async function TenantProfileSettingsPage({
  searchParams
}: {
  searchParams?: Promise<{ error?: string; success?: string }>;
}) {
  const session = await getSession();
  if (!session) {
    redirect("/login");
  }

  const tenant = await prisma.tenant.findUnique({
    where: { id: session.tenantId },
    select: {
      name: true,
      slug: true,
      timezone: true,
      plan: { select: { name: true } }
    }
  });

  if (!tenant) {
    redirect("/unauthorized");
  }

  const params = await (searchParams ?? Promise.resolve({ error: undefined, success: undefined }));
  const infoMessage =
    params.success === "updated"
      ? "Pengaturan tenant berhasil disimpan."
      : params.error === "missing_fields"
        ? "Nama perusahaan, timezone, dan slug wajib diisi."
        : params.error === "tenant_slug_taken"
          ? "Slug tenant sudah dipakai, pilih slug lain."
          : null;

  return (
    <ShellPage shell="admin" title="Tenant Profile Settings" description="Identitas tenant dan informasi workspace.">
      <SectionCard title="Tenant profile">
        <form action={updateTenantProfile} className="grid gap-4 md:max-w-2xl">
          {infoMessage ? (
            <p className="rounded-xl border border-success/30 bg-success/10 p-3 text-sm text-success">{infoMessage}</p>
          ) : null}
          <input
            className="rounded-xl border border-line px-4 py-3"
            defaultValue={tenant.name}
            name="companyName"
            placeholder="Company name"
            required
          />
          <input
            className="rounded-xl border border-line px-4 py-3"
            defaultValue={tenant.timezone}
            name="timezone"
            placeholder="Timezone"
            required
          />
          <input
            className="rounded-xl border border-line px-4 py-3"
            defaultValue={tenant.slug}
            name="slug"
            placeholder="Tenant slug"
            required
          />
          <input
            className="rounded-xl border border-line px-4 py-3"
            defaultValue={tenant.plan.name}
            name="plan"
            placeholder="Plan"
            readOnly
          />
          <div>
            <Button type="submit">Save settings</Button>
          </div>
        </form>
      </SectionCard>
    </ShellPage>
  );
}
