import { MediaKind } from "@/lib/db/enums";
import { redirect } from "next/navigation";

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

import { saveSiteBrandSettingsAction } from "../actions";

export const dynamic = "force-dynamic";

const copy = {
  title: "Brand",
  subtitle: "Primaerfarbe, Logos, Favicon und OG Assets verwalten.",
  overview: "Uebersicht",
  maintenance: "Wartungsmodus",
  uiKit: "UI Kit",
  media: "Media",
  siteSettings: "Settings",
  brandSettings: "Brand",
  localizationSettings: "Localization",
  smtp: "SMTP",
  portfolio: "Portfolio",
  logout: "Ausloggen",
  backToSite: "Zur Website",
};

export default async function AdminSiteBrandSettingsPage({
  searchParams,
}: {
  searchParams?: Promise<{ success?: string; error?: string }>;
}) {
  const flash = readFlash(await searchParams);

  if (!(await isAdminAuthenticated())) {
    redirect(getAdminAppPath("/"));
  }

  async function logoutAction() {
    "use server";

    await clearAdminSessionCookie();
    redirect(getAdminAppPath("/"));
  }

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

  return (
    <AdminDashboardShell
      copy={copy}
      active="site-settings"
      flash={flash}
      siteSettingsChild="brand"
      logoutAction={logoutAction}
      headerTitle={copy.title}
      headerDescription={copy.subtitle}
    >
      <MotionFade delay={0.16}>
        <SiteSettingsForm
          mode="brand"
          action={saveSiteBrandSettingsAction}
          initialSettings={siteSettings}
          initialBindings={mediaBindings}
          mediaOptions={mediaOptions}
        />
      </MotionFade>
    </AdminDashboardShell>
  );
}
