import { redirect } from "next/navigation";

import { FlashMessage } from "@/components/root/flash-message";
import { MediaLibraryManager } from "@/components/root/media-library-manager";
import { MotionFade } from "@/components/motion-fade";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getAdminMediaAssets } from "@/lib/media";

export const dynamic = "force-dynamic";

const copy = {
  title: "Media Library",
  subtitle: "Zentrale Dateien fuer Portfolio und spaetere Inhaltsbereiche.",
  overview: "Uebersicht",
  maintenance: "Wartungsmodus",
  uiKit: "UI Kit",
  media: "Media",
  siteSettings: "Settings",
  portfolio: "Portfolio",
  logout: "Ausloggen",
  backToSite: "Zur Website",
};

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

export default async function RootMediaPage({ searchParams }: RootMediaPageProps) {
  if (!isAdminAuthenticated()) {
    redirect("/root");
  }

  async function logoutAction() {
    "use server";

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

  const mediaAssets = await getAdminMediaAssets();

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

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

        <MediaLibraryManager mediaAssets={mediaAssets} />
      </div>
    </RootDashboardShell>
  );
}
