import type { Metadata } from "next";
import { redirect } from "next/navigation";

import { getLogoUrl } from "@/lib/appwrite/storage";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { LogoUploader } from "./components/logo-uploader";
import { WorkspaceSettingsForm } from "./components/workspace-form";

export const metadata: Metadata = {
  title: "DLS — Şirket bilgileri",
};

export default async function WorkspaceSettingsPage() {
  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    redirect("/onboarding");
  }

  const canEdit = ctx.role === "owner" || ctx.role === "admin";

  return (
    <div className="flex-1 space-y-6 px-6 pt-0">
      <div className="flex flex-col gap-1">
        <p className="text-muted-foreground text-sm">{ctx.settings?.companyName ?? "Çalışma alanı"}</p>
        <h1 className="text-2xl font-bold tracking-tight">Şirket bilgileri</h1>
        <p className="text-muted-foreground text-sm">
          Faturalarda ve panel başlığında görünecek şirket bilgileri.
          {!canEdit && " Düzenlemek için yönetici yetkisine ihtiyacınız var."}
        </p>
      </div>

      <LogoUploader
        canEdit={canEdit}
        currentLogoUrl={getLogoUrl(ctx.settings?.logo)}
        companyName={ctx.settings?.companyName ?? "Çalışma alanı"}
      />

      <WorkspaceSettingsForm
        canEdit={canEdit}
        defaults={{
          companyName: ctx.settings?.companyName ?? "",
          companyTaxId: ctx.settings?.companyTaxId ?? "",
          companyAddress: ctx.settings?.companyAddress ?? "",
          companyEmail: ctx.settings?.companyEmail ?? "",
          companyPhone: ctx.settings?.companyPhone ?? "",
          defaultCurrency: ctx.settings?.defaultCurrency ?? "TRY",
          kind: ctx.settings?.kind ?? null,
          memberNumber: ctx.settings?.memberNumber ?? "",
        }}
      />
    </div>
  );
}
