import { useState } from 'react';
import {
  Coins, MessageSquare, Database, Zap, Loader2,
  Brain, ShieldCheck, FileEdit, ChevronDown
} from 'lucide-react';

// Permission mode definitions with display info
const PERMISSION_MODES = [
  { value: 'default', label: 'Default', icon: ShieldCheck, color: 'text-blue-400', description: 'Prompts for dangerous tools' },
  { value: 'acceptEdits', label: 'Accept Edits', icon: FileEdit, color: 'text-green-400', description: 'Auto-accept file edits' },
  { value: 'plan', label: 'Plan', icon: Brain, color: 'text-purple-400', description: 'Planning mode only' },
  { value: 'bypassPermissions', label: 'Bypass', icon: Zap, color: 'text-orange-400', description: 'Allow all tools (careful!)' },
];

export function StatusBar({ sessionStats, isProcessing, connected, permissionMode = 'default', controlInitialized, onChangeMode }) {
  const [showModeMenu, setShowModeMenu] = useState(false);

  const {
    totalCost = 0,
    inputTokens = 0,
    outputTokens = 0,
    cacheReadTokens = 0,
    cacheCreationTokens = 0,
    numTurns = 0,
    contextWindow = 200000,
    contextLeftPercent = null, // From Claude's "Context left until auto-compact: X%" message
    isCompacting = false,
  } = sessionStats || {};

  // Get current mode info
  const currentMode = PERMISSION_MODES.find(m => m.value === permissionMode) || PERMISSION_MODES[0];
  const ModeIcon = currentMode.icon;

  // Context remaining: Use Claude's reported value if available, otherwise don't show
  // Claude only reports this when context is getting low (< ~15%)
  const contextRemaining = contextLeftPercent;

  // Format cost
  const formatCost = (cost) => {
    if (cost < 0.01) return `$${cost.toFixed(4)}`;
    if (cost < 1) return `$${cost.toFixed(3)}`;
    return `$${cost.toFixed(2)}`;
  };

  // Format token count
  const formatTokens = (tokens) => {
    if (tokens >= 1000000) return `${(tokens / 1000000).toFixed(1)}M`;
    if (tokens >= 1000) return `${(tokens / 1000).toFixed(1)}k`;
    return tokens.toString();
  };

  return (
    <div className="bg-dark-900 border-t border-dark-700 px-4 py-2">
      <div className="flex items-center justify-between text-xs">
        {/* Left side: Stats */}
        <div className="flex items-center gap-4">
          {/* Connection status */}
          <div className="flex items-center gap-1.5">
            <div className={`w-2 h-2 rounded-full ${connected ? 'bg-green-500' : 'bg-red-500'}`} />
            <span className="text-dark-400">{connected ? 'Connected' : 'Disconnected'}</span>
          </div>

          {/* Processing indicator */}
          {isProcessing && (
            <div className="flex items-center gap-1.5 text-orange-400">
              <Loader2 className="w-3 h-3 animate-spin" />
              <span>Processing...</span>
            </div>
          )}

          {/* Compacting indicator */}
          {isCompacting && (
            <div className="flex items-center gap-1.5 text-purple-400">
              <Zap className="w-3 h-3 animate-pulse" />
              <span>Compacting context...</span>
            </div>
          )}

          {/* Turns */}
          {numTurns > 0 && (
            <div className="flex items-center gap-1.5 text-dark-400">
              <MessageSquare className="w-3 h-3" />
              <span>{numTurns} turns</span>
            </div>
          )}

          {/* Cost */}
          {totalCost > 0 && (
            <div className="flex items-center gap-1.5 text-dark-400">
              <Coins className="w-3 h-3" />
              <span>{formatCost(totalCost)}</span>
            </div>
          )}

          {/* Permission Mode Toggle - show always for debugging, just disabled when not initialized */}
          {(
            <div className="relative">
              <button
                onClick={() => setShowModeMenu(!showModeMenu)}
                className={`flex items-center gap-1.5 px-2 py-0.5 rounded ${currentMode.color} hover:bg-dark-800 transition-colors`}
                title={currentMode.description}
              >
                <ModeIcon className="w-3 h-3" />
                <span>{currentMode.label}</span>
                <ChevronDown className={`w-3 h-3 transition-transform ${showModeMenu ? 'rotate-180' : ''}`} />
              </button>

              {showModeMenu && (
                <div className="absolute bottom-full left-0 mb-1 bg-dark-800 border border-dark-600 rounded shadow-lg py-1 min-w-[160px] z-50">
                  {PERMISSION_MODES.map((mode) => {
                    const Icon = mode.icon;
                    const isActive = mode.value === permissionMode;
                    return (
                      <button
                        key={mode.value}
                        onClick={() => {
                          onChangeMode(mode.value);
                          setShowModeMenu(false);
                        }}
                        className={`w-full flex items-center gap-2 px-3 py-1.5 text-left hover:bg-dark-700 transition-colors ${
                          isActive ? mode.color : 'text-dark-300'
                        }`}
                      >
                        <Icon className="w-3.5 h-3.5" />
                        <div>
                          <div className="text-xs font-medium">{mode.label}</div>
                          <div className="text-[10px] text-dark-500">{mode.description}</div>
                        </div>
                      </button>
                    );
                  })}
                </div>
              )}
            </div>
          )}
        </div>

        {/* Right side: Token usage */}
        <div className="flex items-center gap-4">
          {/* Context status - only shown when Claude reports it (context getting low) */}
          {contextRemaining !== null && (
            <div className="flex items-center gap-2">
              <span className="text-dark-500">Context:</span>
              <span className={`${
                contextRemaining <= 5 ? 'text-red-400 font-medium animate-pulse' :
                contextRemaining <= 15 ? 'text-red-400' :
                contextRemaining <= 30 ? 'text-yellow-400' : 'text-green-400'
              }`}>
                {contextRemaining}% left
              </span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
