/**
 * LLMToolsPanel Component
 * Tools integration panel with enable/disable toggles and execution history
 * OQI-007: LLM Strategy Agent - SUBTASK-008
 */

import React, { useState, useMemo } from 'react';
import {
  WrenchScrewdriverIcon,
  ChartBarIcon,
  CurrencyDollarIcon,
  MagnifyingGlassIcon,
  CalculatorIcon,
  NewspaperIcon,
  ClockIcon,
  CheckIcon,
  XMarkIcon,
  ExclamationTriangleIcon,
  ChevronDownIcon,
  ChevronUpIcon,
  PlayIcon,
  ArrowPathIcon,
  InformationCircleIcon,
  Cog6ToothIcon,
} from '@heroicons/react/24/outline';

// ============================================================================
// Types
// ============================================================================

export interface LLMTool {
  id: string;
  name: string;
  description: string;
  category: 'market_data' | 'analysis' | 'trading' | 'research' | 'utility';
  enabled: boolean;
  parameters?: ToolParameter[];
  usageCount: number;
  avgDuration: number;
  lastUsed?: string;
  requiredPermissions?: string[];
}

export interface ToolParameter {
  name: string;
  type: 'string' | 'number' | 'boolean' | 'select';
  required: boolean;
  default?: string | number | boolean;
  options?: string[];
  description?: string;
}

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

interface LLMToolsPanelProps {
  tools: LLMTool[];
  executionHistory: ToolExecution[];
  onToggleTool: (toolId: string, enabled: boolean) => void;
  onConfigureTool?: (toolId: string) => void;
  onRetryExecution?: (executionId: string) => void;
  onClearHistory?: () => void;
  isLoading?: boolean;
}

// ============================================================================
// Constants
// ============================================================================

const CATEGORY_INFO: Record<string, { label: string; color: string; icon: React.ElementType }> = {
  market_data: { label: 'Market Data', color: 'text-blue-500 bg-blue-500/10', icon: CurrencyDollarIcon },
  analysis: { label: 'Analysis', color: 'text-purple-500 bg-purple-500/10', icon: ChartBarIcon },
  trading: { label: 'Trading', color: 'text-emerald-500 bg-emerald-500/10', icon: CalculatorIcon },
  research: { label: 'Research', color: 'text-orange-500 bg-orange-500/10', icon: NewspaperIcon },
  utility: { label: 'Utility', color: 'text-gray-500 bg-gray-500/10', icon: WrenchScrewdriverIcon },
};

const STATUS_STYLES: Record<string, { color: string; icon: React.ElementType }> = {
  pending: { color: 'text-gray-400 bg-gray-500/10', icon: ClockIcon },
  running: { color: 'text-blue-400 bg-blue-500/10', icon: ArrowPathIcon },
  success: { color: 'text-emerald-400 bg-emerald-500/10', icon: CheckIcon },
  error: { color: 'text-red-400 bg-red-500/10', icon: XMarkIcon },
};

// ============================================================================
// Sub-Components
// ============================================================================

interface ToolCardProps {
  tool: LLMTool;
  onToggle: (enabled: boolean) => void;
  onConfigure?: () => void;
}

const ToolCard: React.FC<ToolCardProps> = ({ tool, onToggle, onConfigure }) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const category = CATEGORY_INFO[tool.category];
  const CategoryIcon = category.icon;

  const formatLastUsed = (dateStr?: string) => {
    if (!dateStr) return 'Never';
    const date = new Date(dateStr);
    const now = new Date();
    const diff = now.getTime() - date.getTime();

    if (diff < 60000) return 'Just now';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
    return date.toLocaleDateString();
  };

  return (
    <div className={`rounded-lg border transition-all ${
      tool.enabled
        ? 'border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800'
        : 'border-gray-100 dark:border-gray-800 bg-gray-50 dark:bg-gray-900 opacity-75'
    }`}>
      <div className="p-3">
        <div className="flex items-start gap-3">
          {/* Icon */}
          <div className={`p-2 rounded-lg ${category.color}`}>
            <CategoryIcon className="w-4 h-4" />
          </div>

          {/* Content */}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <h4 className="font-medium text-gray-900 dark:text-white text-sm">{tool.name}</h4>
              <span className={`px-1.5 py-0.5 text-xs rounded ${category.color}`}>
                {category.label}
              </span>
            </div>
            <p className="text-xs text-gray-500 mt-0.5 line-clamp-2">{tool.description}</p>

            {/* Stats */}
            <div className="flex items-center gap-4 mt-2 text-xs text-gray-400">
              <span title="Usage count">{tool.usageCount} uses</span>
              <span title="Average duration">{tool.avgDuration}ms avg</span>
              <span title="Last used">{formatLastUsed(tool.lastUsed)}</span>
            </div>
          </div>

          {/* Actions */}
          <div className="flex items-center gap-2">
            {onConfigure && tool.parameters && tool.parameters.length > 0 && (
              <button
                onClick={onConfigure}
                className="p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
                title="Configure"
              >
                <Cog6ToothIcon className="w-4 h-4" />
              </button>
            )}
            <button
              onClick={() => setIsExpanded(!isExpanded)}
              className="p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
            >
              {isExpanded ? <ChevronUpIcon className="w-4 h-4" /> : <ChevronDownIcon className="w-4 h-4" />}
            </button>
            {/* Toggle */}
            <button
              onClick={() => onToggle(!tool.enabled)}
              className={`relative w-10 h-6 rounded-full transition-colors ${
                tool.enabled ? 'bg-primary-500' : 'bg-gray-300 dark:bg-gray-600'
              }`}
            >
              <span
                className={`absolute top-1 w-4 h-4 bg-white rounded-full transition-transform ${
                  tool.enabled ? 'translate-x-5' : 'translate-x-1'
                }`}
              />
            </button>
          </div>
        </div>

        {/* Expanded Details */}
        {isExpanded && (
          <div className="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">
            {tool.parameters && tool.parameters.length > 0 && (
              <div className="space-y-2">
                <h5 className="text-xs font-medium text-gray-500 uppercase">Parameters</h5>
                {tool.parameters.map((param) => (
                  <div key={param.name} className="flex items-center justify-between text-xs">
                    <div className="flex items-center gap-2">
                      <span className="text-gray-700 dark:text-gray-300">{param.name}</span>
                      {param.required && <span className="text-red-400">*</span>}
                    </div>
                    <span className="text-gray-400">{param.type}</span>
                  </div>
                ))}
              </div>
            )}
            {tool.requiredPermissions && tool.requiredPermissions.length > 0 && (
              <div className="mt-2">
                <h5 className="text-xs font-medium text-gray-500 uppercase mb-1">Required Permissions</h5>
                <div className="flex flex-wrap gap-1">
                  {tool.requiredPermissions.map((perm) => (
                    <span
                      key={perm}
                      className="px-1.5 py-0.5 bg-yellow-100 dark:bg-yellow-900/30 text-yellow-600 dark:text-yellow-400 text-xs rounded"
                    >
                      {perm}
                    </span>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

interface ExecutionHistoryItemProps {
  execution: ToolExecution;
  onRetry?: () => void;
}

const ExecutionHistoryItem: React.FC<ExecutionHistoryItemProps> = ({ execution, onRetry }) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const status = STATUS_STYLES[execution.status];
  const StatusIcon = status.icon;

  return (
    <div className="p-3 hover:bg-gray-50 dark:hover:bg-gray-800 rounded-lg">
      <div className="flex items-start gap-3">
        <div className={`p-1.5 rounded-lg ${status.color}`}>
          <StatusIcon className={`w-4 h-4 ${execution.status === 'running' ? 'animate-spin' : ''}`} />
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <span className="font-medium text-gray-900 dark:text-white text-sm">{execution.toolName}</span>
            <span className={`px-1.5 py-0.5 text-xs rounded ${status.color}`}>
              {execution.status}
            </span>
          </div>

          <div className="flex items-center gap-3 mt-1 text-xs text-gray-400">
            <span>{new Date(execution.startTime).toLocaleTimeString()}</span>
            {execution.duration && <span>{execution.duration}ms</span>}
          </div>

          {execution.error && (
            <div className="mt-2 p-2 bg-red-50 dark:bg-red-900/20 rounded text-xs text-red-600 dark:text-red-400 flex items-start gap-2">
              <ExclamationTriangleIcon className="w-4 h-4 flex-shrink-0" />
              <span>{execution.error}</span>
            </div>
          )}
        </div>

        <div className="flex items-center gap-1">
          {execution.status === 'error' && onRetry && (
            <button
              onClick={onRetry}
              className="p-1.5 text-gray-400 hover:text-primary-500 hover:bg-primary-50 dark:hover:bg-primary-900/20 rounded-lg"
              title="Retry"
            >
              <ArrowPathIcon className="w-4 h-4" />
            </button>
          )}
          <button
            onClick={() => setIsExpanded(!isExpanded)}
            className="p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          >
            {isExpanded ? <ChevronUpIcon className="w-4 h-4" /> : <ChevronDownIcon className="w-4 h-4" />}
          </button>
        </div>
      </div>

      {isExpanded && (
        <div className="mt-3 space-y-2">
          <div>
            <h5 className="text-xs font-medium text-gray-500 uppercase mb-1">Arguments</h5>
            <pre className="p-2 bg-gray-100 dark:bg-gray-900 rounded text-xs text-gray-600 dark:text-gray-400 overflow-x-auto">
              {JSON.stringify(execution.arguments, null, 2)}
            </pre>
          </div>
          {execution.result !== undefined && execution.result !== null && (
            <div>
              <h5 className="text-xs font-medium text-gray-500 uppercase mb-1">Result</h5>
              <pre className="p-2 bg-gray-100 dark:bg-gray-900 rounded text-xs text-gray-600 dark:text-gray-400 overflow-x-auto max-h-32">
                {JSON.stringify(execution.result, null, 2)}
              </pre>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// ============================================================================
// Main Component
// ============================================================================

export const LLMToolsPanel: React.FC<LLMToolsPanelProps> = ({
  tools,
  executionHistory,
  onToggleTool,
  onConfigureTool,
  onRetryExecution,
  onClearHistory,
  isLoading = false,
}) => {
  const [activeTab, setActiveTab] = useState<'tools' | 'history'>('tools');
  const [searchQuery, setSearchQuery] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<string>('all');

  const filteredTools = useMemo(() => {
    let filtered = tools;

    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter((t) =>
        t.name.toLowerCase().includes(query) ||
        t.description.toLowerCase().includes(query)
      );
    }

    if (categoryFilter !== 'all') {
      filtered = filtered.filter((t) => t.category === categoryFilter);
    }

    return filtered;
  }, [tools, searchQuery, categoryFilter]);

  const enabledCount = tools.filter((t) => t.enabled).length;
  const categories = [...new Set(tools.map((t) => t.category))];

  const recentExecutions = executionHistory.slice(0, 20);
  const successRate = executionHistory.length > 0
    ? (executionHistory.filter((e) => e.status === 'success').length / executionHistory.length * 100).toFixed(0)
    : 0;

  return (
    <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
      {/* Header */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2">
            <WrenchScrewdriverIcon className="w-5 h-5 text-primary-500" />
            <h3 className="font-semibold text-gray-900 dark:text-white">LLM Tools</h3>
          </div>
          <div className="text-sm text-gray-500">
            {enabledCount}/{tools.length} enabled
          </div>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-3 gap-3">
          <div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg text-center">
            <div className="text-xl font-bold text-gray-900 dark:text-white">{tools.length}</div>
            <div className="text-xs text-gray-500">Total Tools</div>
          </div>
          <div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg text-center">
            <div className="text-xl font-bold text-emerald-500">{enabledCount}</div>
            <div className="text-xs text-gray-500">Enabled</div>
          </div>
          <div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg text-center">
            <div className="text-xl font-bold text-blue-500">{successRate}%</div>
            <div className="text-xs text-gray-500">Success Rate</div>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex border-b border-gray-200 dark:border-gray-700">
        <button
          onClick={() => setActiveTab('tools')}
          className={`flex-1 flex items-center justify-center gap-2 py-3 text-sm font-medium border-b-2 transition-colors ${
            activeTab === 'tools'
              ? 'border-primary-500 text-primary-500'
              : 'border-transparent text-gray-500'
          }`}
        >
          <Cog6ToothIcon className="w-4 h-4" />
          Available Tools
        </button>
        <button
          onClick={() => setActiveTab('history')}
          className={`flex-1 flex items-center justify-center gap-2 py-3 text-sm font-medium border-b-2 transition-colors ${
            activeTab === 'history'
              ? 'border-primary-500 text-primary-500'
              : 'border-transparent text-gray-500'
          }`}
        >
          <ClockIcon className="w-4 h-4" />
          Execution History ({executionHistory.length})
        </button>
      </div>

      {/* Tools Tab */}
      {activeTab === 'tools' && (
        <>
          {/* Filters */}
          <div className="p-3 border-b border-gray-200 dark:border-gray-700 flex items-center gap-3">
            <div className="flex-1 relative">
              <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search tools..."
                className="w-full pl-9 pr-3 py-2 text-sm bg-gray-100 dark:bg-gray-800 border-0 rounded-lg focus:ring-2 focus:ring-primary-500"
              />
            </div>
            <select
              value={categoryFilter}
              onChange={(e) => setCategoryFilter(e.target.value)}
              className="px-3 py-2 text-sm bg-gray-100 dark:bg-gray-800 border-0 rounded-lg focus:ring-2 focus:ring-primary-500"
            >
              <option value="all">All Categories</option>
              {categories.map((cat) => (
                <option key={cat} value={cat}>
                  {CATEGORY_INFO[cat]?.label || cat}
                </option>
              ))}
            </select>
          </div>

          {/* Tools List */}
          <div className="max-h-96 overflow-y-auto p-3 space-y-2">
            {filteredTools.length === 0 ? (
              <div className="p-8 text-center">
                <WrenchScrewdriverIcon className="w-12 h-12 mx-auto text-gray-300 dark:text-gray-600 mb-3" />
                <p className="text-gray-500 text-sm">No tools found</p>
              </div>
            ) : (
              filteredTools.map((tool) => (
                <ToolCard
                  key={tool.id}
                  tool={tool}
                  onToggle={(enabled) => onToggleTool(tool.id, enabled)}
                  onConfigure={onConfigureTool ? () => onConfigureTool(tool.id) : undefined}
                />
              ))
            )}
          </div>
        </>
      )}

      {/* History Tab */}
      {activeTab === 'history' && (
        <>
          {/* Clear History */}
          {executionHistory.length > 0 && onClearHistory && (
            <div className="p-3 border-b border-gray-200 dark:border-gray-700 flex justify-end">
              <button
                onClick={onClearHistory}
                className="text-xs text-gray-500 hover:text-red-500 transition-colors"
              >
                Clear History
              </button>
            </div>
          )}

          {/* Execution List */}
          <div className="max-h-96 overflow-y-auto">
            {recentExecutions.length === 0 ? (
              <div className="p-8 text-center">
                <ClockIcon className="w-12 h-12 mx-auto text-gray-300 dark:text-gray-600 mb-3" />
                <p className="text-gray-500 text-sm">No execution history</p>
                <p className="text-gray-400 text-xs mt-1">Tool executions will appear here</p>
              </div>
            ) : (
              <div className="divide-y divide-gray-100 dark:divide-gray-800">
                {recentExecutions.map((execution) => (
                  <ExecutionHistoryItem
                    key={execution.id}
                    execution={execution}
                    onRetry={onRetryExecution ? () => onRetryExecution(execution.id) : undefined}
                  />
                ))}
              </div>
            )}
          </div>
        </>
      )}

      {/* Info Footer */}
      <div className="p-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
        <div className="flex items-start gap-2 text-xs text-gray-500">
          <InformationCircleIcon className="w-4 h-4 flex-shrink-0 mt-0.5" />
          <p>
            Tools extend AI capabilities. Enable tools to allow the assistant to access market data,
            analyze charts, execute trades, and more. Some tools may require additional permissions.
          </p>
        </div>
      </div>
    </div>
  );
};

export default LLMToolsPanel;
