import { ArrowLeft, LogOut, Power } from "lucide-react";
import Link from "next/link";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";

import { AppHeader } from "@/components/layout/app-header";
import { AppShell } from "@/components/layout/app-shell";
import { AppSidebar } from "@/components/layout/app-sidebar";
import { ThemeToggle } from "@/components/theme-toggle";
import { routing } from "@/i18n/routing";
import { getLocalizedPath } from "@/lib/locale";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getMaintenanceMode, setMaintenanceMode } from "@/lib/app-config";
import { getRootNavigation } from "@/lib/root-navigation";
import { AppCard } from "@/components/ui/app-card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";

export const dynamic = "force-dynamic";

const copy = {
  title: "Wartungsmodus",
  subtitle: "Steuerung fuer den globalen Maintenance Status.",
  overview: "Uebersicht",
  maintenance: "Wartungsmodus",
  uiKit: "UI Kit",
  media: "Media",
  portfolio: "Portfolio",
  maintenanceText: "Wenn aktiv, werden alle Seiten auf die Coming Soon Seite weitergeleitet.",
  maintenanceOn: "Aktiv",
  maintenanceOff: "Inaktiv",
  enableMaintenance: "Wartungsmodus aktivieren",
  disableMaintenance: "Wartungsmodus deaktivieren",
  logout: "Ausloggen",
  backToSite: "Zur Website",
};

export default async function RootMaintenancePage() {
  const authenticated = isAdminAuthenticated();

  if (!authenticated) {
    redirect("/root");
  }

  const maintenanceEnabled = await getMaintenanceMode();

  async function logoutAction() {
    "use server";

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

  async function updateMaintenanceMode(formData: FormData) {
    "use server";

    if (!isAdminAuthenticated()) {
      redirect("/root");
    }

    const nextValue = formData.get("enabled") === "true";

    await setMaintenanceMode(nextValue);
    revalidatePath("/", "layout");
    revalidatePath("/coming-soon");
    revalidatePath("/root");
    revalidatePath("/root/maintenance");

    for (const appLocale of routing.locales) {
      revalidatePath(getLocalizedPath(appLocale), "layout");
      revalidatePath(getLocalizedPath(appLocale, "/coming-soon"));
    }

    redirect("/root/maintenance");
  }

  const sidebarItems = getRootNavigation(copy, "maintenance");

  return (
    <AppShell
      sidebar={
        <AppSidebar
          title={copy.title}
          description={copy.subtitle}
          items={sidebarItems}
          footer={
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <ThemeToggle ariaLabel="Theme wechseln" />
              </div>
              <Button asChild variant="outline" className="w-full justify-start">
                <Link href={getLocalizedPath("de")}>
                  <ArrowLeft className="h-4 w-4" />
                  {copy.backToSite}
                </Link>
              </Button>
              <form action={logoutAction}>
                <Button type="submit" variant="destructive" className="w-full justify-start">
                  <LogOut className="h-4 w-4" />
                  {copy.logout}
                </Button>
              </form>
            </div>
          }
        />
      }
      header={
        <AppHeader
          title={copy.title}
          description={copy.subtitle}
          actions={
            <Badge variant={maintenanceEnabled ? "warning" : "success"}>
              {maintenanceEnabled ? copy.maintenanceOn : copy.maintenanceOff}
            </Badge>
          }
        />
      }
    >
      <AppCard>
        <CardHeader>
          <CardTitle className="text-xl">{copy.title}</CardTitle>
          <CardDescription>{copy.maintenanceText}</CardDescription>
        </CardHeader>
        <CardContent>
          <form action={updateMaintenanceMode}>
            <input
              type="hidden"
              name="enabled"
              value={maintenanceEnabled ? "false" : "true"}
            />
            <Button type="submit">
              <Power className="h-4 w-4" />
              {maintenanceEnabled ? copy.disableMaintenance : copy.enableMaintenance}
            </Button>
          </form>
        </CardContent>
      </AppCard>
    </AppShell>
  );
}
