'use client';

import { logoutAction } from '../app/actions';

type Props = {
  session: {
    user: {
      name: string;
      email: string;
      status: string;
      lastLoginAt: string | null;
      twoFactorEnabled: boolean;
      twoFactorConfirmedAt: string | null;
    };
    session: {
      issuedAt: string | null;
      expiresAt: string | null;
      refreshExpiresAt: string | null;
      currentIp: string | null;
      policy: 'single-session';
    };
  };
};

function formatDateTime(value: string | null) {
  if (!value) return 'Not available';

  return new Intl.DateTimeFormat('en-US', {
    dateStyle: 'medium',
    timeStyle: 'short',
  }).format(new Date(value));
}

export function SecuritySessionCard({ session }: Props) {
  return (
    <article className="surface-card security-session-card">
      <div className="security-session-head">
        <div>
          <p className="page-eyebrow">Session</p>
          <h2>Current Admin Session</h2>
          <p className="page-copy">
            BizOne currently enforces a single active admin session. A fresh login rotates tokens and replaces the
            previous session.
          </p>
        </div>
        <span className="security-session-badge">Single Session Policy</span>
      </div>

      <div className="security-session-grid">
        <div className="security-session-item">
          <strong>Signed in as</strong>
          <span>{session.user.name}</span>
          <small>{session.user.email}</small>
        </div>
        <div className="security-session-item">
          <strong>Access token issued</strong>
          <span>{formatDateTime(session.session.issuedAt)}</span>
        </div>
        <div className="security-session-item">
          <strong>Access token expires</strong>
          <span>{formatDateTime(session.session.expiresAt)}</span>
        </div>
        <div className="security-session-item">
          <strong>Refresh token expires</strong>
          <span>{formatDateTime(session.session.refreshExpiresAt)}</span>
        </div>
        <div className="security-session-item">
          <strong>Current IP</strong>
          <span>{session.session.currentIp || 'Unavailable'}</span>
        </div>
        <div className="security-session-item">
          <strong>Last successful login</strong>
          <span>{formatDateTime(session.user.lastLoginAt)}</span>
        </div>
      </div>

      <div className="security-session-actions">
        <form action={logoutAction}>
          <button type="submit" className="invite-submit-button">
            Sign Out and Revoke Session
          </button>
        </form>
        <p className="page-copy">
          Use this if you suspect account exposure. Signing out here invalidates the active refresh token and forces a
          fresh login.
        </p>
      </div>
    </article>
  );
}
