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

import { MotionFade } from "@/components/motion-fade";
import { FormSaveButton } from "@/components/root/form-save-button";
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: "SEO",
  subtitle: "Globale SEO Einstellungen, Titelstruktur und Standardbilder verwalten.",
  overview: "Uebersicht",
  maintenance: "Wartungsmodus",
  uiKit: "UI Kit",
  media: "Media",
  siteSettings: "SEO",
  portfolio: "Portfolio",
  logout: "Ausloggen",
  backToSite: "Zur Website",
};

type RootSiteSettingsPageProps = {
  searchParams?: {
    success?: string;
    error?: string;
  };
};

export default async function RootSiteSettingsPage({
  searchParams,
}: RootSiteSettingsPageProps) {
  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}
      headerActions={<FormSaveButton formId="site-settings-form" />}
    >
      <div className="space-y-6">
        {searchParams?.success ? (
          <MotionFade delay={0.1}>
            <p className="rounded-nested border border-status-success/30 bg-status-success/10 px-4 py-3 text-sm text-status-success">
              {searchParams.success}
            </p>
          </MotionFade>
        ) : null}

        {searchParams?.error ? (
          <MotionFade delay={0.12}>
            <p className="rounded-nested border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
              {searchParams.error}
            </p>
          </MotionFade>
        ) : null}

        <MotionFade delay={0.16}>
          <SiteSettingsForm
            action={saveSiteSettingsAction}
            initialSettings={siteSettings}
            initialBindings={mediaBindings}
            mediaOptions={mediaOptions}
          />
        </MotionFade>
      </div>
    </RootDashboardShell>
  );
}
