// @File: src/pages/admin/cms/CmsMfa.tsx
// @Desc: Admin-only page that manages two MFA concerns:
//        1. Global enforcement toggle — when ON, any admin without MFA must
//           enroll before they can finish signing in.
//        2. Roster view — lists every admin account with their SMS MFA
//           state, masked phone, and last-verified timestamp.
//        It also embeds the per-user SMS MFA setup widget so the logged-in
//        admin can enroll/disable their own phone from the same page.
import { useEffect, useState } from "react";
import { AlertCircle, CheckCircle2, ShieldCheck, Smartphone, RefreshCw, Loader2 } from "lucide-react";
import CmsLayout from "./CmsLayout";
import { PageHeader, SectionCard, Toggle, Badge } from "./ui";
import MfaSettingsPanel from "@/components/mfa/MfaSettingsPanel";
import {
  mfaAdminGetEnforcement,
  mfaAdminRoster,
  mfaAdminSetEnforcement,
  type MfaAdminRosterEntry,
} from "@/lib/adminApi";

function formatDateTime(value: string | null): string {
  if (!value) return "—";
  try {
    return new Date(value).toLocaleString();
  } catch {
    return value;
  }
}

export default function CmsMfa() {
  const [enforceOn, setEnforceOn] = useState(false);
  const [enforceLoading, setEnforceLoading] = useState(true);
  const [enforceSaving, setEnforceSaving] = useState(false);
  const [roster, setRoster] = useState<MfaAdminRosterEntry[]>([]);
  const [rosterLoading, setRosterLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [toast, setToast] = useState<{ ok: boolean; msg: string } | null>(null);

  const notify = (ok: boolean, msg: string) => {
    setToast({ ok, msg });
    window.setTimeout(() => setToast(null), 3500);
  };

  async function loadAll() {
    setError(null);
    setEnforceLoading(true);
    setRosterLoading(true);
    try {
      const [en, rs] = await Promise.all([mfaAdminGetEnforcement(), mfaAdminRoster()]);
      setEnforceOn(en.require_admin_mfa);
      setRoster(rs);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load MFA settings.");
    } finally {
      setEnforceLoading(false);
      setRosterLoading(false);
    }
  }

  useEffect(() => {
    loadAll();
  }, []);

  async function handleEnforceToggle(next: boolean) {
    setEnforceSaving(true);
    const prev = enforceOn;
    setEnforceOn(next);
    try {
      const resp = await mfaAdminSetEnforcement(next);
      setEnforceOn(resp.require_admin_mfa);
      notify(
        true,
        resp.require_admin_mfa
          ? "MFA is now required for every admin login."
          : "Admin MFA enforcement has been disabled.",
      );
    } catch (err) {
      setEnforceOn(prev);
      notify(false, err instanceof Error ? err.message : "Failed to update enforcement.");
    } finally {
      setEnforceSaving(false);
    }
  }

  const enrolledCount = roster.filter((r) => r.enabled).length;
  const notEnrolledCount = roster.length - enrolledCount;

  return (
    <CmsLayout>
      <PageHeader
        icon={<ShieldCheck className="w-6 h-6" />}
        title="Multi-Factor Authentication"
        description="Require SMS verification on admin sign-in and manage enrollment."
      />

      {error && (
        <div className="mb-4 p-3 rounded-lg bg-red-50 border border-red-200 text-sm text-red-800 flex items-center gap-2">
          <AlertCircle className="w-4 h-4" /> {error}
        </div>
      )}
      {toast && (
        <div
          className={`mb-4 p-3 rounded-lg text-sm flex items-center gap-2 ${
            toast.ok
              ? "bg-emerald-50 border border-emerald-200 text-emerald-800"
              : "bg-red-50 border border-red-200 text-red-800"
          }`}
        >
          {toast.ok ? <CheckCircle2 className="w-4 h-4" /> : <AlertCircle className="w-4 h-4" />}
          {toast.msg}
        </div>
      )}

      <SectionCard
        title="Global policy"
        description="When enabled, every admin must complete an SMS challenge to finish signing in. Admins without an enrolled phone will be blocked until an administrator enrolls them."
      >
        {enforceLoading ? (
          <div className="text-sm text-slate-500 flex items-center gap-2">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading policy…
          </div>
        ) : (
          <Toggle
            label="Require MFA for all admin logins"
            description={
              enforceSaving
                ? "Saving…"
                : "Admins with no enrolled phone will be locked out until they enroll."
            }
            checked={enforceOn}
            onChange={handleEnforceToggle}
          />
        )}
      </SectionCard>

      <div className="h-6" />

      <SectionCard
        title="Your MFA"
        description="Enroll or disable SMS verification for the account you are currently signed in with."
      >
        <MfaSettingsPanel onChanged={() => loadAll()} />
      </SectionCard>

      <div className="h-6" />

      <SectionCard
        title="Admin roster"
        description="SMS MFA status for every admin account. Users enroll their own phone from their profile."
      >
        <div className="flex flex-wrap items-center gap-2 mb-4">
          <Badge tone="green">{enrolledCount} enrolled</Badge>
          <Badge tone="yellow">{notEnrolledCount} not enrolled</Badge>
          <button
            type="button"
            onClick={loadAll}
            className="ml-auto text-xs font-medium text-[#0b6e3e] hover:text-[#0a8048] inline-flex items-center gap-1"
          >
            <RefreshCw className="w-3.5 h-3.5" /> Refresh
          </button>
        </div>

        {rosterLoading ? (
          <div className="text-sm text-slate-500 flex items-center gap-2">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading admins…
          </div>
        ) : roster.length === 0 ? (
          <div className="text-sm text-slate-500">No admin accounts found.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-xs uppercase tracking-wider text-slate-500 border-b border-slate-200">
                  <th className="py-2 pr-3">Admin</th>
                  <th className="py-2 pr-3">MFA</th>
                  <th className="py-2 pr-3">Phone</th>
                  <th className="py-2 pr-3">Last verified</th>
                </tr>
              </thead>
              <tbody>
                {roster.map((r) => (
                  <tr key={r.user_id} className="border-b border-slate-100">
                    <td className="py-2.5 pr-3">
                      <div className="font-semibold text-slate-800">{r.name || r.email}</div>
                      <div className="text-xs text-slate-500">{r.email}</div>
                    </td>
                    <td className="py-2.5 pr-3">
                      {r.enabled ? (
                        <Badge tone="green">
                          <Smartphone className="w-3 h-3 inline mr-1" />
                          SMS enabled
                        </Badge>
                      ) : (
                        <Badge tone="yellow">Not enrolled</Badge>
                      )}
                    </td>
                    <td className="py-2.5 pr-3 font-mono text-xs text-slate-700">
                      {r.phone_masked || "—"}
                    </td>
                    <td className="py-2.5 pr-3 text-slate-600">
                      {formatDateTime(r.last_verified_at)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>
    </CmsLayout>
  );
}