import { CalendarDays, Globe2, LockKeyhole, UserRound } from "lucide-react";
import type { ReactNode } from "react";
import { AccountSettings } from "@/components/account-settings";
import { requirePageUser } from "@/server/security/page-auth";

export const dynamic = "force-dynamic";

export default async function SettingsPage() {
  const { user } = await requirePageUser();
  const profile = user.profile;

  return (
    <div className="space-y-3">
      <section className="rounded-lg border border-white/10 bg-[#101521] p-3 shadow-panel">
        <div className="flex items-center gap-2.5">
          <span className="grid h-9 w-9 place-items-center rounded-lg bg-felt/10 text-felt">
            <UserRound className="h-4 w-4" />
          </span>
          <div>
            <h1 className="text-xl font-extrabold text-white">Paramètres</h1>
            <p className="mt-0.5 text-xs text-slate-400">Compte, sécurité et informations personnelles.</p>
          </div>
        </div>
      </section>

      <section className="rounded-lg border border-white/10 bg-[#101521] p-3 shadow-panel">
        <div className="flex items-center gap-2">
          <LockKeyhole className="h-4 w-4 text-felt" />
          <h2 className="text-sm font-semibold text-white">Informations personnelles</h2>
        </div>
        <div className="mt-3 grid grid-cols-2 gap-2">
          <InfoTile label="Nom" value={profile?.lastName ?? "-"} locked />
          <InfoTile label="Prénom" value={profile?.firstName ?? "-"} locked />
          <InfoTile label="Pseudo" value={`@${user.username}`} />
          <InfoTile label="Statut" value={user.status} />
          <InfoTile label="Naissance" value={profile?.dateOfBirth ? formatDate(profile.dateOfBirth) : "-"} icon={<CalendarDays className="h-3.5 w-3.5" />} />
          <InfoTile label="Pays" value={profile?.country ?? "-"} icon={<Globe2 className="h-3.5 w-3.5" />} />
          <InfoTile label="Devise" value={profile?.currency ?? "EUR"} />
          <InfoTile label="Langue" value={profile?.language?.toUpperCase() ?? "FR"} />
        </div>
      </section>

      <AccountSettings currentEmail={user.email} />
    </div>
  );
}

function InfoTile({ label, value, locked = false, icon }: { label: string; value: string; locked?: boolean; icon?: ReactNode }) {
  return (
    <div className="rounded-lg border border-white/10 bg-white/[0.035] p-2.5">
      <div className="flex items-center gap-1.5 text-[10px] font-bold uppercase text-slate-500">
        {icon}
        {label}
        {locked ? <LockKeyhole className="ml-auto h-3 w-3 text-slate-600" /> : null}
      </div>
      <div className="mt-1 truncate text-sm font-semibold text-white">{value}</div>
    </div>
  );
}

function formatDate(value: Date) {
  return new Intl.DateTimeFormat("fr-FR", { day: "2-digit", month: "2-digit", year: "numeric" }).format(value);
}
