import { redirect } from "next/navigation";

import { FlashMessage } from "@/components/root/flash-message";
import { MarqueeSettingsForm } from "@/components/root/marquee-settings-form";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { MotionFade } from "@/components/motion-fade";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getMarqueeSettings } from "@/lib/app-config";

import { saveMarqueeSettingsAction } from "./actions";

export const dynamic = "force-dynamic";

const copy = {
  title: "Marquee",
  subtitle: "Scrollende Textzeilen fuer die Startseite pro Sprache verwalten.",
  overview: "Uebersicht",
  maintenance: "Wartungsmodus",
  uiKit: "UI Kit",
  media: "Media",
  siteSettings: "SEO",
  marquee: "Marquee",
  smtp: "SMTP",
  portfolio: "Portfolio",
  logout: "Ausloggen",
  backToSite: "Zur Website",
};

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

export default async function RootMarqueePage({
  searchParams,
}: RootMarqueePageProps) {
  if (!isAdminAuthenticated()) {
    redirect("/root");
  }

  async function logoutAction() {
    "use server";

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

  const marqueeSettings = await getMarqueeSettings();

  return (
    <RootDashboardShell
      copy={copy}
      active="marquee"
      logoutAction={logoutAction}
      headerTitle={copy.title}
      headerDescription={copy.subtitle}
      saveFormId="marquee-settings-form"
      reloadDocumentOnSave
    >
      <div className="space-y-6">
        {searchParams?.success ? (
          <MotionFade delay={0.08}>
            <FlashMessage type="success" message={searchParams.success} />
          </MotionFade>
        ) : null}

        {searchParams?.error ? (
          <MotionFade delay={0.1}>
            <FlashMessage type="error" message={searchParams.error} />
          </MotionFade>
        ) : null}

        <MotionFade delay={0.14}>
          <MarqueeSettingsForm
            action={saveMarqueeSettingsAction}
            initialSettings={marqueeSettings}
          />
        </MotionFade>
      </div>
    </RootDashboardShell>
  );
}
