/**
 * LLMConfigPanel Component
 * Model selection and inference parameters
 * OQI-007: LLM Strategy Agent
 */

import React, { useState } from 'react';
import {
  CpuChipIcon,
  AdjustmentsHorizontalIcon,
  SparklesIcon,
  CurrencyDollarIcon,
  ClockIcon,
  LightBulbIcon,
  BookmarkIcon,
  XMarkIcon,
  InformationCircleIcon,
  CheckIcon,
} from '@heroicons/react/24/outline';

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

export type ModelId = 'claude-3-5-sonnet' | 'claude-3-opus' | 'claude-3-haiku';
export type ReasoningStyle = 'concise' | 'detailed' | 'technical' | 'exploratory';
export type AnalysisDepth = 'quick' | 'standard' | 'deep';

export interface LLMConfig {
  modelId: ModelId;
  temperature: number;
  reasoningStyle: ReasoningStyle;
  analysisDepth: AnalysisDepth;
  showThinking: boolean;
  maxTokens: number;
}

export interface ModelInfo {
  id: ModelId;
  name: string;
  description: string;
  contextWindow: string;
  speed: 'fast' | 'medium' | 'slow';
  intelligence: 'good' | 'great' | 'best';
  costPerMToken: number;
}

export interface ConfigPreset {
  id: string;
  name: string;
  description: string;
  config: LLMConfig;
}

interface LLMConfigPanelProps {
  config: LLMConfig;
  onConfigChange: (config: LLMConfig) => void;
  onSavePreset?: (name: string, config: LLMConfig) => void;
  savedPresets?: ConfigPreset[];
  onLoadPreset?: (presetId: string) => void;
  estimatedCost?: number;
  isOpen: boolean;
  onClose: () => void;
}

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

const MODELS: ModelInfo[] = [
  {
    id: 'claude-3-5-sonnet',
    name: 'Claude 3.5 Sonnet',
    description: 'Fast and capable, great for most analysis tasks',
    contextWindow: '200K',
    speed: 'fast',
    intelligence: 'great',
    costPerMToken: 3.0,
  },
  {
    id: 'claude-3-opus',
    name: 'Claude 3 Opus',
    description: 'Most intelligent, best for complex reasoning',
    contextWindow: '200K',
    speed: 'slow',
    intelligence: 'best',
    costPerMToken: 15.0,
  },
  {
    id: 'claude-3-haiku',
    name: 'Claude 3 Haiku',
    description: 'Budget-friendly, good for simple queries',
    contextWindow: '200K',
    speed: 'fast',
    intelligence: 'good',
    costPerMToken: 0.25,
  },
];

const REASONING_STYLES: Array<{ value: ReasoningStyle; label: string; desc: string }> = [
  { value: 'concise', label: 'Concise', desc: 'Brief, actionable insights' },
  { value: 'detailed', label: 'Detailed', desc: 'Comprehensive explanations' },
  { value: 'technical', label: 'Technical', desc: 'In-depth technical analysis' },
  { value: 'exploratory', label: 'Exploratory', desc: 'Consider multiple scenarios' },
];

const ANALYSIS_DEPTHS: Array<{ value: AnalysisDepth; label: string; desc: string; tools: string }> = [
  { value: 'quick', label: 'Quick', desc: 'Fast signal check', tools: '1 tool call' },
  { value: 'standard', label: 'Standard', desc: 'Balanced analysis', tools: '2-3 tool calls' },
  { value: 'deep', label: 'Deep', desc: 'Thorough investigation', tools: '5+ tool calls' },
];

const DEFAULT_PRESETS: ConfigPreset[] = [
  {
    id: 'quick-signal',
    name: 'Quick Signal Check',
    description: 'Fast, low-cost signal verification',
    config: {
      modelId: 'claude-3-haiku',
      temperature: 0.3,
      reasoningStyle: 'concise',
      analysisDepth: 'quick',
      showThinking: false,
      maxTokens: 1024,
    },
  },
  {
    id: 'deep-analysis',
    name: 'Deep Analysis',
    description: 'Comprehensive market analysis',
    config: {
      modelId: 'claude-3-opus',
      temperature: 0.7,
      reasoningStyle: 'detailed',
      analysisDepth: 'deep',
      showThinking: true,
      maxTokens: 4096,
    },
  },
  {
    id: 'balanced',
    name: 'Balanced',
    description: 'Good balance of speed and quality',
    config: {
      modelId: 'claude-3-5-sonnet',
      temperature: 0.5,
      reasoningStyle: 'detailed',
      analysisDepth: 'standard',
      showThinking: false,
      maxTokens: 2048,
    },
  },
];

// ============================================================================
// Component
// ============================================================================

export const LLMConfigPanel: React.FC<LLMConfigPanelProps> = ({
  config,
  onConfigChange,
  onSavePreset,
  savedPresets = [],
  onLoadPreset,
  estimatedCost,
  isOpen,
  onClose,
}) => {
  const [showSaveDialog, setShowSaveDialog] = useState(false);
  const [presetName, setPresetName] = useState('');
  const [activeTab, setActiveTab] = useState<'model' | 'style' | 'presets'>('model');

  const allPresets = [...DEFAULT_PRESETS, ...savedPresets];

  const updateConfig = <K extends keyof LLMConfig>(key: K, value: LLMConfig[K]) => {
    onConfigChange({ ...config, [key]: value });
  };

  const selectedModel = MODELS.find((m) => m.id === config.modelId) || MODELS[0];

  const getSpeedBadge = (speed: ModelInfo['speed']) => {
    switch (speed) {
      case 'fast':
        return 'bg-emerald-500/20 text-emerald-400';
      case 'medium':
        return 'bg-yellow-500/20 text-yellow-400';
      case 'slow':
        return 'bg-red-500/20 text-red-400';
    }
  };

  const getIntelligenceBadge = (intel: ModelInfo['intelligence']) => {
    switch (intel) {
      case 'good':
        return 'bg-gray-500/20 text-gray-400';
      case 'great':
        return 'bg-blue-500/20 text-blue-400';
      case 'best':
        return 'bg-purple-500/20 text-purple-400';
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white dark:bg-gray-900 rounded-xl max-w-2xl w-full max-h-[85vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="p-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <CpuChipIcon className="w-5 h-5 text-primary-500" />
            <h3 className="font-semibold text-gray-900 dark:text-white">LLM Configuration</h3>
          </div>
          <button onClick={onClose} className="p-1 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg">
            <XMarkIcon className="w-5 h-5 text-gray-400" />
          </button>
        </div>

        {/* Tabs */}
        <div className="flex border-b border-gray-200 dark:border-gray-700">
          {[
            { id: 'model', label: 'Model', icon: CpuChipIcon },
            { id: 'style', label: 'Style', icon: AdjustmentsHorizontalIcon },
            { id: 'presets', label: 'Presets', icon: BookmarkIcon },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id as typeof activeTab)}
              className={`flex-1 flex items-center justify-center gap-2 py-3 text-sm font-medium border-b-2 transition-colors ${
                activeTab === tab.id
                  ? 'border-primary-500 text-primary-500'
                  : 'border-transparent text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'
              }`}
            >
              <tab.icon className="w-4 h-4" />
              {tab.label}
            </button>
          ))}
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-4">
          {/* Model Tab */}
          {activeTab === 'model' && (
            <div className="space-y-4">
              <div className="space-y-3">
                {MODELS.map((model) => (
                  <button
                    key={model.id}
                    onClick={() => updateConfig('modelId', model.id)}
                    className={`w-full p-4 rounded-xl border-2 text-left transition-all ${
                      config.modelId === model.id
                        ? 'border-primary-500 bg-primary-500/5'
                        : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
                    }`}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <span className="font-semibold text-gray-900 dark:text-white">{model.name}</span>
                          {config.modelId === model.id && (
                            <CheckIcon className="w-4 h-4 text-primary-500" />
                          )}
                        </div>
                        <p className="text-sm text-gray-500 mt-1">{model.description}</p>
                        <div className="flex gap-2 mt-2">
                          <span className={`px-2 py-0.5 text-xs rounded ${getSpeedBadge(model.speed)}`}>
                            {model.speed}
                          </span>
                          <span className={`px-2 py-0.5 text-xs rounded ${getIntelligenceBadge(model.intelligence)}`}>
                            {model.intelligence}
                          </span>
                          <span className="px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-800 text-gray-500 rounded">
                            {model.contextWindow} context
                          </span>
                        </div>
                      </div>
                      <div className="text-right">
                        <div className="text-sm font-medium text-gray-900 dark:text-white">
                          ${model.costPerMToken.toFixed(2)}
                        </div>
                        <div className="text-xs text-gray-500">/1M tokens</div>
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Style Tab */}
          {activeTab === 'style' && (
            <div className="space-y-6">
              {/* Temperature */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <label className="text-sm font-medium text-gray-900 dark:text-white">
                    Temperature
                  </label>
                  <span className="text-sm text-gray-500">{config.temperature.toFixed(1)}</span>
                </div>
                <input
                  type="range"
                  min="0"
                  max="1"
                  step="0.1"
                  value={config.temperature}
                  onChange={(e) => updateConfig('temperature', parseFloat(e.target.value))}
                  className="w-full"
                />
                <div className="flex justify-between text-xs text-gray-500 mt-1">
                  <span>Deterministic (0)</span>
                  <span>Creative (1)</span>
                </div>
              </div>

              {/* Reasoning Style */}
              <div>
                <label className="block text-sm font-medium text-gray-900 dark:text-white mb-2">
                  Reasoning Style
                </label>
                <div className="grid grid-cols-2 gap-2">
                  {REASONING_STYLES.map((style) => (
                    <button
                      key={style.value}
                      onClick={() => updateConfig('reasoningStyle', style.value)}
                      className={`p-3 rounded-lg border-2 text-left transition-all ${
                        config.reasoningStyle === style.value
                          ? 'border-primary-500 bg-primary-500/5'
                          : 'border-gray-200 dark:border-gray-700 hover:border-gray-300'
                      }`}
                    >
                      <div className="font-medium text-gray-900 dark:text-white text-sm">{style.label}</div>
                      <div className="text-xs text-gray-500">{style.desc}</div>
                    </button>
                  ))}
                </div>
              </div>

              {/* Analysis Depth */}
              <div>
                <label className="block text-sm font-medium text-gray-900 dark:text-white mb-2">
                  Analysis Depth
                </label>
                <div className="flex gap-2">
                  {ANALYSIS_DEPTHS.map((depth) => (
                    <button
                      key={depth.value}
                      onClick={() => updateConfig('analysisDepth', depth.value)}
                      className={`flex-1 p-3 rounded-lg border-2 text-center transition-all ${
                        config.analysisDepth === depth.value
                          ? 'border-primary-500 bg-primary-500/5'
                          : 'border-gray-200 dark:border-gray-700 hover:border-gray-300'
                      }`}
                    >
                      <div className="font-medium text-gray-900 dark:text-white text-sm">{depth.label}</div>
                      <div className="text-xs text-gray-500">{depth.tools}</div>
                    </button>
                  ))}
                </div>
              </div>

              {/* Show Thinking */}
              <div className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                <div className="flex items-center gap-3">
                  <LightBulbIcon className="w-5 h-5 text-yellow-500" />
                  <div>
                    <div className="font-medium text-gray-900 dark:text-white text-sm">Show Thinking</div>
                    <div className="text-xs text-gray-500">Display Claude's reasoning process</div>
                  </div>
                </div>
                <button
                  onClick={() => updateConfig('showThinking', !config.showThinking)}
                  className={`relative w-11 h-6 rounded-full transition-colors ${
                    config.showThinking ? '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 ${
                      config.showThinking ? 'translate-x-6' : 'translate-x-1'
                    }`}
                  />
                </button>
              </div>

              {/* Max Tokens */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <label className="text-sm font-medium text-gray-900 dark:text-white">
                    Max Response Tokens
                  </label>
                  <span className="text-sm text-gray-500">{config.maxTokens.toLocaleString()}</span>
                </div>
                <input
                  type="range"
                  min="512"
                  max="8192"
                  step="256"
                  value={config.maxTokens}
                  onChange={(e) => updateConfig('maxTokens', parseInt(e.target.value))}
                  className="w-full"
                />
              </div>
            </div>
          )}

          {/* Presets Tab */}
          {activeTab === 'presets' && (
            <div className="space-y-3">
              {allPresets.map((preset) => (
                <button
                  key={preset.id}
                  onClick={() => onConfigChange(preset.config)}
                  className="w-full p-4 bg-gray-50 dark:bg-gray-800 rounded-lg text-left hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <div className="font-medium text-gray-900 dark:text-white">{preset.name}</div>
                      <div className="text-sm text-gray-500">{preset.description}</div>
                    </div>
                    <div className="text-xs text-gray-400">
                      {MODELS.find((m) => m.id === preset.config.modelId)?.name}
                    </div>
                  </div>
                </button>
              ))}

              {onSavePreset && (
                <button
                  onClick={() => setShowSaveDialog(true)}
                  className="w-full p-4 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg text-gray-500 hover:border-primary-500 hover:text-primary-500 transition-colors"
                >
                  + Save Current as Preset
                </button>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-4 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4 text-sm text-gray-500">
              <div className="flex items-center gap-1">
                <CpuChipIcon className="w-4 h-4" />
                <span>{selectedModel.name}</span>
              </div>
              {estimatedCost !== undefined && (
                <div className="flex items-center gap-1">
                  <CurrencyDollarIcon className="w-4 h-4" />
                  <span>~${estimatedCost.toFixed(4)}/request</span>
                </div>
              )}
            </div>
            <button
              onClick={onClose}
              className="px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-lg font-medium transition-colors"
            >
              Apply
            </button>
          </div>
        </div>

        {/* Save Preset Dialog */}
        {showSaveDialog && (
          <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
            <div className="bg-white dark:bg-gray-900 rounded-xl p-6 w-80">
              <h4 className="font-semibold text-gray-900 dark:text-white mb-4">Save Preset</h4>
              <input
                type="text"
                value={presetName}
                onChange={(e) => setPresetName(e.target.value)}
                placeholder="Preset name..."
                className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-800 border-0 rounded-lg text-gray-900 dark:text-white mb-4"
              />
              <div className="flex gap-2">
                <button
                  onClick={() => setShowSaveDialog(false)}
                  className="flex-1 px-4 py-2 text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg"
                >
                  Cancel
                </button>
                <button
                  onClick={() => {
                    if (presetName.trim()) {
                      onSavePreset?.(presetName, config);
                      setShowSaveDialog(false);
                      setPresetName('');
                    }
                  }}
                  disabled={!presetName.trim()}
                  className="flex-1 px-4 py-2 bg-primary-600 text-white rounded-lg font-medium disabled:opacity-50"
                >
                  Save
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default LLMConfigPanel;
