import { MediaKind } from "@prisma/client";
import { redirect } from "next/navigation";

import { MotionFade } from "@/components/motion-fade";
import { SiteSettingsForm } from "@/components/root/site-settings-form";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import {
  getSiteSettings,
  getSiteSettingsMediaBindings,
} from "@/lib/app-config";
import { getMediaOptions } from "@/lib/media";

import { saveSiteSettingsAction } from "./actions";

export const dynamic = "force-dynamic";

const copy = {
  title: "Settings",
  subtitle: "Globale Titel, Copy und Brand Assets verwalten.",
  overview: "Uebersicht",
  maintenance: "Wartungsmodus",
  uiKit: "UI Kit",
  media: "Media",
  siteSettings: "Settings",
  smtp: "SMTP",
  portfolio: "Portfolio",
  logout: "Ausloggen",
  backToSite: "Zur Website",
};

export default async function RootSiteSettingsPage() {
  if (!isAdminAuthenticated()) {
    redirect("/root");
  }

  async function logoutAction() {
    "use server";

    clearAdminSessionCookie();
    redirect("/root");
  }

  const [siteSettings, mediaBindings, mediaOptions] = await Promise.all([
    getSiteSettings(),
    getSiteSettingsMediaBindings(),
    getMediaOptions({ kind: MediaKind.IMAGE }),
  ]);

  return (
    <RootDashboardShell
      copy={copy}
      active="site-settings"
      logoutAction={logoutAction}
      headerTitle={copy.title}
      headerDescription={copy.subtitle}
      saveFormId="site-settings-form"
    >
      <div className="space-y-6">
        <MotionFade delay={0.16}>
          <SiteSettingsForm
            action={saveSiteSettingsAction}
            initialSettings={siteSettings}
            initialBindings={mediaBindings}
            mediaOptions={mediaOptions}
          />
        </MotionFade>
      </div>
    </RootDashboardShell>
  );
}
