import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { ConnState } from '../../../../hooks/useConsoleSession';
import type { ConsoleSessionSummary } from '../../../../lib/ssh-console-types';

function fmtElapsed(ms: number): string {
  const total = Math.floor(ms / 1000);
  const h = Math.floor(total / 3600), m = Math.floor((total % 3600) / 60), s = total % 60;
  if (h) return `${h}h ${m}m`;
  if (m) return `${m}m ${s}s`;
  return `${s}s`;
}

/**
 * Detail line for the currently-selected console tab: connecting/replaying/
 * disconnected status, or (once connected) the connection id, uptime, idle
 * time and a read-only badge. `session` is the selected tab's REST-polled
 * summary (for label/timestamps); `state` is the live WS state from
 * useConsoleSession (for connected/canWrite, which the poll can't see).
 */
export function ConsoleHeader({ state, session }: { state: ConnState; session: ConsoleSessionSummary | null }) {
  const { t } = useTranslation('detail');
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    const timer = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(timer);
  }, []);

  if (state.kind === 'no_session') {
    return <div className="px-3 py-2 text-sm text-slate-500">{t('console.noActiveConsole')}</div>;
  }
  if (state.kind === 'connecting' || state.kind === 'replaying') {
    return (
      <div className="px-3 py-2 text-sm text-amber-600">
        {state.kind === 'connecting' ? t('console.connecting') : t('console.restoringScrollback')}
      </div>
    );
  }
  if (state.kind === 'disconnected') {
    return (
      <div className="px-3 py-2 text-sm text-red-700 dark:text-red-300">
        {t('console.disconnected', { reason: state.reason ?? t('console.unknownReason') })}
      </div>
    );
  }
  const startedAt = session?.started_at ? new Date(session.started_at).getTime() : now;
  const lastAt = session?.last_activity_at ? new Date(session.last_activity_at).getTime() : now;
  return (
    <div className="px-3 py-2 text-sm text-slate-700 border-b border-slate-200 flex items-center gap-3">
      <span className="text-green-600">● {t('console.connected')}</span>
      <span className="text-slate-500">{t('console.connLabel', { label: session?.connection_label ?? session?.connection_id ?? '—' })}</span>
      <span className="text-slate-500">{t('console.uptime', { time: fmtElapsed(now - startedAt) })}</span>
      <span className="text-slate-500">{t('console.idle', { time: fmtElapsed(now - lastAt) })}</span>
      {!state.canWrite && <span className="ml-auto rounded bg-slate-100 px-2 py-0.5 text-xs">{t('console.readOnly')}</span>}
    </div>
  );
}
