import { redirect } from "next/navigation";

import { MotionFade } from "@/components/motion-fade";
import { FlashMessage } from "@/components/root/flash-message";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { SMTPSettingsForm } from "@/components/root/smtp-settings-form";
import { Button } from "@/components/ui/button";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
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: "SEO",
  smtp: "SMTP",
  contactProtection: "Contact Protection",
  portfolio: "Portfolio",
  logout: "Ausloggen",
  backToSite: "Zur Website",
};

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

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

  async function logoutAction() {
    "use server";

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

  const mailSettings = await getMailSettingsFormValues();

  return (
    <RootDashboardShell
      copy={copy}
      active="smtp"
      smtpChild="settings"
      logoutAction={logoutAction}
      headerTitle={copy.title}
      headerDescription={copy.subtitle}
      saveFormId="smtp-settings-form"
      reloadDocumentOnSave
      headerActions={(
        <form action={sendTestEmailAction}>
          <Button type="submit" variant="outline">
            Send test email
          </Button>
        </form>
      )}
    >
      <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}

        <MotionFade delay={0.16}>
          <SMTPSettingsForm
            action={saveMailSettingsAction}
            initialSettings={mailSettings}
          />
        </MotionFade>
      </div>
    </RootDashboardShell>
  );
}
