'use client';

import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { listMySessions, logoutSession, type UserSession } from '@/features/auth/api.client';
import { errorText } from '@/lib/api/errors';
import { ConfirmDialog } from './settings-ui';

const PAGE_SIZE = 4;

type Parsed = { device: string; browser: string };

/** Turns a raw User-Agent into the design's "Device" and "Browser" columns. */
export function parseUserAgent(ua: string | null): Parsed {
  if (!ua) return { device: 'Unknown device', browser: 'Unknown browser' };

  let os: string | null = null;
  if (/Windows/.test(ua)) os = 'Windows';
  else if (/iPhone|iPad|iPod/.test(ua)) os = 'iOS';
  else if (/Android/.test(ua)) os = 'Android';
  else if (/Macintosh|Mac OS X/.test(ua)) os = 'macOS';
  else if (/Linux/.test(ua)) os = 'Linux';

  const device =
    os === 'macOS'
      ? 'Mac (macOS)'
      : os === 'iOS'
        ? 'iPhone or iPad (iOS)'
        : os
          ? `Unknown device (${os})`
          : 'Unknown device';

  const rules: Array<[RegExp, string]> = [
    [/Edg\/([\d.]+)/, 'Edge'],
    [/OPR\/([\d.]+)/, 'Opera'],
    [/Firefox\/([\d.]+)/, 'Firefox'],
    [/Chrome\/([\d.]+)/, 'Chrome'],
    [/Version\/([\d.]+).*Safari/, 'Safari'],
  ];
  for (const [pattern, name] of rules) {
    const match = ua.match(pattern);
    if (match) return { device, browser: `${name} ${match[1]}` };
  }
  return { device, browser: 'Unknown browser' };
}

function gmtOffset(date: Date): string {
  const minutes = -date.getTimezoneOffset();
  const sign = minutes >= 0 ? '+' : '-';
  const abs = Math.abs(minutes);
  const h = Math.floor(abs / 60);
  const m = abs % 60;
  return `GMT${sign}${h}${m ? `:${String(m).padStart(2, '0')}` : ''}`;
}

/** "October 27, 2026 12:49 PM" in the browser's zone, as the design shows. */
function formatLastActive(date: Date): string {
  return date.toLocaleString('en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
    hour12: true,
  });
}

function relativeFromNow(date: Date, now = Date.now()): string {
  const seconds = Math.round((date.getTime() - now) / 1000);
  if (Math.abs(seconds) < 60) return 'a few seconds ago';
  const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
  const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [
    ['day', 86400],
    ['hour', 3600],
    ['minute', 60],
  ];
  for (const [unit, size] of units) {
    if (Math.abs(seconds) >= size) return rtf.format(Math.round(seconds / size), unit);
  }
  return rtf.format(seconds, 'second');
}

/**
 * Settings › Security › Session Management: the user's live sessions with per-session Log out.
 * `onSignOutCurrent` runs the existing sign-out for the session in this browser.
 * Danger-zone blocks (remove/delete account) nest under this section per Untitled-2.
 */
export function SecuritySessions({
  onSignOutCurrent,
  onLogoutAll,
  children,
}: {
  onSignOutCurrent: () => void;
  onLogoutAll: () => void;
  children?: ReactNode;
}) {
  const toast = useToast();
  const [sessions, setSessions] = useState<UserSession[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(0);
  const [pending, setPending] = useState<UserSession | null>(null);
  const [busy, setBusy] = useState(false);

  const load = useCallback(async () => {
    try {
      const res = await listMySessions();
      setSessions(res.data);
      setError(null);
    } catch (err) {
      setError(errorText(err));
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  const pageCount = Math.max(1, Math.ceil((sessions?.length ?? 0) / PAGE_SIZE));
  const shown = useMemo(
    () => (sessions ?? []).slice(page * PAGE_SIZE, page * PAGE_SIZE + PAGE_SIZE),
    [sessions, page],
  );

  useEffect(() => {
    if (page > pageCount - 1) setPage(pageCount - 1);
  }, [page, pageCount]);

  const confirmLogout = async () => {
    if (!pending) return;
    if (pending.current) {
      setPending(null);
      onSignOutCurrent();
      return;
    }
    setBusy(true);
    try {
      await logoutSession(pending.id);
      toast('Session logged out', 'success');
      setPending(null);
      await load();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  return (
    <section className="set-security-section set-security-section--sessions">
      <h2 className="set-security-title">Session Management</h2>
      <p className="set-security-subtitle">
        Manage your active and inactive sessions across devices.
      </p>

      {error ? (
        <p className="set-security-meta" role="alert">
          {error}
        </p>
      ) : null}

      <div className="set-security-table-wrap">
        <table className="set-security-table">
          <thead>
            <tr>
              <th>Device</th>
              <th>Browser</th>
              <th>
                IP Address{' '}
                <span className="set-security-info" title="Internet Protocol address">
                  ⓘ
                </span>
              </th>
              <th>Last Active</th>
            </tr>
          </thead>
          <tbody data-security-sessions>
            {sessions === null && !error ? (
              <tr>
                <td colSpan={4}>Loading sessions…</td>
              </tr>
            ) : null}
            {sessions !== null && sessions.length === 0 ? (
              <tr>
                <td colSpan={4}>No active sessions.</td>
              </tr>
            ) : null}
            {shown.map((s) => {
              const { device, browser } = parseUserAgent(s.userAgent);
              const last = new Date(s.lastActiveAt);
              return (
                <tr key={s.id}>
                  <td>
                    <span className="set-security-device">▣</span> {device}
                    {s.current ? <span className="set-security-current">Current</span> : null}
                    <button
                      type="button"
                      className="set-security-session-logout"
                      data-session-logout
                      onClick={() => setPending(s)}
                    >
                      Log out
                    </button>
                  </td>
                  <td>{browser}</td>
                  <td>{s.ip ?? '—'}</td>
                  <td>
                    {formatLastActive(last)}
                    <br />
                    {gmtOffset(last)} <small>{relativeFromNow(last)}</small>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <nav className="set-security-pagination" aria-label="Session pages">
        <button
          type="button"
          disabled={page === 0}
          onClick={() => setPage((p) => Math.max(0, p - 1))}
          aria-label="Previous page"
        >
          ‹
        </button>
        <span>Prev</span>
        <strong>{page + 1}</strong>
        <span>Next</span>
        <button
          type="button"
          disabled={page >= pageCount - 1}
          onClick={() => setPage((p) => Math.min(pageCount - 1, p + 1))}
          aria-label="Next page"
        >
          ›
        </button>
      </nav>

      <div className="set-security-danger-block">
        <h3>Log Out of All Sessions</h3>
        <p>This will log you out of all devices and sessions, including this active one.</p>
        <button type="button" className="set-security-link" onClick={onLogoutAll}>
          Log Out of All Sessions
        </button>
      </div>

      {children}

      <ConfirmDialog
        id="session-logout"
        open={pending !== null}
        onClose={() => setPending(null)}
        title={pending?.current ? 'Sign out?' : 'Log out this session?'}
        confirmLabel="Log out"
        danger={!pending?.current}
        onConfirm={() => {
          if (!busy) void confirmLogout();
        }}
      >
        <p>
          {pending?.current
            ? 'You will be signed out of the CRM in this browser.'
            : 'This device will be signed out of your account.'}
        </p>
      </ConfirmDialog>
    </section>
  );
}
