import { Show, createSignal, onCleanup, onMount } from 'solid-js';
import { useAuth } from '~/lib/auth';

const WARNING_AT = 13 * 60 * 1000;
const LOGOUT_AT = 15 * 60 * 1000;

export default function SessionTimer() {
  const auth = useAuth();
  const [showWarning, setShowWarning] = createSignal(false);
  let warningTimer: ReturnType<typeof setTimeout> | null = null;
  let logoutTimer: ReturnType<typeof setTimeout> | null = null;
  let lastActivity = Date.now();

  const resetTimers = () => {
    lastActivity = Date.now();
    setShowWarning(false);
    if (warningTimer) clearTimeout(warningTimer);
    if (logoutTimer) clearTimeout(logoutTimer);
    warningTimer = setTimeout(() => setShowWarning(true), WARNING_AT);
    logoutTimer = setTimeout(() => auth.logout(), LOGOUT_AT);
  };

  const onActivity = () => {
    if (auth.isAuthenticated()) resetTimers();
  };

  onMount(() => {
    if (!auth.isAuthenticated()) return;
    resetTimers();

    const events = ['mousedown', 'keydown', 'touchstart', 'scroll'];
    for (const ev of events) {
      document.addEventListener(ev, onActivity, { passive: true });
    }

    onCleanup(() => {
      if (warningTimer) clearTimeout(warningTimer);
      if (logoutTimer) clearTimeout(logoutTimer);
      for (const ev of events) {
        document.removeEventListener(ev, onActivity);
      }
    });
  });

  return (
    <Show when={showWarning()}>
      <div style={{
        position: 'fixed',
        top: '0',
        left: '0',
        right: '0',
        bottom: '0',
        background: 'rgba(0,0,0,0.5)',
        display: 'flex',
        'align-items': 'center',
        'justify-content': 'center',
        'z-index': '9999',
      }}>
        <div style={{
          background: '#FFF',
          'border-radius': '16px',
          padding: '32px',
          'max-width': '420px',
          width: '90%',
          'text-align': 'center',
          'box-shadow': '0 20px 60px rgba(0,0,0,0.3)',
        }}>
          <p style={{
            margin: '0 0 8px',
            'font-size': '20px',
            'font-weight': '800',
            color: '#0D0D2A',
          }}>
            Session Expiring
          </p>
          <p style={{
            margin: '0 0 24px',
            'font-size': '14px',
            color: '#6B7280',
            'line-height': '1.6',
          }}>
            Your session will expire soon due to inactivity.
            Click continue to stay signed in.
          </p>
          <button
            type="button"
            onClick={resetTimers}
            style={{
              background: '#FF5E13',
              color: '#FFF',
              border: 'none',
              'border-radius': '10px',
              padding: '12px 32px',
              'font-size': '15px',
              'font-weight': '700',
              cursor: 'pointer',
              width: '100%',
            }}
          >
            Continue Session
          </button>
        </div>
      </div>
    </Show>
  );
}