import { getTranslations, setRequestLocale } from "next-intl/server";
import { redirect } from "next/navigation";
import { connectDB } from "@/lib/db";
import { Client } from "@/models/Client";
import { Department } from "@/models/Department";
import { Position } from "@/models/Position";
import { getSessionClientId } from "@/lib/auth";
import { AccountPageHeader } from "@/components/account/AccountPageHeader";
import { ProfileForm } from "@/components/account/ProfileForm";
import { TwoFactorSetupPanel } from "@/components/account/TwoFactorSetupPanel";
import { AccountDeletionPanel } from "@/components/account/AccountDeletionPanel";
import { EmailNotificationToggle } from "@/components/account/EmailNotificationToggle";

export const dynamic = "force-dynamic";

export default async function ProfilePage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params;
  setRequestLocale(locale);
  const t = await getTranslations({ locale, namespace: "auth" });

  const clientId = await getSessionClientId();
  if (!clientId) redirect(`/${locale}/login`);

  await connectDB();
  const client = await Client.findById(clientId).lean();
  if (!client) redirect(`/${locale}/login`);

  const [department, position] = await Promise.all([
    client.departmentId ? Department.findById(client.departmentId).lean() : null,
    client.positionId ? Position.findById(client.positionId).lean() : null,
  ]);

  return (
    <div>
      <div className="max-w-lg">
        <AccountPageHeader eyebrow={t("profileEyebrow")} title={t("profileTitle")} />
        <div>
          <ProfileForm
            locale={locale}
            client={{
              id: String(client._id),
              firstName: client.firstName || "",
              lastName: client.lastName || "",
              salutation: client.salutation || "",
              pronouns: client.pronouns || "",
              nickname: client.nickname || "",
              avatarPath: client.avatarPath || "",
              birthDate: client.birthDate ? new Date(client.birthDate).toISOString().slice(0, 10) : "",
              phone: client.phone || "",
              billingStreet: client.billingStreet || "",
              billingPostCode: client.billingPostCode || "",
              billingCity: client.billingCity || "",
              billingCountryCode: client.billingCountryCode || "DE",
              departmentName: department?.name || "",
              positionName: position?.name || "",
              role: client.role,
            }}
          />
        </div>

        <div className="mt-8">
          <EmailNotificationToggle
            initialEnabled={client.emailNotificationsEnabled ?? true}
            labels={{
              title: locale === "en" ? "Email notifications" : "E-Mail-Benachrichtigungen",
              text:
                locale === "en"
                  ? "Applies to optional reminders (re-engagement, pre-shoot reminder, weather heads-up, loyalty/review rewards) — important emails (order confirmations, invoices, payment reminders) always go out regardless. In-app notifications (bell icon) are unaffected either way."
                  : "Betrifft optionale Erinnerungen (Wiedervorlage, Vor-Shooting-Erinnerung, Wetter-Hinweis, Stammkunden-/Bewertungs-Prämie) — wichtige E-Mails (Auftragsbestätigung, Rechnungen, Zahlungserinnerungen) gehen unabhängig davon immer raus. In-App-Benachrichtigungen (Glocke) sind davon ebenfalls nicht betroffen.",
              label: locale === "en" ? "Receive optional reminder emails" : "Optionale Erinnerungs-E-Mails erhalten",
            }}
          />
        </div>

        <div className="mt-8">
          <p className="mb-4 text-xs uppercase tracking-[0.3em] text-[var(--rk-ink-muted)]">
            {t("twoFactorTitle")}
          </p>
          <TwoFactorSetupPanel enabled={client.totpEnabled} />
        </div>

        {client.role === "client" && (
          <div className="mt-8">
            <AccountDeletionPanel locale={locale} deletionRequested={Boolean(client.deletionRequestedAt)} />
          </div>
        )}
      </div>
    </div>
  );
}
