import { useState, useEffect } from 'react';
import { TrendingUp, Star, Save, Plus, Trash2, Info } from 'lucide-react';
import { settingsApi } from '../services/api';

interface IndicatorPreference {
  id?: number;
  indicator_name: string;
  enabled: boolean;
  parameters?: any;
  priority: number;
  notes?: string;
}

// Available indicators in the system
const AVAILABLE_INDICATORS = [
  { name: 'SMA', label: 'Simple Moving Average', description: 'Smooths price data to identify trends' },
  { name: 'EMA', label: 'Exponential Moving Average', description: 'More weight to recent prices' },
  { name: 'RSI', label: 'Relative Strength Index', description: 'Momentum oscillator (0-100)' },
  { name: 'MACD', label: 'Moving Average Convergence Divergence', description: 'Trend-following momentum indicator' },
  { name: 'BB', label: 'Bollinger Bands', description: 'Volatility bands around price' },
  { name: 'ATR', label: 'Average True Range', description: 'Measures market volatility' },
  { name: 'Stochastic', label: 'Stochastic Oscillator', description: 'Momentum indicator comparing price to range' },
  { name: 'Fibonacci', label: 'Fibonacci Retracement', description: 'Support/resistance levels' },
  { name: 'VWAP', label: 'Volume Weighted Average Price', description: 'Average price weighted by volume' },
  { name: 'Pivot', label: 'Pivot Points', description: 'Key support and resistance levels' },
];

export default function IndicatorPreferences() {
  const [preferences, setPreferences] = useState<IndicatorPreference[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  useEffect(() => {
    loadPreferences();
  }, []);

  const loadPreferences = async () => {
    try {
      setLoading(true);
      const response = await settingsApi.getIndicatorPreferences();
      setPreferences(response.preferences || []);
    } catch (error) {
      console.error('Failed to load indicator preferences:', error);
      setMessage({ type: 'error', text: 'Failed to load preferences' });
    } finally {
      setLoading(false);
    }
  };

  const addIndicator = (indicatorName: string) => {
    const existing = preferences.find(p => p.indicator_name === indicatorName);
    if (existing) {
      setMessage({ type: 'error', text: 'Indicator already added' });
      return;
    }

    const newPref: IndicatorPreference = {
      indicator_name: indicatorName,
      enabled: true,
      priority: 1,
      parameters: {},
      notes: '',
    };

    setPreferences([...preferences, newPref]);
  };

  const removeIndicator = (index: number) => {
    const pref = preferences[index];
    if (pref.id) {
      // Delete from backend if it has an ID
      settingsApi.deleteIndicatorPreference(pref.id).catch(console.error);
    }
    setPreferences(preferences.filter((_, i) => i !== index));
  };

  const updatePreference = (index: number, updates: Partial<IndicatorPreference>) => {
    const updated = [...preferences];
    updated[index] = { ...updated[index], ...updates };
    setPreferences(updated);
  };

  const savePreferences = async () => {
    try {
      setSaving(true);
      setMessage(null);

      // Separate new preferences from existing ones
      const newPrefs = preferences.filter(p => !p.id);
      const existingPrefs = preferences.filter(p => p.id);

      // Create new preferences in bulk
      if (newPrefs.length > 0) {
        await settingsApi.createBulkIndicatorPreferences(newPrefs);
      }

      // Update existing preferences
      for (const pref of existingPrefs) {
        if (pref.id) {
          await settingsApi.updateIndicatorPreference(pref.id, {
            enabled: pref.enabled,
            parameters: pref.parameters,
            priority: pref.priority,
            notes: pref.notes,
          });
        }
      }

      setMessage({ type: 'success', text: 'Preferences saved successfully!' });
      await loadPreferences(); // Reload to get IDs for new items
    } catch (error: any) {
      console.error('Failed to save preferences:', error);
      setMessage({ type: 'error', text: error.response?.data?.detail || 'Failed to save preferences' });
    } finally {
      setSaving(false);
    }
  };

  const getUnusedIndicators = () => {
    return AVAILABLE_INDICATORS.filter(
      ind => !preferences.some(p => p.indicator_name === ind.name)
    );
  };

  if (loading) {
    return (
      <div className="bg-dark-panel rounded-xl border border-gray-800 p-6">
        <div className="flex items-center justify-center py-8">
          <div className="text-gray-400">Loading preferences...</div>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-dark-panel rounded-xl border border-gray-800 p-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-blue-500/20 rounded-lg">
            <TrendingUp className="w-5 h-5 text-blue-500" />
          </div>
          <div>
            <h3 className="text-lg font-semibold">Indicator Preferences</h3>
            <p className="text-sm text-gray-400">
              Select indicators to use in AI trading plan generation
            </p>
          </div>
        </div>
        <button
          onClick={savePreferences}
          disabled={saving}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-700 disabled:cursor-not-allowed rounded-lg transition-colors"
        >
          <Save className="w-4 h-4" />
          {saving ? 'Saving...' : 'Save'}
        </button>
      </div>

      {/* Message */}
      {message && (
        <div
          className={`mb-4 p-3 rounded-lg ${
            message.type === 'success'
              ? 'bg-green-500/10 border border-green-500/30 text-green-500'
              : 'bg-red-500/10 border border-red-500/30 text-red-500'
          }`}
        >
          {message.text}
        </div>
      )}

      {/* Info Box */}
      <div className="mb-6 p-4 bg-blue-500/10 border border-blue-500/30 rounded-lg flex gap-3">
        <Info className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" />
        <div className="text-sm text-blue-200">
          <p className="font-semibold mb-1">How it works:</p>
          <ul className="list-disc list-inside space-y-1 text-blue-300">
            <li>Select your preferred indicators for analysis</li>
            <li>Set priority (higher = more important in AI analysis)</li>
            <li>AI will focus on these indicators when generating trading plans</li>
          </ul>
        </div>
      </div>

      {/* Selected Indicators */}
      <div className="space-y-3 mb-6">
        {preferences.length === 0 ? (
          <div className="text-center py-8 text-gray-400">
            <TrendingUp className="w-12 h-12 mx-auto mb-3 opacity-50" />
            <p>No indicators selected</p>
            <p className="text-sm mt-1">Add indicators below to get started</p>
          </div>
        ) : (
          preferences.map((pref, index) => {
            const indicatorInfo = AVAILABLE_INDICATORS.find(i => i.name === pref.indicator_name);
            return (
              <div
                key={index}
                className="p-4 bg-dark-bg border border-gray-700 rounded-lg"
              >
                <div className="flex items-start justify-between mb-3">
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-1">
                      <h4 className="font-semibold">{indicatorInfo?.label || pref.indicator_name}</h4>
                      <button
                        onClick={() => updatePreference(index, { enabled: !pref.enabled })}
                        className={`text-xs px-2 py-1 rounded ${
                          pref.enabled
                            ? 'bg-green-500/20 text-green-500'
                            : 'bg-gray-700 text-gray-400'
                        }`}
                      >
                        {pref.enabled ? 'Enabled' : 'Disabled'}
                      </button>
                    </div>
                    <p className="text-xs text-gray-400">{indicatorInfo?.description}</p>
                  </div>
                  <button
                    onClick={() => removeIndicator(index)}
                    className="p-2 hover:bg-red-500/20 rounded-lg text-red-500 transition-colors"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs text-gray-400 mb-1">
                      Priority (1-10)
                    </label>
                    <div className="flex items-center gap-2">
                      <input
                        type="range"
                        min="1"
                        max="10"
                        value={pref.priority}
                        onChange={(e) =>
                          updatePreference(index, { priority: parseInt(e.target.value) })
                        }
                        className="flex-1"
                      />
                      <div className="flex gap-0.5">
                        {[...Array(pref.priority)].map((_, i) => (
                          <Star key={i} className="w-3 h-3 text-yellow-500 fill-yellow-500" />
                        ))}
                      </div>
                    </div>
                  </div>
                  <div>
                    <label className="block text-xs text-gray-400 mb-1">Notes</label>
                    <input
                      type="text"
                      value={pref.notes || ''}
                      onChange={(e) => updatePreference(index, { notes: e.target.value })}
                      placeholder="Why this indicator?"
                      className="w-full px-3 py-1.5 bg-dark-panel border border-gray-700 rounded text-sm"
                    />
                  </div>
                </div>
              </div>
            );
          })
        )}
      </div>

      {/* Add Indicator Section */}
      <div className="border-t border-gray-700 pt-6">
        <h4 className="text-sm font-semibold mb-3 flex items-center gap-2">
          <Plus className="w-4 h-4" />
          Add Indicators
        </h4>
        <div className="grid grid-cols-2 gap-2">
          {getUnusedIndicators().map((indicator) => (
            <button
              key={indicator.name}
              onClick={() => addIndicator(indicator.name)}
              className="p-3 bg-dark-bg hover:bg-dark-hover border border-gray-700 hover:border-blue-500/50 rounded-lg text-left transition-all group"
            >
              <div className="font-medium text-sm group-hover:text-blue-500 transition-colors">
                {indicator.label}
              </div>
              <div className="text-xs text-gray-400 mt-0.5">{indicator.description}</div>
            </button>
          ))}
        </div>
        {getUnusedIndicators().length === 0 && (
          <p className="text-sm text-gray-400 text-center py-4">
            All indicators have been added
          </p>
        )}
      </div>
    </div>
  );
}
