'use client';

import { useCallback, useEffect, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  confirmTwoFactorSetup,
  disableTwoFactor,
  getTwoFactorStatus,
  regenerateTwoFactorBackupCodes,
  startTwoFactorSetup,
  type TwoFactorStatus,
} from '../api.client';
import { errorText } from '@/lib/api/errors';

/**
 * Settings › Security › Two-factor authentication (2FA).
 * Markup matches PHP design `settings-profile.php` / Untitled-2:
 * Remove Security App · Set up secondary method · View backup codes
 * (static in PHP — no enable/disable check there).
 */
export function ProfileTwoFactorPanel() {
  const toast = useToast();
  const [status, setStatus] = useState<TwoFactorStatus | null>(null);
  const [secret, setSecret] = useState<string | null>(null);
  const [otpauthUrl, setOtpauthUrl] = useState<string | null>(null);
  const [code, setCode] = useState('');
  const [removeOpen, setRemoveOpen] = useState(false);
  const [removeCode, setRemoveCode] = useState('');
  const [manageCodes, setManageCodes] = useState(false);
  const [regenCode, setRegenCode] = useState('');
  const [backupCodes, setBackupCodes] = useState<string[] | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const reload = useCallback(async () => {
    const row = await getTwoFactorStatus();
    setStatus(row);
  }, []);

  useEffect(() => {
    void reload().catch((err) => setError(errorText(err)));
  }, [reload]);

  const onStart = useCallback(async () => {
    setError(null);
    setBackupCodes(null);
    setRemoveOpen(false);
    setManageCodes(false);
    setBusy(true);
    try {
      const row = await startTwoFactorSetup();
      setSecret(row.secret);
      setOtpauthUrl(row.otpauthUrl);
      setCode('');
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  }, []);

  const onConfirm = useCallback(async () => {
    setError(null);
    setBusy(true);
    try {
      const result = await confirmTwoFactorSetup(code.trim());
      setBackupCodes(result.backupCodes);
      setSecret(null);
      setOtpauthUrl(null);
      setCode('');
      await reload();
      toast('Two-factor authentication enabled', 'success');
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  }, [code, reload, toast]);

  /** "Remove Security App" (primary method): turns 2FA off after a current code. */
  const onRemove = useCallback(async () => {
    setError(null);
    setBusy(true);
    try {
      await disableTwoFactor(removeCode.trim());
      setRemoveCode('');
      setRemoveOpen(false);
      setManageCodes(false);
      setBackupCodes(null);
      await reload();
      toast('Two-factor authentication removed', 'success');
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  }, [removeCode, reload, toast]);

  const onRegenerate = useCallback(async () => {
    setError(null);
    setBusy(true);
    try {
      const result = await regenerateTwoFactorBackupCodes(regenCode.trim());
      setBackupCodes(result.backupCodes);
      setManageCodes(false);
      setRegenCode('');
      await reload();
      toast('New backup codes created. The old codes no longer work.', 'success');
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  }, [regenCode, reload, toast]);

  const onCancelSetup = useCallback(() => {
    setSecret(null);
    setOtpauthUrl(null);
    setCode('');
    setError(null);
  }, []);

  const onSecondary = useCallback(() => {
    toast('A second authentication method is not available yet.', 'info');
  }, [toast]);

  if (!status) {
    return (
      <div className="set-security-block set-security-block--twofa">
        <h3>Two-factor authentication (2FA)</h3>
        <p className="set-security-meta">{error ?? 'Loading…'}</p>
      </div>
    );
  }

  const enabled = status.enabled;
  const codesLeft = status.backupCodesRemaining;
  const inSetup = Boolean(secret && otpauthUrl);

  return (
    <div className="set-security-block set-security-block--twofa">
      <h3>Two-factor authentication (2FA)</h3>
      {status.setupRequired && !enabled ? (
        <p className="set-security-meta" role="status">
          Your account requires 2FA. Enable it below to keep signing in.
        </p>
      ) : null}
      {error ? (
        <p className="set-security-meta" role="alert">
          {error}
        </p>
      ) : null}

      {backupCodes ? (
        <div className="set-2fa-backup">
          <p>Save these backup codes now. Each works once and will not be shown again.</p>
          <ul className="set-2fa-backup__list">
            {backupCodes.map((c) => (
              <li key={c}>
                <code>{c}</code>
              </li>
            ))}
          </ul>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => setBackupCodes(null)}
          >
            Done
          </button>
        </div>
      ) : null}

      {inSetup ? (
        <div className="set-2fa-setup">
          <p>
            Scan the QR code, or enter the secret in your authenticator app, then confirm with a
            code.
          </p>
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            alt="Authenticator QR code"
            width={180}
            height={180}
            src={`https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=${encodeURIComponent(otpauthUrl!)}`}
          />
          <p className="set-security-meta">
            Secret: <code>{secret}</code>
          </p>
          <label className="field">
            <span className="field__label">6-digit code</span>
            <input
              className="field__input"
              value={code}
              onChange={(e) => setCode(e.target.value)}
              inputMode="numeric"
              autoComplete="one-time-code"
              placeholder="123456"
            />
          </label>
          <div className="set-2fa-setup__actions">
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              disabled={busy || !/^\d{6}$/.test(code.trim())}
              onClick={() => void onConfirm()}
            >
              Confirm and enable
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              disabled={busy}
              onClick={onCancelSetup}
            >
              Cancel
            </button>
          </div>
        </div>
      ) : (
        <>
          {/* PHP: settings-profile.php — set-security-block--twofa (always shown in design) */}
          <p>
            {enabled ? (
              <button
                type="button"
                className="set-security-link"
                data-security-action="remove-security-app"
                aria-expanded={removeOpen}
                onClick={() => {
                  setManageCodes(false);
                  setRemoveOpen((open) => !open);
                }}
              >
                Remove Security App
              </button>
            ) : (
              <button
                type="button"
                className="set-security-link"
                data-security-action="setup-security-app"
                disabled={busy}
                onClick={() => void onStart()}
              >
                Set up Security App
              </button>
            )}
            <span className="set-security-meta">Primary method</span>
          </p>
          {enabled && removeOpen ? (
            <div className="set-2fa-manage">
              <label className="field">
                <span className="field__label">Authenticator code</span>
                <input
                  className="field__input"
                  value={removeCode}
                  onChange={(e) => setRemoveCode(e.target.value)}
                  inputMode="numeric"
                  autoComplete="one-time-code"
                  placeholder="123456"
                />
              </label>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                disabled={busy || removeCode.trim().length < 6}
                onClick={() => void onRemove()}
              >
                Remove Security App
              </button>
            </div>
          ) : null}

          <p>
            <button
              type="button"
              className="set-security-link"
              data-security-action="setup-secondary-method"
              onClick={onSecondary}
            >
              Set up secondary method
            </button>
            <span className="set-security-meta">Secondary method</span>
          </p>

          <p>
            <button
              type="button"
              className="set-security-link"
              data-security-action="view-backup-codes"
              aria-expanded={manageCodes}
              disabled={!enabled}
              title={enabled ? undefined : 'Enable 2FA to manage backup codes'}
              onClick={() => {
                if (!enabled) return;
                setRemoveOpen(false);
                setManageCodes((open) => !open);
              }}
            >
              View backup codes
            </button>
            <span className="set-security-meta">
              {enabled
                ? codesLeft === 1
                  ? '1 code remaining'
                  : `${codesLeft} codes remaining`
                : 'Not set up'}
            </span>
          </p>
          {enabled && manageCodes ? (
            <div className="set-2fa-manage">
              <p>
                Backup codes cannot be shown again. Create a new set to replace them; the old codes
                stop working.
              </p>
              <label className="field">
                <span className="field__label">Authenticator code</span>
                <input
                  className="field__input"
                  value={regenCode}
                  onChange={(e) => setRegenCode(e.target.value)}
                  inputMode="numeric"
                  autoComplete="one-time-code"
                  placeholder="123456"
                />
              </label>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                disabled={busy || !/^\d{6}$/.test(regenCode.trim())}
                onClick={() => void onRegenerate()}
              >
                Create new backup codes
              </button>
            </div>
          ) : null}
        </>
      )}
    </div>
  );
}
