/**
 * ToolsConfigPanel Component
 * Tool configuration panel with enable/disable, parameters, and descriptions
 * OQI-007: LLM Strategy Agent - Tools Configuration UI
 */

import React, { useState, useMemo, useCallback } from 'react';
import {
  WrenchScrewdriverIcon,
  ChartBarIcon,
  CurrencyDollarIcon,
  CalculatorIcon,
  NewspaperIcon,
  ShieldCheckIcon,
  BoltIcon,
  Cog6ToothIcon,
  ChevronDownIcon,
  ChevronUpIcon,
  MagnifyingGlassIcon,
  InformationCircleIcon,
  CheckCircleIcon,
  XCircleIcon,
} from '@heroicons/react/24/outline';

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

export type ToolCategory = 'analysis' | 'trading' | 'risk' | 'data' | 'utility';

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

export interface AgentTool {
  id: string;
  name: string;
  description: string;
  category: ToolCategory;
  enabled: boolean;
  parameters: ToolParameter[];
  parameterValues: Record<string, string | number | boolean>;
  requiredPermissions?: string[];
  lastUsed?: string;
  usageCount: number;
  isCore?: boolean;
}

interface ToolsConfigPanelProps {
  tools: AgentTool[];
  onToggleTool: (toolId: string, enabled: boolean) => void;
  onUpdateToolParams: (toolId: string, params: Record<string, string | number | boolean>) => void;
  onResetTool?: (toolId: string) => void;
  onResetAllTools?: () => void;
  isLoading?: boolean;
}

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

const CATEGORY_INFO: Record<ToolCategory, { label: string; icon: React.ElementType; color: string }> = {
  analysis: { label: 'Analisis', icon: ChartBarIcon, color: 'text-blue-500 bg-blue-500/10' },
  trading: { label: 'Trading', icon: BoltIcon, color: 'text-emerald-500 bg-emerald-500/10' },
  risk: { label: 'Riesgo', icon: ShieldCheckIcon, color: 'text-amber-500 bg-amber-500/10' },
  data: { label: 'Datos', icon: CurrencyDollarIcon, color: 'text-purple-500 bg-purple-500/10' },
  utility: { label: 'Utilidades', icon: WrenchScrewdriverIcon, color: 'text-gray-500 bg-gray-500/10' },
};

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

interface ParameterFieldProps {
  param: ToolParameter;
  value: string | number | boolean;
  onChange: (value: string | number | boolean) => void;
  disabled?: boolean;
}

const ParameterField: React.FC<ParameterFieldProps> = ({ param, value, onChange, disabled }) => {
  const baseClasses = "w-full px-3 py-2 text-sm bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg disabled:opacity-50";

  switch (param.type) {
    case 'boolean':
      return (
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm font-medium text-gray-700 dark:text-gray-300">{param.label}</p>
            {param.description && <p className="text-xs text-gray-500">{param.description}</p>}
          </div>
          <button
            onClick={() => onChange(!value)}
            disabled={disabled}
            className={`relative w-11 h-6 rounded-full transition-colors disabled:opacity-50 ${
              value ? 'bg-primary-500' : 'bg-gray-300 dark:bg-gray-600'
            }`}
          >
            <div className={`absolute top-1 w-4 h-4 bg-white rounded-full transition-transform ${
              value ? 'translate-x-6' : 'translate-x-1'
            }`} />
          </button>
        </div>
      );

    case 'select':
      return (
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {param.label}
          </label>
          <select
            value={String(value)}
            onChange={(e) => onChange(e.target.value)}
            disabled={disabled}
            className={baseClasses}
          >
            {param.options?.map((opt) => (
              <option key={opt.value} value={opt.value}>{opt.label}</option>
            ))}
          </select>
          {param.description && <p className="text-xs text-gray-500 mt-1">{param.description}</p>}
        </div>
      );

    case 'number':
      return (
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {param.label}
          </label>
          <input
            type="number"
            value={Number(value)}
            onChange={(e) => onChange(parseFloat(e.target.value) || 0)}
            min={param.min}
            max={param.max}
            disabled={disabled}
            className={baseClasses}
          />
          {param.description && <p className="text-xs text-gray-500 mt-1">{param.description}</p>}
        </div>
      );

    default:
      return (
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {param.label}
          </label>
          <input
            type="text"
            value={String(value)}
            onChange={(e) => onChange(e.target.value)}
            disabled={disabled}
            className={baseClasses}
          />
          {param.description && <p className="text-xs text-gray-500 mt-1">{param.description}</p>}
        </div>
      );
  }
};

interface ToolCardProps {
  tool: AgentTool;
  onToggle: (enabled: boolean) => void;
  onUpdateParams: (params: Record<string, string | number | boolean>) => void;
  onReset?: () => void;
}

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

  const handleParamChange = useCallback((name: string, value: string | number | boolean) => {
    onUpdateParams({ ...tool.parameterValues, [name]: value });
  }, [tool.parameterValues, onUpdateParams]);

  const formatLastUsed = (dateStr?: string) => {
    if (!dateStr) return 'Nunca usado';
    const date = new Date(dateStr);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    if (diff < 3600000) return `Hace ${Math.floor(diff / 60000)}m`;
    if (diff < 86400000) return `Hace ${Math.floor(diff / 3600000)}h`;
    return date.toLocaleDateString('es-ES', { day: 'numeric', month: 'short' });
  };

  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-4">
        <div className="flex items-start gap-3">
          <div className={`p-2.5 rounded-lg ${category.color}`}>
            <CategoryIcon className="w-5 h-5" />
          </div>

          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 mb-1">
              <h4 className="font-medium text-gray-900 dark:text-white">{tool.name}</h4>
              <span className={`px-2 py-0.5 text-xs rounded ${category.color}`}>
                {category.label}
              </span>
              {tool.isCore && (
                <span className="px-2 py-0.5 text-xs bg-amber-100 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400 rounded">
                  Core
                </span>
              )}
            </div>
            <p className="text-sm text-gray-500 line-clamp-2">{tool.description}</p>
            <div className="flex items-center gap-4 mt-2 text-xs text-gray-400">
              <span>{tool.usageCount} usos</span>
              <span>{formatLastUsed(tool.lastUsed)}</span>
            </div>
          </div>

          <div className="flex items-center gap-2">
            {tool.parameters.length > 0 && (
              <button
                onClick={() => setIsExpanded(!isExpanded)}
                className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
              >
                {isExpanded ? <ChevronUpIcon className="w-4 h-4" /> : <ChevronDownIcon className="w-4 h-4" />}
              </button>
            )}
            <button
              onClick={() => onToggle(!tool.enabled)}
              disabled={tool.isCore}
              className={`relative w-12 h-7 rounded-full transition-colors disabled:cursor-not-allowed ${
                tool.enabled ? 'bg-primary-500' : 'bg-gray-300 dark:bg-gray-600'
              }`}
              title={tool.isCore ? 'Herramienta core - no se puede desactivar' : (tool.enabled ? 'Desactivar' : 'Activar')}
            >
              <div className={`absolute top-1 w-5 h-5 bg-white rounded-full shadow transition-transform ${
                tool.enabled ? 'translate-x-6' : 'translate-x-1'
              }`}>
                {tool.enabled ? (
                  <CheckCircleIcon className="w-5 h-5 text-primary-500" />
                ) : (
                  <XCircleIcon className="w-5 h-5 text-gray-400" />
                )}
              </div>
            </button>
          </div>
        </div>

        {/* Required Permissions */}
        {tool.requiredPermissions && tool.requiredPermissions.length > 0 && (
          <div className="mt-3 flex items-center gap-2">
            <ShieldCheckIcon className="w-4 h-4 text-amber-500" />
            <div className="flex flex-wrap gap-1">
              {tool.requiredPermissions.map((perm) => (
                <span key={perm} className="px-2 py-0.5 text-xs bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400 rounded">
                  {perm}
                </span>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Expanded Parameters */}
      {isExpanded && tool.parameters.length > 0 && (
        <div className="px-4 pb-4 pt-3 border-t border-gray-100 dark:border-gray-700">
          <div className="flex items-center justify-between mb-3">
            <h5 className="text-sm font-medium text-gray-700 dark:text-gray-300">Configuracion</h5>
            {onReset && (
              <button
                onClick={onReset}
                className="text-xs text-gray-500 hover:text-primary-500"
              >
                Restaurar valores
              </button>
            )}
          </div>
          <div className="space-y-3">
            {tool.parameters.map((param) => (
              <ParameterField
                key={param.name}
                param={param}
                value={tool.parameterValues[param.name] ?? param.default}
                onChange={(value) => handleParamChange(param.name, value)}
                disabled={!tool.enabled}
              />
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

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

export const ToolsConfigPanel: React.FC<ToolsConfigPanelProps> = ({
  tools,
  onToggleTool,
  onUpdateToolParams,
  onResetTool,
  onResetAllTools,
  isLoading = false,
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<ToolCategory | 'all'>('all');
  const [showEnabledOnly, setShowEnabledOnly] = useState(false);

  const filteredTools = useMemo(() => {
    let filtered = tools;
    if (categoryFilter !== 'all') {
      filtered = filtered.filter((t) => t.category === categoryFilter);
    }
    if (showEnabledOnly) {
      filtered = filtered.filter((t) => t.enabled);
    }
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter((t) =>
        t.name.toLowerCase().includes(query) || t.description.toLowerCase().includes(query)
      );
    }
    return filtered;
  }, [tools, categoryFilter, showEnabledOnly, searchQuery]);

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

  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">
            <Cog6ToothIcon className="w-5 h-5 text-primary-500" />
            <h3 className="font-semibold text-gray-900 dark:text-white">Herramientas del Agente</h3>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm text-gray-500">{enabledCount}/{tools.length} activas</span>
            {onResetAllTools && (
              <button
                onClick={onResetAllTools}
                className="text-xs text-gray-500 hover:text-primary-500"
              >
                Restaurar todo
              </button>
            )}
          </div>
        </div>

        {/* Category Filters */}
        <div className="flex flex-wrap gap-2 mb-3">
          <button
            onClick={() => setCategoryFilter('all')}
            className={`px-3 py-1.5 text-sm rounded-lg transition-colors ${
              categoryFilter === 'all'
                ? 'bg-primary-500 text-white'
                : 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-700'
            }`}
          >
            Todas
          </button>
          {categories.map((cat) => {
            const info = CATEGORY_INFO[cat];
            const Icon = info.icon;
            return (
              <button
                key={cat}
                onClick={() => setCategoryFilter(cat)}
                className={`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-lg transition-colors ${
                  categoryFilter === cat
                    ? 'bg-primary-500 text-white'
                    : 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-700'
                }`}
              >
                <Icon className="w-4 h-4" />
                {info.label}
              </button>
            );
          })}
        </div>

        {/* Search & Filter */}
        <div className="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="Buscar herramientas..."
              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>
          <button
            onClick={() => setShowEnabledOnly(!showEnabledOnly)}
            className={`flex items-center gap-2 px-3 py-2 text-sm rounded-lg transition-colors ${
              showEnabledOnly
                ? 'bg-primary-100 dark:bg-primary-900/30 text-primary-600 dark:text-primary-400'
                : 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400'
            }`}
          >
            <CheckCircleIcon className="w-4 h-4" />
            Solo activas
          </button>
        </div>
      </div>

      {/* Tools List */}
      <div className="max-h-[500px] overflow-y-auto p-4 space-y-3">
        {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 se encontraron herramientas</p>
          </div>
        ) : (
          filteredTools.map((tool) => (
            <ToolCard
              key={tool.id}
              tool={tool}
              onToggle={(enabled) => onToggleTool(tool.id, enabled)}
              onUpdateParams={(params) => onUpdateToolParams(tool.id, params)}
              onReset={onResetTool ? () => onResetTool(tool.id) : undefined}
            />
          ))
        )}
      </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>
            Las herramientas extienden las capacidades del agente. Activa las herramientas que necesites
            para analisis de mercado, ejecucion de operaciones, calculo de riesgo y mas.
          </p>
        </div>
      </div>
    </div>
  );
};

export default ToolsConfigPanel;
