/**
 * IndicatorConfigPanel Component
 * Advanced technical indicator configuration and management
 * OQI-003: Trading y Charts
 */

import React, { useState, useMemo } from 'react';
import {
  Settings,
  Plus,
  Trash2,
  Save,
  RotateCcw,
  ChevronDown,
  ChevronUp,
  TrendingUp,
  Activity,
  BarChart3,
  Waves,
  Target,
  Eye,
  EyeOff,
  Palette,
  Copy,
} from 'lucide-react';

export type IndicatorType = 'sma' | 'ema' | 'rsi' | 'macd' | 'bollinger' | 'atr' | 'stochastic' | 'vwap';

export interface IndicatorConfig {
  id: string;
  type: IndicatorType;
  enabled: boolean;
  params: Record<string, number>;
  color: string;
  lineWidth: number;
}

interface IndicatorPreset {
  name: string;
  indicators: Omit<IndicatorConfig, 'id'>[];
}

interface IndicatorConfigPanelProps {
  indicators?: IndicatorConfig[];
  onIndicatorChange?: (indicators: IndicatorConfig[]) => void;
  onIndicatorAdd?: (indicator: IndicatorConfig) => void;
  onIndicatorRemove?: (indicatorId: string) => void;
  onPresetSave?: (preset: IndicatorPreset) => void;
  onPresetLoad?: (preset: IndicatorPreset) => void;
  savedPresets?: IndicatorPreset[];
  compact?: boolean;
}

const INDICATOR_DEFINITIONS: Record<IndicatorType, {
  label: string;
  icon: React.ReactNode;
  defaultParams: Record<string, number>;
  paramLabels: Record<string, string>;
  color: string;
}> = {
  sma: {
    label: 'Simple Moving Average',
    icon: <TrendingUp className="w-4 h-4" />,
    defaultParams: { period: 20 },
    paramLabels: { period: 'Period' },
    color: '#3B82F6',
  },
  ema: {
    label: 'Exponential Moving Average',
    icon: <TrendingUp className="w-4 h-4" />,
    defaultParams: { period: 12 },
    paramLabels: { period: 'Period' },
    color: '#10B981',
  },
  rsi: {
    label: 'Relative Strength Index',
    icon: <Activity className="w-4 h-4" />,
    defaultParams: { period: 14, overbought: 70, oversold: 30 },
    paramLabels: { period: 'Period', overbought: 'Overbought', oversold: 'Oversold' },
    color: '#8B5CF6',
  },
  macd: {
    label: 'MACD',
    icon: <BarChart3 className="w-4 h-4" />,
    defaultParams: { fastPeriod: 12, slowPeriod: 26, signalPeriod: 9 },
    paramLabels: { fastPeriod: 'Fast', slowPeriod: 'Slow', signalPeriod: 'Signal' },
    color: '#F59E0B',
  },
  bollinger: {
    label: 'Bollinger Bands',
    icon: <Waves className="w-4 h-4" />,
    defaultParams: { period: 20, stdDev: 2 },
    paramLabels: { period: 'Period', stdDev: 'Std Dev' },
    color: '#EC4899',
  },
  atr: {
    label: 'Average True Range',
    icon: <Target className="w-4 h-4" />,
    defaultParams: { period: 14 },
    paramLabels: { period: 'Period' },
    color: '#EF4444',
  },
  stochastic: {
    label: 'Stochastic Oscillator',
    icon: <Activity className="w-4 h-4" />,
    defaultParams: { kPeriod: 14, dPeriod: 3, smooth: 3 },
    paramLabels: { kPeriod: '%K Period', dPeriod: '%D Period', smooth: 'Smooth' },
    color: '#06B6D4',
  },
  vwap: {
    label: 'Volume Weighted Avg Price',
    icon: <BarChart3 className="w-4 h-4" />,
    defaultParams: { period: 1 },
    paramLabels: { period: 'Days' },
    color: '#84CC16',
  },
};

const PRESET_COLORS = [
  '#3B82F6', '#10B981', '#8B5CF6', '#F59E0B', '#EC4899',
  '#EF4444', '#06B6D4', '#84CC16', '#F97316', '#6366F1',
];

const DEFAULT_PRESETS: IndicatorPreset[] = [
  {
    name: 'Trend Following',
    indicators: [
      { type: 'sma', enabled: true, params: { period: 50 }, color: '#3B82F6', lineWidth: 2 },
      { type: 'sma', enabled: true, params: { period: 200 }, color: '#EF4444', lineWidth: 2 },
      { type: 'macd', enabled: true, params: { fastPeriod: 12, slowPeriod: 26, signalPeriod: 9 }, color: '#F59E0B', lineWidth: 1 },
    ],
  },
  {
    name: 'Momentum',
    indicators: [
      { type: 'rsi', enabled: true, params: { period: 14, overbought: 70, oversold: 30 }, color: '#8B5CF6', lineWidth: 1 },
      { type: 'stochastic', enabled: true, params: { kPeriod: 14, dPeriod: 3, smooth: 3 }, color: '#06B6D4', lineWidth: 1 },
    ],
  },
  {
    name: 'Volatility',
    indicators: [
      { type: 'bollinger', enabled: true, params: { period: 20, stdDev: 2 }, color: '#EC4899', lineWidth: 1 },
      { type: 'atr', enabled: true, params: { period: 14 }, color: '#EF4444', lineWidth: 1 },
    ],
  },
];

const IndicatorConfigPanel: React.FC<IndicatorConfigPanelProps> = ({
  indicators = [],
  onIndicatorChange,
  onIndicatorAdd,
  onIndicatorRemove,
  onPresetSave,
  onPresetLoad,
  savedPresets = DEFAULT_PRESETS,
  compact = false,
}) => {
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [showAddMenu, setShowAddMenu] = useState(false);
  const [showPresets, setShowPresets] = useState(false);
  const [presetName, setPresetName] = useState('');

  const generateId = () => `ind_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

  const handleAddIndicator = (type: IndicatorType) => {
    const def = INDICATOR_DEFINITIONS[type];
    const newIndicator: IndicatorConfig = {
      id: generateId(),
      type,
      enabled: true,
      params: { ...def.defaultParams },
      color: def.color,
      lineWidth: 2,
    };
    onIndicatorAdd?.(newIndicator);
    setShowAddMenu(false);
  };

  const handleToggleEnabled = (id: string) => {
    const updated = indicators.map(ind =>
      ind.id === id ? { ...ind, enabled: !ind.enabled } : ind
    );
    onIndicatorChange?.(updated);
  };

  const handleParamChange = (id: string, paramKey: string, value: number) => {
    const updated = indicators.map(ind =>
      ind.id === id ? { ...ind, params: { ...ind.params, [paramKey]: value } } : ind
    );
    onIndicatorChange?.(updated);
  };

  const handleColorChange = (id: string, color: string) => {
    const updated = indicators.map(ind =>
      ind.id === id ? { ...ind, color } : ind
    );
    onIndicatorChange?.(updated);
  };

  const handleLineWidthChange = (id: string, lineWidth: number) => {
    const updated = indicators.map(ind =>
      ind.id === id ? { ...ind, lineWidth } : ind
    );
    onIndicatorChange?.(updated);
  };

  const handleResetDefaults = (id: string) => {
    const indicator = indicators.find(ind => ind.id === id);
    if (!indicator) return;

    const def = INDICATOR_DEFINITIONS[indicator.type];
    const updated = indicators.map(ind =>
      ind.id === id ? { ...ind, params: { ...def.defaultParams }, color: def.color, lineWidth: 2 } : ind
    );
    onIndicatorChange?.(updated);
  };

  const handleDuplicateIndicator = (indicator: IndicatorConfig) => {
    const newIndicator: IndicatorConfig = {
      ...indicator,
      id: generateId(),
      color: PRESET_COLORS[Math.floor(Math.random() * PRESET_COLORS.length)],
    };
    onIndicatorAdd?.(newIndicator);
  };

  const handleSavePreset = () => {
    if (!presetName.trim()) return;
    const preset: IndicatorPreset = {
      name: presetName,
      indicators: indicators.map(({ id, ...rest }) => rest),
    };
    onPresetSave?.(preset);
    setPresetName('');
    setShowPresets(false);
  };

  const handleLoadPreset = (preset: IndicatorPreset) => {
    onPresetLoad?.(preset);
    setShowPresets(false);
  };

  const enabledCount = useMemo(() => indicators.filter(i => i.enabled).length, [indicators]);

  return (
    <div className={`bg-gray-800/50 rounded-xl border border-gray-700 ${compact ? 'p-3' : 'p-4'}`}>
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <Settings className="w-5 h-5 text-blue-400" />
          <div>
            <h3 className="font-semibold text-white">Indicators</h3>
            <p className="text-xs text-gray-500">{enabledCount} active</p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          {/* Presets Button */}
          <div className="relative">
            <button
              onClick={() => setShowPresets(!showPresets)}
              className="px-3 py-1.5 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded text-xs font-medium transition-colors"
            >
              Presets
            </button>

            {showPresets && (
              <div className="absolute top-full right-0 mt-2 w-64 bg-gray-800 rounded-lg border border-gray-700 shadow-xl z-50">
                <div className="p-3 border-b border-gray-700">
                  <div className="text-xs text-gray-400 mb-2">Load Preset</div>
                  <div className="space-y-1">
                    {savedPresets.map((preset, idx) => (
                      <button
                        key={idx}
                        onClick={() => handleLoadPreset(preset)}
                        className="w-full text-left px-3 py-2 text-sm text-white hover:bg-gray-700 rounded transition-colors"
                      >
                        {preset.name}
                        <span className="text-xs text-gray-500 ml-2">
                          ({preset.indicators.length} indicators)
                        </span>
                      </button>
                    ))}
                  </div>
                </div>
                <div className="p-3">
                  <div className="text-xs text-gray-400 mb-2">Save Current</div>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={presetName}
                      onChange={(e) => setPresetName(e.target.value)}
                      placeholder="Preset name..."
                      className="flex-1 px-2 py-1.5 bg-gray-900 border border-gray-700 rounded text-xs text-white focus:outline-none focus:border-blue-500"
                    />
                    <button
                      onClick={handleSavePreset}
                      disabled={!presetName.trim()}
                      className="p-1.5 bg-blue-600 hover:bg-blue-500 text-white rounded disabled:opacity-50"
                    >
                      <Save className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Add Indicator Button */}
          <div className="relative">
            <button
              onClick={() => setShowAddMenu(!showAddMenu)}
              className="flex items-center gap-1 px-3 py-1.5 bg-blue-600 hover:bg-blue-500 text-white rounded text-xs font-medium transition-colors"
            >
              <Plus className="w-4 h-4" />
              Add
            </button>

            {showAddMenu && (
              <div className="absolute top-full right-0 mt-2 w-56 bg-gray-800 rounded-lg border border-gray-700 shadow-xl z-50 max-h-80 overflow-y-auto">
                {Object.entries(INDICATOR_DEFINITIONS).map(([type, def]) => (
                  <button
                    key={type}
                    onClick={() => handleAddIndicator(type as IndicatorType)}
                    className="w-full flex items-center gap-3 px-4 py-2.5 text-white hover:bg-gray-700 transition-colors"
                  >
                    <div className="p-1.5 bg-gray-700 rounded" style={{ color: def.color }}>
                      {def.icon}
                    </div>
                    <span className="text-sm">{def.label}</span>
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Indicators List */}
      {indicators.length === 0 ? (
        <div className="text-center py-8">
          <Activity className="w-10 h-10 text-gray-600 mx-auto mb-2" />
          <p className="text-gray-400 text-sm">No indicators configured</p>
          <p className="text-gray-500 text-xs mt-1">Click "Add" to add technical indicators</p>
        </div>
      ) : (
        <div className="space-y-2 max-h-[400px] overflow-y-auto">
          {indicators.map((indicator) => {
            const def = INDICATOR_DEFINITIONS[indicator.type];
            const isExpanded = expandedId === indicator.id;

            return (
              <div
                key={indicator.id}
                className={`bg-gray-900/50 rounded-lg border transition-all ${
                  indicator.enabled ? 'border-gray-700' : 'border-gray-800 opacity-60'
                }`}
              >
                {/* Header Row */}
                <div
                  onClick={() => setExpandedId(isExpanded ? null : indicator.id)}
                  className="flex items-center justify-between p-3 cursor-pointer hover:bg-gray-800/50"
                >
                  <div className="flex items-center gap-3">
                    <div
                      className="w-3 h-3 rounded-full"
                      style={{ backgroundColor: indicator.color }}
                    />
                    <div className="p-1.5 bg-gray-800 rounded" style={{ color: indicator.color }}>
                      {def.icon}
                    </div>
                    <div>
                      <span className="font-medium text-white text-sm">{def.label}</span>
                      <div className="text-xs text-gray-500">
                        {Object.entries(indicator.params)
                          .map(([k, v]) => `${def.paramLabels[k]}: ${v}`)
                          .join(' • ')}
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        handleToggleEnabled(indicator.id);
                      }}
                      className="p-1.5 text-gray-400 hover:text-white transition-colors"
                    >
                      {indicator.enabled ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
                    </button>
                    {isExpanded ? (
                      <ChevronUp className="w-4 h-4 text-gray-500" />
                    ) : (
                      <ChevronDown className="w-4 h-4 text-gray-500" />
                    )}
                  </div>
                </div>

                {/* Expanded Config */}
                {isExpanded && (
                  <div className="px-3 pb-3 pt-1 border-t border-gray-800">
                    {/* Parameters */}
                    <div className="grid grid-cols-2 gap-3 mb-3">
                      {Object.entries(indicator.params).map(([paramKey, paramValue]) => (
                        <div key={paramKey}>
                          <label className="block text-xs text-gray-500 mb-1">
                            {def.paramLabels[paramKey]}
                          </label>
                          <input
                            type="number"
                            value={paramValue}
                            onChange={(e) => handleParamChange(indicator.id, paramKey, Number(e.target.value))}
                            className="w-full px-2 py-1.5 bg-gray-800 border border-gray-700 rounded text-white text-sm focus:outline-none focus:border-blue-500"
                          />
                        </div>
                      ))}
                    </div>

                    {/* Style Options */}
                    <div className="flex items-center gap-4 mb-3">
                      <div>
                        <label className="block text-xs text-gray-500 mb-1">Color</label>
                        <div className="flex gap-1">
                          {PRESET_COLORS.slice(0, 5).map((color) => (
                            <button
                              key={color}
                              onClick={() => handleColorChange(indicator.id, color)}
                              className={`w-6 h-6 rounded-full border-2 transition-all ${
                                indicator.color === color ? 'border-white scale-110' : 'border-transparent'
                              }`}
                              style={{ backgroundColor: color }}
                            />
                          ))}
                        </div>
                      </div>
                      <div>
                        <label className="block text-xs text-gray-500 mb-1">Line Width</label>
                        <div className="flex gap-1">
                          {[1, 2, 3].map((width) => (
                            <button
                              key={width}
                              onClick={() => handleLineWidthChange(indicator.id, width)}
                              className={`w-8 h-6 rounded text-xs ${
                                indicator.lineWidth === width
                                  ? 'bg-blue-600 text-white'
                                  : 'bg-gray-700 text-gray-300'
                              }`}
                            >
                              {width}px
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>

                    {/* Actions */}
                    <div className="flex items-center justify-between pt-2 border-t border-gray-800">
                      <div className="flex items-center gap-2">
                        <button
                          onClick={() => handleResetDefaults(indicator.id)}
                          className="flex items-center gap-1 px-2 py-1 text-xs text-gray-400 hover:text-white transition-colors"
                        >
                          <RotateCcw className="w-3 h-3" />
                          Reset
                        </button>
                        <button
                          onClick={() => handleDuplicateIndicator(indicator)}
                          className="flex items-center gap-1 px-2 py-1 text-xs text-gray-400 hover:text-white transition-colors"
                        >
                          <Copy className="w-3 h-3" />
                          Duplicate
                        </button>
                      </div>
                      <button
                        onClick={() => onIndicatorRemove?.(indicator.id)}
                        className="flex items-center gap-1 px-2 py-1 text-xs text-red-400 hover:text-red-300 transition-colors"
                      >
                        <Trash2 className="w-3 h-3" />
                        Remove
                      </button>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* Close menus on outside click */}
      {(showAddMenu || showPresets) && (
        <div
          className="fixed inset-0 z-40"
          onClick={() => {
            setShowAddMenu(false);
            setShowPresets(false);
          }}
        />
      )}
    </div>
  );
};

export default IndicatorConfigPanel;
