import { formatDistanceToNow } from 'date-fns';
import { sanitizeTerminalText } from '../../utils/terminal';
import { useAppState } from '../state/context';
import { colors } from '../theme';

export function Header() {
  const state = useAppState();

  const lastFetchText = state.lastFetchedAt ? formatDistanceToNow(state.lastFetchedAt, { addSuffix: true }) : 'never';

  const progressText = state.fetchProgress
    ? `  [Fetching ${state.fetchProgress.current}/${state.fetchProgress.total}...]`
    : '';

  return (
    <box height={1} backgroundColor={colors.bgHighlight} paddingLeft={1} paddingRight={1} flexDirection="row">
      <box flexGrow={1}>
        <text>
          <span fg={colors.accentBlue}>
            <strong>RSS Reader</strong>
          </span>
          <span fg={colors.textSecondary}> {' · '} </span>
          <span fg={colors.textPrimary}>{state.totalUnread} unread</span>
          <span fg={colors.textSecondary}> {' · '} </span>
          <span fg={colors.accentYellow}>{state.totalStarred} starred</span>
          <span fg={colors.textSecondary}> {' · '} </span>
          <span fg={colors.textSecondary}>Last: {lastFetchText}</span>
          {progressText ? <span fg={colors.accentGreen}>{progressText}</span> : null}
          {state.error ? (
            <span fg={colors.accentRed}>
              {' '}
              {' · '} {sanitizeTerminalText(state.error)}
            </span>
          ) : null}
        </text>
      </box>
      <box>
        <text>
          <span fg={colors.accentBlue}>
            <strong>?</strong>
          </span>
          <span fg={colors.textSecondary}> Help</span>
        </text>
      </box>
    </box>
  );
}
