import { formatTokenCount } from '@robota-sdk/agent-core';
import { Box, Text } from 'ink';
import React from 'react';

import { formatStatusActivity } from './status-activity.js';

import type { TPermissionMode } from '@robota-sdk/agent-core';

/** Threshold boundaries for context percentage color coding */
const CONTEXT_YELLOW_THRESHOLD = 70;
const CONTEXT_RED_THRESHOLD = 90;

interface IProps {
  permissionMode: TPermissionMode;
  modelName: string;
  providerDisplayName?: string | undefined;
  sessionId: string;
  isThinking: boolean;
  activeToolCount?: number;
  activeBackgroundTaskCount?: number;
  hasPendingPrompt?: boolean;
  contextPercentage: number;
  contextUsedTokens: number;
  contextMaxTokens: number;
  sessionName?: string;
  gitBranch?: string;
  showGitBranch?: boolean;
  activeAgentLabel?: string;
  activePresetId?: string;
}

interface IStatusLeftProps {
  permissionMode: TPermissionMode;
  modelName: string;
  providerDisplayName?: string | undefined;
  isThinking: boolean;
  activeToolCount: number;
  activeBackgroundTaskCount: number;
  hasPendingPrompt: boolean;
  contextPercentage: number;
  contextUsedTokens: number;
  contextMaxTokens: number;
  sessionName?: string;
  gitBranch?: string;
  showGitBranch: boolean;
  activePresetId?: string;
}

/** Return the color for the context percentage indicator */
function getContextColor(percentage: number): string {
  if (percentage >= CONTEXT_RED_THRESHOLD) return 'red';
  if (percentage >= CONTEXT_YELLOW_THRESHOLD) return 'yellow';
  return 'green';
}

function StatusActivityText({
  isThinking,
  activeToolCount,
  activeBackgroundTaskCount,
  hasPendingPrompt,
}: Pick<
  IStatusLeftProps,
  'isThinking' | 'activeToolCount' | 'activeBackgroundTaskCount' | 'hasPendingPrompt'
>): React.ReactElement {
  const activity = formatStatusActivity({
    isThinking,
    activeToolCount,
    activeBackgroundTaskCount,
    hasPendingPrompt,
  });

  return (
    <Text color={activity.color} bold={activity.kind !== 'idle'}>
      {activity.text}
    </Text>
  );
}

function ContextText({
  percentage,
  usedTokens,
  maxTokens,
}: {
  percentage: number;
  usedTokens: number;
  maxTokens: number;
}): React.ReactElement {
  return (
    <Text color={getContextColor(percentage)}>
      Context: {Math.round(percentage)}% ({formatTokenCount(usedTokens)}/
      {formatTokenCount(maxTokens)} tokens)
    </Text>
  );
}

function ModeText({ permissionMode }: { permissionMode: TPermissionMode }): React.ReactElement {
  return (
    <>
      <Text color="cyan" bold>
        Mode:
      </Text>{' '}
      <Text>{permissionMode}</Text>
    </>
  );
}

function shouldShowPermissionMode(permissionMode: TPermissionMode): boolean {
  return permissionMode !== 'default';
}

function PresetText({ activePresetId }: { activePresetId: string }): React.ReactElement {
  return (
    <>
      <Text color="cyan" bold>
        Preset:
      </Text>{' '}
      <Text>{activePresetId}</Text>
    </>
  );
}

function shouldShowActivePreset(activePresetId: string | undefined): activePresetId is string {
  return activePresetId !== undefined && activePresetId !== 'default';
}

function ProviderText({
  modelName,
  providerDisplayName,
}: {
  modelName: string;
  providerDisplayName?: string | undefined;
}): React.ReactElement {
  if (providerDisplayName !== undefined) {
    return (
      <Text dimColor>
        {providerDisplayName} {modelName}
      </Text>
    );
  }
  return <Text dimColor>{modelName}</Text>;
}

function StatusLeft(props: IStatusLeftProps): React.ReactElement {
  const shouldShowGitBranch =
    props.showGitBranch && props.gitBranch !== undefined && props.gitBranch.length > 0;
  const showPermissionMode = shouldShowPermissionMode(props.permissionMode);
  const activePresetId = props.activePresetId;
  const showActivePreset = shouldShowActivePreset(activePresetId);
  return (
    <Text>
      <StatusActivityText
        isThinking={props.isThinking}
        activeToolCount={props.activeToolCount}
        activeBackgroundTaskCount={props.activeBackgroundTaskCount}
        hasPendingPrompt={props.hasPendingPrompt}
      />
      {showPermissionMode && (
        <>
          {'  |  '}
          <ModeText permissionMode={props.permissionMode} />
        </>
      )}
      {showActivePreset && (
        <>
          {'  |  '}
          <PresetText activePresetId={activePresetId} />
        </>
      )}
      {props.sessionName && (
        <>
          {'  |  '}
          <Text color="magenta">{props.sessionName}</Text>
        </>
      )}
      {shouldShowGitBranch && (
        <>
          {'  |  '}
          <Text dimColor>git: {props.gitBranch}</Text>
        </>
      )}
      {'  |  '}
      <ProviderText modelName={props.modelName} providerDisplayName={props.providerDisplayName} />
      {'  |  '}
      <ContextText
        percentage={props.contextPercentage}
        usedTokens={props.contextUsedTokens}
        maxTokens={props.contextMaxTokens}
      />
    </Text>
  );
}

export default function StatusBar({
  permissionMode,
  modelName,
  providerDisplayName,
  sessionId: _sessionId,
  isThinking,
  activeToolCount = 0,
  activeBackgroundTaskCount = 0,
  hasPendingPrompt = false,
  contextPercentage,
  contextUsedTokens,
  contextMaxTokens,
  sessionName,
  gitBranch,
  showGitBranch = true,
  activeAgentLabel,
  activePresetId,
}: IProps): React.ReactElement {
  return (
    <Box paddingLeft={1} paddingRight={1} justifyContent="space-between">
      <StatusLeft
        permissionMode={permissionMode}
        modelName={modelName}
        providerDisplayName={providerDisplayName}
        isThinking={isThinking}
        activeToolCount={activeToolCount}
        activeBackgroundTaskCount={activeBackgroundTaskCount}
        hasPendingPrompt={hasPendingPrompt}
        contextPercentage={contextPercentage}
        contextUsedTokens={contextUsedTokens}
        contextMaxTokens={contextMaxTokens}
        sessionName={sessionName}
        gitBranch={gitBranch}
        showGitBranch={showGitBranch}
        activePresetId={activePresetId}
      />
      {activeAgentLabel !== undefined && (
        <Text color="yellow" bold>
          [{activeAgentLabel}]
        </Text>
      )}
    </Box>
  );
}
