import { Power } from "lucide-react";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";

import { FormSaveButton } from "@/components/root/form-save-button";
import { MotionFade } from "@/components/motion-fade";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
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 { AppCard } from "@/components/ui/app-card";
import { Badge } from "@/components/ui/badge";
import { CardContent } from "@/components/ui/card";
import { Label } from "@/components/ui/label";

export const dynamic = "force-dynamic";

const copy = {
  title: "Wartungsmodus",
  subtitle: "Steuerung fuer den globalen Wartungsstatus.",
  overview: "Uebersicht",
  maintenance: "Wartungsmodus",
  uiKit: "UI Kit",
  media: "Media",
  siteSettings: "SEO",
  portfolio: "Portfolio",
  maintenanceText: "Wenn aktiv, werden alle Seiten auf die Coming Soon Seite weitergeleitet.",
  maintenanceOn: "Aktiv",
  maintenanceOff: "Inaktiv",
  selectLabel: "Status",
  selectHint: "Aenderung wird erst nach Speichern uebernommen.",
  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");
  }

  return (
    <RootDashboardShell
      copy={copy}
      active="maintenance"
      logoutAction={logoutAction}
      headerTitle={copy.title}
      headerDescription={copy.subtitle}
      headerActions={
        <>
          <Badge variant={maintenanceEnabled ? "warning" : "success"}>
            {maintenanceEnabled ? copy.maintenanceOn : copy.maintenanceOff}
          </Badge>
          <FormSaveButton formId="maintenance-form" />
        </>
      }
    >
      <MotionFade delay={0.1}>
        <AppCard>
          <CardContent className="space-y-4 p-6">
            <p className="text-sm text-muted-foreground">{copy.maintenanceText}</p>
            <form id="maintenance-form" action={updateMaintenanceMode} className="space-y-3">
              <div className="space-y-2">
                <Label htmlFor="enabled">{copy.selectLabel}</Label>
                <select
                  id="enabled"
                  name="enabled"
                  defaultValue={maintenanceEnabled ? "true" : "false"}
                  className="flex h-11 w-full rounded-pill border border-border bg-background px-4 text-sm text-foreground shadow-sm"
                >
                  <option value="false">{copy.maintenanceOff}</option>
                  <option value="true">{copy.maintenanceOn}</option>
                </select>
                <p className="text-xs text-muted-foreground">{copy.selectHint}</p>
              </div>
              <div className="inline-flex items-center gap-2 rounded-nested border border-border bg-surface-1 px-3 py-2 text-sm text-foreground">
                <Power className="h-4 w-4 text-brand-primary" />
                {maintenanceEnabled ? copy.maintenanceOn : copy.maintenanceOff}
              </div>
            </form>
          </CardContent>
        </AppCard>
      </MotionFade>
    </RootDashboardShell>
  );
}
