/**
 * ToolCallCard Component
 * Displays tool execution results from LLM agent
 */

import React, { useState } from 'react';
import {
  Wrench,
  Check,
  X,
  Loader2,
  Copy,
  ChevronDown,
  ChevronUp,
  TrendingUp,
  TrendingDown,
  DollarSign,
  BarChart3,
  Search,
  AlertTriangle,
  Clock,
} from 'lucide-react';

export interface ToolCall {
  id: string;
  name: string;
  arguments: Record<string, unknown>;
  result?: unknown;
  status: 'pending' | 'running' | 'success' | 'error';
  error?: string;
  duration?: number;
}

interface ToolCallCardProps {
  toolCall: ToolCall;
  compact?: boolean;
}

const TOOL_ICONS: Record<string, React.ReactNode> = {
  get_price: <DollarSign className="w-4 h-4" />,
  get_quote: <DollarSign className="w-4 h-4" />,
  analyze_symbol: <BarChart3 className="w-4 h-4" />,
  get_signal: <TrendingUp className="w-4 h-4" />,
  create_order: <TrendingUp className="w-4 h-4" />,
  close_position: <TrendingDown className="w-4 h-4" />,
  get_portfolio: <BarChart3 className="w-4 h-4" />,
  search_symbols: <Search className="w-4 h-4" />,
  backtest: <Clock className="w-4 h-4" />,
};

const TOOL_LABELS: Record<string, string> = {
  get_price: 'Get Price',
  get_quote: 'Get Quote',
  analyze_symbol: 'Analyze Symbol',
  get_signal: 'Get Signal',
  create_order: 'Create Order',
  close_position: 'Close Position',
  get_portfolio: 'Get Portfolio',
  search_symbols: 'Search Symbols',
  backtest: 'Backtest Strategy',
};

const ToolCallCard: React.FC<ToolCallCardProps> = ({
  toolCall,
  compact = false,
}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const [copied, setCopied] = useState(false);

  const icon = TOOL_ICONS[toolCall.name] || <Wrench className="w-4 h-4" />;
  const label = TOOL_LABELS[toolCall.name] || toolCall.name;

  const statusColors = {
    pending: 'bg-gray-500/20 text-gray-400 border-gray-500/30',
    running: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
    success: 'bg-green-500/20 text-green-400 border-green-500/30',
    error: 'bg-red-500/20 text-red-400 border-red-500/30',
  };

  const statusIcons = {
    pending: <Clock className="w-3 h-3" />,
    running: <Loader2 className="w-3 h-3 animate-spin" />,
    success: <Check className="w-3 h-3" />,
    error: <X className="w-3 h-3" />,
  };

  const handleCopy = async () => {
    const content = JSON.stringify(toolCall.result, null, 2);
    await navigator.clipboard.writeText(content);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const formatResult = (result: unknown): string => {
    if (result === null || result === undefined) return 'No result';
    if (typeof result === 'string') return result;
    if (typeof result === 'number') return result.toLocaleString();
    return JSON.stringify(result, null, 2);
  };

  const renderResultPreview = () => {
    const result = toolCall.result;
    if (!result) return null;

    // Handle price result
    if (typeof result === 'object' && result !== null) {
      const r = result as Record<string, unknown>;

      if ('price' in r || 'bid' in r || 'ask' in r) {
        return (
          <div className="flex items-center gap-4 text-sm">
            {Boolean(r.symbol) && (
              <span className="font-medium text-white">{String(r.symbol)}</span>
            )}
            {Boolean(r.price) && (
              <span className="font-mono text-green-400">{String(Number(r.price).toFixed(5))}</span>
            )}
            {Boolean(r.bid) && Boolean(r.ask) && (
              <span className="text-gray-400">
                <span className="text-red-400">{String(Number(r.bid).toFixed(5))}</span>
                {' / '}
                <span className="text-green-400">{String(Number(r.ask).toFixed(5))}</span>
              </span>
            )}
            {r.change !== undefined && (
              <span className={Number(r.change) >= 0 ? 'text-green-400' : 'text-red-400'}>
                {Number(r.change) >= 0 ? '+' : ''}{String(Number(r.change).toFixed(2))}%
              </span>
            )}
          </div>
        );
      }

      // Handle signal result
      if ('signal' in r || 'direction' in r) {
        const direction = r.direction || r.signal;
        return (
          <div className="flex items-center gap-3 text-sm">
            <span className={`px-2 py-0.5 rounded font-medium ${
              direction === 'BUY' || direction === 'LONG'
                ? 'bg-green-500/20 text-green-400'
                : direction === 'SELL' || direction === 'SHORT'
                ? 'bg-red-500/20 text-red-400'
                : 'bg-gray-500/20 text-gray-400'
            }`}>
              {String(direction)}
            </span>
            {Boolean(r.confidence) && (
              <span className="text-gray-400">
                Confidence: <span className="text-white">{String(Number(r.confidence).toFixed(0))}%</span>
              </span>
            )}
            {Boolean(r.entry) && (
              <span className="text-gray-400">
                Entry: <span className="font-mono text-white">{String(Number(r.entry).toFixed(5))}</span>
              </span>
            )}
          </div>
        );
      }

      // Handle portfolio result
      if ('balance' in r || 'equity' in r) {
        return (
          <div className="flex items-center gap-4 text-sm">
            {Boolean(r.balance) && (
              <span className="text-gray-400">
                Balance: <span className="text-white font-medium">${String(Number(r.balance).toLocaleString())}</span>
              </span>
            )}
            {Boolean(r.equity) && (
              <span className="text-gray-400">
                Equity: <span className={Number(r.equity) >= Number(r.balance || 0) ? 'text-green-400' : 'text-red-400'}>
                  ${String(Number(r.equity).toLocaleString())}
                </span>
              </span>
            )}
            {r.positions !== undefined && (
              <span className="text-gray-400">
                Positions: <span className="text-white">{String(r.positions)}</span>
              </span>
            )}
          </div>
        );
      }

      // Handle array results (e.g., search results)
      if (Array.isArray(result)) {
        return (
          <span className="text-sm text-gray-400">
            {result.length} result{result.length !== 1 ? 's' : ''} found
          </span>
        );
      }
    }

    // Fallback for simple results
    return (
      <span className="text-sm text-gray-300 truncate max-w-[300px]">
        {formatResult(result).substring(0, 100)}
        {formatResult(result).length > 100 ? '...' : ''}
      </span>
    );
  };

  if (compact) {
    return (
      <div className={`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${statusColors[toolCall.status]}`}>
        {icon}
        <span>{label}</span>
        {statusIcons[toolCall.status]}
      </div>
    );
  }

  return (
    <div className={`rounded-lg border ${statusColors[toolCall.status]} overflow-hidden`}>
      {/* Header */}
      <button
        onClick={() => setIsExpanded(!isExpanded)}
        className="w-full flex items-center justify-between p-3 hover:bg-white/5 transition-colors"
      >
        <div className="flex items-center gap-3">
          <div className={`p-1.5 rounded ${statusColors[toolCall.status]}`}>
            {icon}
          </div>
          <div className="text-left">
            <div className="flex items-center gap-2">
              <span className="font-medium text-white">{label}</span>
              <span className={`flex items-center gap-1 text-xs px-1.5 py-0.5 rounded ${statusColors[toolCall.status]}`}>
                {statusIcons[toolCall.status]}
                {toolCall.status}
              </span>
            </div>
            {toolCall.status === 'success' && Boolean(toolCall.result) && (
              <div className="mt-1">{renderResultPreview()}</div>
            )}
            {toolCall.status === 'error' && toolCall.error && (
              <div className="flex items-center gap-1.5 mt-1 text-sm text-red-400">
                <AlertTriangle className="w-3 h-3" />
                <span>{toolCall.error}</span>
              </div>
            )}
          </div>
        </div>
        <div className="flex items-center gap-2">
          {toolCall.duration && (
            <span className="text-xs text-gray-500">{toolCall.duration}ms</span>
          )}
          {isExpanded ? (
            <ChevronUp className="w-4 h-4 text-gray-400" />
          ) : (
            <ChevronDown className="w-4 h-4 text-gray-400" />
          )}
        </div>
      </button>

      {/* Expanded Content */}
      {isExpanded && (
        <div className="border-t border-gray-700 p-3 space-y-3">
          {/* Arguments */}
          <div>
            <div className="flex items-center justify-between mb-1">
              <span className="text-xs text-gray-500 uppercase tracking-wide">Arguments</span>
            </div>
            <pre className="p-2 bg-gray-900/50 rounded text-xs text-gray-300 overflow-x-auto">
              {JSON.stringify(toolCall.arguments, null, 2)}
            </pre>
          </div>

          {/* Result */}
          {Boolean(toolCall.result) && (
            <div>
              <div className="flex items-center justify-between mb-1">
                <span className="text-xs text-gray-500 uppercase tracking-wide">Result</span>
                <button
                  onClick={handleCopy}
                  className="flex items-center gap-1 text-xs text-gray-400 hover:text-white transition-colors"
                >
                  {copied ? (
                    <>
                      <Check className="w-3 h-3" />
                      Copied
                    </>
                  ) : (
                    <>
                      <Copy className="w-3 h-3" />
                      Copy
                    </>
                  )}
                </button>
              </div>
              <pre className="p-2 bg-gray-900/50 rounded text-xs text-gray-300 overflow-x-auto max-h-40">
                {formatResult(toolCall.result)}
              </pre>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default ToolCallCard;
