/**
 * TokenUsageDisplay Component
 * Shows token consumption and context window usage
 * OQI-007: LLM Strategy Agent
 */

import React, { useMemo } from 'react';
import {
  Coins,
  TrendingUp,
  TrendingDown,
  AlertTriangle,
  Info,
  BarChart3,
  Clock,
  DollarSign,
  Zap,
  ChevronDown,
  ChevronUp,
} from 'lucide-react';

export interface TokenUsage {
  inputTokens: number;
  outputTokens: number;
  totalTokens: number;
  contextWindowSize: number;
  contextUsedTokens: number;
}

export interface TokenCosts {
  inputCostPer1k: number;
  outputCostPer1k: number;
  currency?: string;
}

export interface SessionTokenStats {
  totalInputTokens: number;
  totalOutputTokens: number;
  totalCost: number;
  messageCount: number;
  averageTokensPerMessage: number;
  sessionDuration?: number; // minutes
}

export interface TokenUsageDisplayProps {
  usage: TokenUsage;
  costs?: TokenCosts;
  sessionStats?: SessionTokenStats;
  modelName?: string;
  variant?: 'compact' | 'detailed' | 'inline';
  showCosts?: boolean;
  showContextWarning?: boolean;
  onViewDetails?: () => void;
}

const TokenUsageDisplay: React.FC<TokenUsageDisplayProps> = ({
  usage,
  costs,
  sessionStats,
  modelName = 'Claude 3.5',
  variant = 'compact',
  showCosts = true,
  showContextWarning = true,
  onViewDetails,
}) => {
  const [isExpanded, setIsExpanded] = React.useState(false);

  const contextPercentage = useMemo(
    () => Math.round((usage.contextUsedTokens / usage.contextWindowSize) * 100),
    [usage.contextUsedTokens, usage.contextWindowSize]
  );

  const contextStatus = useMemo(() => {
    if (contextPercentage >= 90) return { color: 'red', label: 'Critical', warning: true };
    if (contextPercentage >= 75) return { color: 'orange', label: 'High', warning: true };
    if (contextPercentage >= 50) return { color: 'yellow', label: 'Moderate', warning: false };
    return { color: 'green', label: 'Good', warning: false };
  }, [contextPercentage]);

  const estimatedCost = useMemo(() => {
    if (!costs) return null;
    const inputCost = (usage.inputTokens / 1000) * costs.inputCostPer1k;
    const outputCost = (usage.outputTokens / 1000) * costs.outputCostPer1k;
    return {
      input: inputCost,
      output: outputCost,
      total: inputCost + outputCost,
    };
  }, [usage, costs]);

  const formatTokens = (tokens: number): string => {
    if (tokens >= 1000000) return `${(tokens / 1000000).toFixed(1)}M`;
    if (tokens >= 1000) return `${(tokens / 1000).toFixed(1)}K`;
    return tokens.toString();
  };

  const formatCost = (cost: number, currency = 'USD'): string => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency,
      minimumFractionDigits: 4,
      maximumFractionDigits: 4,
    }).format(cost);
  };

  const getContextColor = (color: string) => {
    switch (color) {
      case 'red':
        return 'text-red-400 bg-red-500/20';
      case 'orange':
        return 'text-orange-400 bg-orange-500/20';
      case 'yellow':
        return 'text-yellow-400 bg-yellow-500/20';
      case 'green':
        return 'text-green-400 bg-green-500/20';
      default:
        return 'text-gray-400 bg-gray-500/20';
    }
  };

  const getBarColor = (color: string) => {
    switch (color) {
      case 'red':
        return 'bg-red-500';
      case 'orange':
        return 'bg-orange-500';
      case 'yellow':
        return 'bg-yellow-500';
      case 'green':
        return 'bg-green-500';
      default:
        return 'bg-gray-500';
    }
  };

  // Inline variant (minimal, for chat header)
  if (variant === 'inline') {
    return (
      <div className="flex items-center gap-3 text-sm">
        <div className="flex items-center gap-1.5 text-gray-400">
          <Coins className="w-4 h-4" />
          <span>{formatTokens(usage.totalTokens)}</span>
        </div>
        <div className={`flex items-center gap-1.5 ${getContextColor(contextStatus.color).split(' ')[0]}`}>
          <BarChart3 className="w-4 h-4" />
          <span>{contextPercentage}%</span>
        </div>
        {contextStatus.warning && (
          <AlertTriangle className="w-4 h-4 text-yellow-400" />
        )}
      </div>
    );
  }

  // Compact variant (badge-like)
  if (variant === 'compact') {
    return (
      <div className="inline-flex items-center gap-4 px-4 py-2 bg-gray-800/50 border border-gray-700 rounded-lg">
        {/* Token Count */}
        <div className="flex items-center gap-2">
          <Coins className="w-4 h-4 text-purple-400" />
          <div>
            <div className="text-sm font-medium text-white">{formatTokens(usage.totalTokens)}</div>
            <div className="text-xs text-gray-500">tokens</div>
          </div>
        </div>

        {/* Context Usage */}
        <div className="flex items-center gap-2">
          <div className={`p-1 rounded ${getContextColor(contextStatus.color)}`}>
            <BarChart3 className="w-4 h-4" />
          </div>
          <div>
            <div className={`text-sm font-medium ${getContextColor(contextStatus.color).split(' ')[0]}`}>
              {contextPercentage}%
            </div>
            <div className="text-xs text-gray-500">context</div>
          </div>
        </div>

        {/* Cost (if available) */}
        {showCosts && estimatedCost && (
          <div className="flex items-center gap-2">
            <DollarSign className="w-4 h-4 text-green-400" />
            <div>
              <div className="text-sm font-medium text-white">
                {formatCost(estimatedCost.total, costs?.currency)}
              </div>
              <div className="text-xs text-gray-500">cost</div>
            </div>
          </div>
        )}
      </div>
    );
  }

  // Detailed variant (full panel)
  return (
    <div className="p-4 bg-gray-800/50 border border-gray-700 rounded-xl">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-purple-500/20 text-purple-400 rounded-lg">
            <Coins className="w-5 h-5" />
          </div>
          <div>
            <h4 className="font-semibold text-white">Token Usage</h4>
            <p className="text-xs text-gray-500">{modelName}</p>
          </div>
        </div>
        {onViewDetails && (
          <button
            onClick={() => setIsExpanded(!isExpanded)}
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
          >
            {isExpanded ? <ChevronUp className="w-5 h-5" /> : <ChevronDown className="w-5 h-5" />}
          </button>
        )}
      </div>

      {/* Context Window Progress */}
      <div className="mb-4">
        <div className="flex items-center justify-between mb-2">
          <span className="text-sm text-gray-400">Context Window</span>
          <div className="flex items-center gap-2">
            <span className={`text-sm font-medium ${getContextColor(contextStatus.color).split(' ')[0]}`}>
              {contextPercentage}%
            </span>
            <span className={`text-xs px-1.5 py-0.5 rounded ${getContextColor(contextStatus.color)}`}>
              {contextStatus.label}
            </span>
          </div>
        </div>
        <div className="h-2 bg-gray-700 rounded-full overflow-hidden">
          <div
            className={`h-full transition-all ${getBarColor(contextStatus.color)}`}
            style={{ width: `${contextPercentage}%` }}
          />
        </div>
        <div className="flex items-center justify-between mt-1 text-xs text-gray-500">
          <span>{formatTokens(usage.contextUsedTokens)} used</span>
          <span>{formatTokens(usage.contextWindowSize)} max</span>
        </div>
      </div>

      {/* Context Warning */}
      {showContextWarning && contextStatus.warning && (
        <div className={`mb-4 p-3 rounded-lg ${getContextColor(contextStatus.color)} border border-${contextStatus.color}-500/30`}>
          <div className="flex items-start gap-2">
            <AlertTriangle className="w-4 h-4 flex-shrink-0 mt-0.5" />
            <div className="text-sm">
              {contextPercentage >= 90
                ? 'Context window nearly full. Older messages may be truncated.'
                : 'Context usage is high. Consider starting a new conversation soon.'}
            </div>
          </div>
        </div>
      )}

      {/* Token Breakdown */}
      <div className="grid grid-cols-3 gap-3 mb-4">
        <div className="p-3 bg-gray-900/50 rounded-lg">
          <div className="flex items-center gap-2 mb-1">
            <TrendingUp className="w-4 h-4 text-blue-400" />
            <span className="text-xs text-gray-400">Input</span>
          </div>
          <div className="text-lg font-bold text-white">{formatTokens(usage.inputTokens)}</div>
        </div>
        <div className="p-3 bg-gray-900/50 rounded-lg">
          <div className="flex items-center gap-2 mb-1">
            <TrendingDown className="w-4 h-4 text-green-400" />
            <span className="text-xs text-gray-400">Output</span>
          </div>
          <div className="text-lg font-bold text-white">{formatTokens(usage.outputTokens)}</div>
        </div>
        <div className="p-3 bg-gray-900/50 rounded-lg">
          <div className="flex items-center gap-2 mb-1">
            <Zap className="w-4 h-4 text-purple-400" />
            <span className="text-xs text-gray-400">Total</span>
          </div>
          <div className="text-lg font-bold text-white">{formatTokens(usage.totalTokens)}</div>
        </div>
      </div>

      {/* Expanded Session Stats */}
      {isExpanded && sessionStats && (
        <div className="pt-4 border-t border-gray-700">
          <h5 className="text-sm font-medium text-gray-400 mb-3">Session Statistics</h5>
          <div className="grid grid-cols-2 gap-3">
            <div className="p-3 bg-gray-900/50 rounded-lg">
              <div className="text-xs text-gray-500 mb-1">Messages</div>
              <div className="text-lg font-bold text-white">{sessionStats.messageCount}</div>
            </div>
            <div className="p-3 bg-gray-900/50 rounded-lg">
              <div className="text-xs text-gray-500 mb-1">Avg Tokens/Msg</div>
              <div className="text-lg font-bold text-white">{sessionStats.averageTokensPerMessage}</div>
            </div>
            {sessionStats.sessionDuration && (
              <div className="p-3 bg-gray-900/50 rounded-lg">
                <div className="text-xs text-gray-500 mb-1">Duration</div>
                <div className="text-lg font-bold text-white">{sessionStats.sessionDuration}m</div>
              </div>
            )}
            {showCosts && sessionStats.totalCost > 0 && (
              <div className="p-3 bg-gray-900/50 rounded-lg">
                <div className="text-xs text-gray-500 mb-1">Session Cost</div>
                <div className="text-lg font-bold text-green-400">
                  {formatCost(sessionStats.totalCost, costs?.currency)}
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Cost Breakdown */}
      {showCosts && estimatedCost && (
        <div className="pt-4 border-t border-gray-700">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2 text-gray-400">
              <DollarSign className="w-4 h-4" />
              <span className="text-sm">Estimated Cost</span>
            </div>
            <div className="text-right">
              <div className="text-lg font-bold text-green-400">
                {formatCost(estimatedCost.total, costs?.currency)}
              </div>
              <div className="text-xs text-gray-500">
                In: {formatCost(estimatedCost.input)} | Out: {formatCost(estimatedCost.output)}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default TokenUsageDisplay;
