'use client';

import { useEffect, useState, useTransition } from 'react';
import {
  listMySessions,
  revokeSession,
  revokeAllOtherSessions,
  type SessionRow,
} from '@/app/main/settings/sessionsActions';

function relAge(iso: string): string {
  const ms = Date.now() - new Date(iso).getTime();
  const m = Math.floor(ms / 60_000);
  if (m < 1) return 'just now';
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  const d = Math.floor(h / 24);
  return `${d}d ago`;
}

export default function SessionsList() {
  const [rows, setRows] = useState<SessionRow[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [pending, startTransition] = useTransition();

  const refresh = () => {
    listMySessions()
      .then(setRows)
      .catch((e) => setError(e.message ?? 'Failed to load sessions.'));
  };

  useEffect(() => {
    refresh();
  }, []);

  const onRevoke = (id: string) => {
    startTransition(async () => {
      setError(null);
      const res = await revokeSession(id);
      if (res.error) setError(res.error);
      refresh();
    });
  };

  const onRevokeAll = () => {
    startTransition(async () => {
      setError(null);
      const res = await revokeAllOtherSessions();
      if (res.error) setError(res.error);
      refresh();
    });
  };

  const otherCount = (rows ?? []).filter((r) => !r.isCurrent).length;

  return (
    <section className="bg-zinc-900 rounded border border-zinc-800 p-6 space-y-4">
      <header className="flex items-start justify-between gap-4">
        <div>
          <h2 className="text-sm font-semibold text-white uppercase tracking-wider">
            Active sessions
          </h2>
          <p className="text-xs text-zinc-500 mt-1">
            Each row is a browser or device with a valid session cookie.
            Revoking ends that session immediately.
          </p>
        </div>
        {otherCount > 0 && (
          <button
            type="button"
            onClick={onRevokeAll}
            disabled={pending}
            className="text-xs px-3 py-1.5 rounded border border-zinc-700 text-zinc-300 uppercase tracking-wider hover:bg-zinc-800 disabled:opacity-50 whitespace-nowrap"
          >
            Sign out other devices
          </button>
        )}
      </header>

      {error && (
        <div className="rounded bg-red-900/50 px-3 py-2 border border-red-800 text-xs text-red-400">
          {error}
        </div>
      )}

      {rows == null ? (
        <p className="text-xs text-zinc-500">Loading...</p>
      ) : rows.length === 0 ? (
        <p className="text-xs text-zinc-500">No active sessions.</p>
      ) : (
        <ul className="divide-y divide-zinc-800 -mx-2">
          {rows.map((s) => (
            <li
              key={s.id}
              className="flex items-center justify-between gap-3 px-2 py-3"
            >
              <div className="min-w-0">
                <div className="flex items-center gap-2 text-sm text-white font-mono">
                  <span>...{s.tokenSuffix}</span>
                  {s.isCurrent && (
                    <span className="text-[10px] uppercase tracking-wider bg-emerald-900/50 text-emerald-300 px-1.5 py-0.5 rounded font-sans">
                      this device
                    </span>
                  )}
                </div>
                <div className="text-xs text-zinc-500 mt-0.5">
                  Started {relAge(s.createdAt)} · Expires{' '}
                  {new Date(s.expiresAt).toLocaleDateString()}
                </div>
              </div>
              {!s.isCurrent && (
                <button
                  type="button"
                  onClick={() => onRevoke(s.id)}
                  disabled={pending}
                  className="text-xs px-2 py-1 rounded border border-red-900 text-red-400 hover:bg-red-900/30 disabled:opacity-50"
                >
                  Revoke
                </button>
              )}
            </li>
          ))}
        </ul>
      )}
    </section>
  );
}
