import { redirect } from "next/navigation";

import { MotionFade } from "@/components/motion-fade";
import { AdminDashboardShell } from "@/components/admin/admin-dashboard-shell";
import { SMTPSettingsForm } from "@/components/admin/smtp-settings-form";
import { Button } from "@/components/ui/button";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getAdminAppPath } from "@/lib/admin-routing";
import { getMailSettingsFormValues } from "@/lib/app-config";

import { saveMailSettingsAction, sendTestEmailAction } from "./actions";

export const dynamic = "force-dynamic";

const copy = {
  title: "SMTP",
  subtitle: "Mailserver, Absender und Testempfaenger verwalten.",
  overview: "Uebersicht",
  maintenance: "Wartungsmodus",
  uiKit: "UI Kit",
  media: "Media",
  siteSettings: "Settings",
  smtp: "SMTP",
  contactProtection: "Contact Protection",
  portfolio: "Portfolio",
  logout: "Ausloggen",
  backToSite: "Zur Website",
};

export default async function AdminSMTPPage() {
  if (!(await isAdminAuthenticated())) {
    redirect(getAdminAppPath("/"));
  }

  async function logoutAction() {
    "use server";

    await clearAdminSessionCookie();
    redirect(getAdminAppPath("/"));
  }

  const mailSettings = await getMailSettingsFormValues();

  return (
    <AdminDashboardShell
      copy={copy}
      active="smtp"
      smtpChild="settings"
      logoutAction={logoutAction}
      headerTitle={copy.title}
      headerDescription={copy.subtitle}
      headerActions={(
        <form action={sendTestEmailAction}>
          <Button type="submit" variant="outline">
            Send test email
          </Button>
        </form>
      )}
    >
      <div className="space-y-6">
        <MotionFade delay={0.16}>
          <SMTPSettingsForm
            action={saveMailSettingsAction}
            initialSettings={mailSettings}
          />
        </MotionFade>
      </div>
    </AdminDashboardShell>
  );
}
