'use client';

import { useActionState, useMemo } from 'react';
import {
  confirmTwoFactorSetupAction,
  disableTwoFactorAction,
  initiateTwoFactorSetupAction,
  regenerateTwoFactorRecoveryCodesAction,
} from '../app/actions';

type Props = {
  status: {
    enabled: boolean;
    pendingSetup: boolean;
    confirmedAt: string | null;
    recoveryCodesRemaining: number;
  };
};

const initialState: {
  error?: string;
  success?: string;
  manualEntryKey?: string;
  otpauthUrl?: string;
  qrCodeDataUrl?: string;
  recoveryCodes?: string[];
} = {};

function RecoveryCodesPanel({ codes, title }: { codes: string[]; title: string }) {
  if (codes.length === 0) {
    return null;
  }

  return (
    <div className="invite-form">
      <strong>{title}</strong>
      <p className="page-copy">Simpan kode ini sekarang. Setiap kode hanya bisa dipakai sekali saat login darurat.</p>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))',
          gap: '0.75rem',
        }}
      >
        {codes.map((code) => (
          <div
            key={code}
            style={{
              border: '1px solid var(--border-subtle)',
              borderRadius: '0.9rem',
              padding: '0.8rem 1rem',
              background: 'var(--surface-muted)',
              fontFamily: 'var(--font-mono)',
              fontWeight: 700,
              letterSpacing: '0.08em',
            }}
          >
            {code}
          </div>
        ))}
      </div>
    </div>
  );
}

export function TwoFactorSettingsCard({ status }: Props) {
  const [setupState, setupAction, setupPending] = useActionState(initiateTwoFactorSetupAction, initialState);
  const [confirmState, confirmAction, confirmPending] = useActionState(confirmTwoFactorSetupAction, initialState);
  const [regenerateState, regenerateAction, regeneratePending] = useActionState(
    regenerateTwoFactorRecoveryCodesAction,
    initialState,
  );
  const [disableState, disableAction, disablePending] = useActionState(disableTwoFactorAction, initialState);

  const manualEntryKey = setupState.manualEntryKey;
  const otpauthUrl = setupState.otpauthUrl;
  const qrCodeDataUrl = setupState.qrCodeDataUrl;
  const hasPendingSecret = status.pendingSetup || Boolean(manualEntryKey);
  const confirmedLabel = useMemo(() => {
    if (!status.confirmedAt) return 'Not enabled';
    return new Date(status.confirmedAt).toLocaleString();
  }, [status.confirmedAt]);

  return (
    <article className="surface-card">
      <h2>Two-Factor Authentication</h2>
      <p className="page-copy">
        Protect admin login with a time-based code from Google Authenticator, 1Password, or another TOTP app.
      </p>

      <div className="metric-stack">
        <div>
          <strong>Status</strong>
          <span>{status.enabled ? 'Enabled' : 'Disabled'}</span>
        </div>
        <div>
          <strong>Confirmed At</strong>
          <span>{confirmedLabel}</span>
        </div>
        <div>
          <strong>Backup Codes Remaining</strong>
          <span>{status.recoveryCodesRemaining}</span>
        </div>
      </div>

      {!status.enabled ? (
        <form action={setupAction} className="invite-form">
          <button type="submit" className="invite-submit-button" disabled={setupPending}>
            {setupPending ? 'Preparing...' : 'Start 2FA Setup'}
          </button>
          {setupState.error ? <p className="form-error">{setupState.error}</p> : null}
          {setupState.success ? <p className="form-success">{setupState.success}</p> : null}
        </form>
      ) : null}

      {hasPendingSecret && !status.enabled ? (
        <div className="invite-form">
          {qrCodeDataUrl ? (
            <div
              style={{
                display: 'grid',
                justifyItems: 'start',
                gap: '0.75rem',
              }}
            >
              <img
                src={qrCodeDataUrl}
                alt="Scan this QR code in your authenticator app"
                width={220}
                height={220}
                style={{ borderRadius: '1rem', border: '1px solid var(--border-subtle)', background: '#fff' }}
              />
            </div>
          ) : null}

          <label className="invite-field">
            <span>Manual Entry Key</span>
            <input type="text" readOnly value={manualEntryKey || ''} />
          </label>
          {otpauthUrl ? (
            <label className="invite-field">
              <span>OTPAuth URL</span>
              <textarea readOnly rows={4} value={otpauthUrl} />
            </label>
          ) : null}

          <form action={confirmAction} className="invite-form">
            <label className="invite-field">
              <span>Verification Code</span>
              <input name="code" type="text" inputMode="numeric" pattern="[0-9]{6}" maxLength={6} placeholder="123456" />
            </label>
            <button type="submit" className="invite-submit-button" disabled={confirmPending}>
              {confirmPending ? 'Verifying...' : 'Confirm and Enable 2FA'}
            </button>
            {confirmState.error ? <p className="form-error">{confirmState.error}</p> : null}
            {confirmState.success ? <p className="form-success">{confirmState.success}</p> : null}
          </form>

          <RecoveryCodesPanel
            codes={confirmState.recoveryCodes || []}
            title="Backup Recovery Codes"
          />
        </div>
      ) : null}

      {status.enabled ? (
        <>
          <form action={regenerateAction} className="invite-form">
            <label className="invite-field">
              <span>Current 2FA Code to Regenerate Backup Codes</span>
              <input name="code" type="text" inputMode="numeric" pattern="[0-9]{6}" maxLength={6} placeholder="123456" />
            </label>
            <button type="submit" className="invite-submit-button" disabled={regeneratePending}>
              {regeneratePending ? 'Regenerating...' : 'Regenerate Backup Codes'}
            </button>
            {regenerateState.error ? <p className="form-error">{regenerateState.error}</p> : null}
            {regenerateState.success ? <p className="form-success">{regenerateState.success}</p> : null}
          </form>

          <RecoveryCodesPanel
            codes={regenerateState.recoveryCodes || []}
            title="New Backup Recovery Codes"
          />

          <form action={disableAction} className="invite-form">
            <label className="invite-field">
              <span>Current 2FA Code</span>
              <input name="code" type="text" inputMode="numeric" pattern="[0-9]{6}" maxLength={6} placeholder="123456" />
            </label>
            <button type="submit" className="invite-submit-button" disabled={disablePending}>
              {disablePending ? 'Disabling...' : 'Disable 2FA'}
            </button>
            {disableState.error ? <p className="form-error">{disableState.error}</p> : null}
            {disableState.success ? <p className="form-success">{disableState.success}</p> : null}
          </form>
        </>
      ) : null}
    </article>
  );
}
