'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;
  };
  labels: {
    twoFactorTitle: string;
    twoFactorCopy: string;
    status: string;
    enabled: string;
    disabled: string;
    confirmedAt: string;
    notEnabled: string;
    backupCodesRemaining: string;
    preparing: string;
    startSetup: string;
    recoveryCodesCopy: string;
    manualEntryKey: string;
    otpauthUrl: string;
    verificationCode: string;
    verifying: string;
    confirmEnable: string;
    backupRecoveryCodes: string;
    regenerateCodeLabel: string;
    regenerating: string;
    regenerateCodes: string;
    newBackupRecoveryCodes: string;
    current2faCode: string;
    disabling: string;
    disable2fa: string;
    scanQrAlt: string;
  };
};

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

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

  return (
    <div className="invite-form">
      <strong>{title}</strong>
      <p className="page-copy">{copy}</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, labels }: 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 labels.notEnabled;
    return new Date(status.confirmedAt).toLocaleString();
  }, [labels.notEnabled, status.confirmedAt]);

  return (
    <article className="surface-card">
      <h2>{labels.twoFactorTitle}</h2>
      <p className="page-copy">{labels.twoFactorCopy}</p>

      <div className="metric-stack">
        <div>
          <strong>{labels.status}</strong>
          <span>{status.enabled ? labels.enabled : labels.disabled}</span>
        </div>
        <div>
          <strong>{labels.confirmedAt}</strong>
          <span>{confirmedLabel}</span>
        </div>
        <div>
          <strong>{labels.backupCodesRemaining}</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 ? labels.preparing : labels.startSetup}
          </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={labels.scanQrAlt}
                width={220}
                height={220}
                style={{ borderRadius: '1rem', border: '1px solid var(--border-subtle)', background: '#fff' }}
              />
            </div>
          ) : null}

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

          <form action={confirmAction} className="invite-form">
            <label className="invite-field">
              <span>{labels.verificationCode}</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 ? labels.verifying : labels.confirmEnable}
            </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={labels.backupRecoveryCodes}
            copy={labels.recoveryCodesCopy}
          />
        </div>
      ) : null}

      {status.enabled ? (
        <>
          <form action={regenerateAction} className="invite-form">
            <label className="invite-field">
              <span>{labels.regenerateCodeLabel}</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 ? labels.regenerating : labels.regenerateCodes}
            </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={labels.newBackupRecoveryCodes}
            copy={labels.recoveryCodesCopy}
          />

          <form action={disableAction} className="invite-form">
            <label className="invite-field">
              <span>{labels.current2faCode}</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 ? labels.disabling : labels.disable2fa}
            </button>
            {disableState.error ? <p className="form-error">{disableState.error}</p> : null}
            {disableState.success ? <p className="form-success">{disableState.success}</p> : null}
          </form>
        </>
      ) : null}
    </article>
  );
}
