"use client";

import { App, Card, Switch, Typography } from "antd";
import { useCallback, useEffect, useState } from "react";
import { getGlobalSettings, updateGlobalSettings } from "@/lib/api/settings";
import { ApiError } from "@/lib/api/client";

/**
 * Admin-only, unlike the personal 2FA setup card alongside it - this is the
 * org-wide master switch (global_settings.require_2fa). On, it both forces
 * enrollment for anyone without 2FA yet and enforces the challenge for
 * anyone who already has a device. Off, nobody is challenged at login at
 * all, even someone with their own device enrolled - see
 * AuthController::login().
 */
export function RequireTwoFactorToggle() {
  const { message } = App.useApp();
  const [require2fa, setRequire2fa] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);

  const load = useCallback(async () => {
    setIsLoading(true);
    try {
      const settings = await getGlobalSettings();
      setRequire2fa(settings.require_2fa);
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't load settings.");
    } finally {
      setIsLoading(false);
    }
  }, [message]);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    void load();
  }, [load]);

  async function handleToggle(checked: boolean) {
    setIsSaving(true);
    try {
      const updated = await updateGlobalSettings({ require_2fa: checked });
      setRequire2fa(updated.require_2fa);
      message.success(
        checked
          ? "Two-factor authentication is now required for every user."
          : "Two-factor authentication is no longer required.",
      );
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't change that setting.");
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <Card loading={isLoading} className="require-2fa-toggle dms_settings_security_require_2fa_card">
      <div className="flex items-center gap-3">
        <Switch checked={require2fa} loading={isSaving} onChange={handleToggle} />
        <div>
          <Typography.Text strong>Require Two-Factor Authentication For Everyone</Typography.Text>
          <Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
            When on, anyone signing in without 2FA set up is walked through scanning a QR code and confirming a
            code as part of that sign-in, before they reach the dashboard - no exceptions, admins included - and
            anyone who already has a device enrolled is challenged for a code every time. When off, nobody is
            asked for a code at sign-in, even if they have a device enrolled. Users manage their own devices in
            Settings → Profile regardless of this setting.
          </Typography.Paragraph>
        </div>
      </div>
    </Card>
  );
}
