import { useState, useEffect } from 'react';
import { SymbolChart } from './components/SymbolChart';
import { ChartToolbar } from './components/ChartToolbar';
import { IndicatorList } from './components/IndicatorList';
import { IndicatorSelector } from './components/IndicatorSelector';
import { IndicatorSettings, type IndicatorConfig } from './components/IndicatorSettings';
import type { ChartConfig, CandlestickData, MarketData } from './types';

// Mock data generator for demonstration
function generateMockData(days: number = 365): CandlestickData[] {
  const data: CandlestickData[] = [];
  const now = new Date();
  let price = 100;

  for (let i = days; i >= 0; i--) {
    const date = new Date(now);
    date.setDate(date.getDate() - i);
    
    // Generate realistic price movement
    const volatility = 0.02;
    const trend = Math.random() > 0.5 ? 1 : -1;
    const change = (Math.random() * volatility * 2 - volatility) * price;
    
    const open = price;
    const close = price + change * trend;
    const high = Math.max(open, close) + Math.random() * volatility * price;
    const low = Math.min(open, close) - Math.random() * volatility * price;
    const volume = Math.floor(1000000 + Math.random() * 9000000);

    data.push({
      time: Math.floor(date.getTime() / 1000), // Convert to Unix timestamp (seconds)
      open: parseFloat(open.toFixed(2)),
      high: parseFloat(high.toFixed(2)),
      low: parseFloat(low.toFixed(2)),
      close: parseFloat(close.toFixed(2)),
      volume,
    });

    price = close;
  }

  return data;
}

interface ChartPageProps {
  symbol?: string;
  showHeader?: boolean;
}

export function ChartPage({ symbol = 'AAPL', showHeader = true }: ChartPageProps = {}) {
  const [config, setConfig] = useState<ChartConfig>({
    symbol,
    interval: '1d',
    chartType: 'candlestick',
    showVolume: true,
    indicators: [],
    theme: 'dark',
  });

  const [chartData, setChartData] = useState<CandlestickData[]>([]);
  const [marketData, setMarketData] = useState<MarketData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [showIndicatorSelector, setShowIndicatorSelector] = useState(false);
  const [showIndicatorSettings, setShowIndicatorSettings] = useState(false);
  const [selectedIndicator, setSelectedIndicator] = useState<IndicatorConfig | null>(null);
  const [activeIndicators, setActiveIndicators] = useState<IndicatorConfig[]>([
    {
      id: 'VOLUME',
      name: 'Volume',
      type: 'overlay',
      visible: true,
      parameters: {},
      style: {
        color: '#3b82f6',
        lineWidth: 1,
        lineStyle: 'solid',
      },
    }
  ]);
  const [showSidebar, setShowSidebar] = useState(false);

  // Keyboard shortcuts
  useEffect(() => {
    const handleKeyPress = (e: KeyboardEvent) => {
      if (e.key === '/') {
        e.preventDefault();
        setShowIndicatorSelector(true);
      }
    };

    window.addEventListener('keydown', handleKeyPress);
    return () => window.removeEventListener('keydown', handleKeyPress);
  }, []);

  // Load chart data
  useEffect(() => {
    setIsLoading(true);
    
    // Simulate API call delay
    setTimeout(() => {
      const data = generateMockData();
      setChartData(data);
      
      // Set market data from latest candle
      if (data.length > 0) {
        const latest = data[data.length - 1];
        const previous = data[data.length - 2];
        const change = latest.close - previous.close;
        const changePercent = (change / previous.close) * 100;
        
        setMarketData({
          symbol: config.symbol,
          name: 'Apple Inc.',
          price: latest.close,
          change,
          changePercent,
          volume: latest.volume || 0,
          high: latest.high,
          low: latest.low,
          open: latest.open,
          previousClose: previous.close,
          timestamp: new Date().toISOString(),
        });
      }
      
      setIsLoading(false);
    }, 1000);
  }, [config.symbol, config.interval]);

  const handleConfigChange = (updates: Partial<ChartConfig>) => {
    setConfig(prev => ({ ...prev, ...updates }));
  };

  const handleAddIndicators = (indicatorIds: string[]) => {
    // Filter out indicators that already exist
    const newIndicatorIds = indicatorIds.filter(id => !activeIndicators.find(i => i.id === id));
    
    const newIndicators = newIndicatorIds.map(id => {
      const colors: Record<string, string> = {
        SMA20: '#ff9800',
        SMA50: '#2196f3',
        EMA20: '#4caf50',
        BB: '#ff5252',
        VWAP: '#9c27b0',
        RSI: '#00bcd4',
        MACD: '#795548',
      };

      return {
        id,
        name: id.replace(/(\d+)/, ' $1'),
        type: ['RSI', 'MACD'].includes(id) ? 'panel' : 'overlay',
        visible: true,
        parameters: {},
        style: {
          color: colors[id] || '#9e9e9e',
          lineWidth: 2,
          lineStyle: 'solid' as const,
        },
      } as IndicatorConfig;
    });

    const updatedIndicators = [...activeIndicators, ...newIndicators];
    setActiveIndicators(updatedIndicators);
    setConfig(prev => ({ ...prev, indicators: updatedIndicators.filter(i => i.id !== 'VOLUME').map(i => i.id) }));
  };

  const handleRemoveIndicator = (id: string) => {
    // Don't allow removing Volume indicator
    if (id === 'VOLUME') return;
    
    setActiveIndicators(prev => prev.filter(i => i.id !== id));
    setConfig(prev => ({ ...prev, indicators: prev.indicators.filter(i => i !== id) }));
  };

  const handleToggleIndicatorVisibility = (id: string) => {
    setActiveIndicators(prev => {
      const updated = prev.map(i => 
        i.id === id ? { ...i, visible: !i.visible } : i
      );
      // Force chart update by also updating config
      if (id === 'VOLUME') {
        const volumeIndicator = updated.find(i => i.id === 'VOLUME');
        setConfig(prevConfig => ({ 
          ...prevConfig, 
          showVolume: volumeIndicator?.visible ?? true 
        }));
      }
      return updated;
    });
  };

  const handleIndicatorSettings = (id: string) => {
    const indicator = activeIndicators.find(i => i.id === id);
    if (indicator) {
      setSelectedIndicator(indicator);
      setShowIndicatorSettings(true);
    }
  };

  const handleSaveIndicatorSettings = (updatedConfig: IndicatorConfig) => {
    setActiveIndicators(prev => prev.map(i => 
      i.id === updatedConfig.id ? updatedConfig : i
    ));
  };

  return (
    <div className="flex flex-col h-full">
      {showHeader && (
        <div className="flex-shrink-0">
          <h1 className="text-lg font-bold text-text-primary mb-2 px-8 pt-4">Market Charts</h1>
          <p className="text-text-secondary mb-4 text-sm px-8">
            Real-time market data and advanced charting powered by TradingView.
          </p>
        </div>
      )}

      <div className={`flex-1 flex bg-surface-secondary ${showHeader ? 'rounded-lg border border-border mx-8 mb-8' : ''} overflow-hidden`}>
        {/* Left Sidebar - Indicator List */}
        {showSidebar && (
          <IndicatorList
          indicators={activeIndicators.map(i => ({
            id: i.id,
            name: i.name,
            type: i.type,
            visible: i.visible,
            color: i.style.color,
          }))}
          onRemove={handleRemoveIndicator}
          onToggleVisibility={handleToggleIndicatorVisibility}
          onSettings={handleIndicatorSettings}
          onAddIndicator={() => setShowIndicatorSelector(true)}
        />
        )}

        {/* Main Chart Area */}
        <div className="flex-1 flex flex-col">
          <ChartToolbar config={config} onConfigChange={handleConfigChange} />
          
          <div className="flex-1">
            {isLoading ? (
              <div className="h-full flex items-center justify-center">
                <div className="text-center">
                  <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-primary-500 mx-auto mb-4"></div>
                  <p className="text-sm text-text-secondary">Loading chart data...</p>
                </div>
              </div>
            ) : (
              <SymbolChart
                symbol={config.symbol}
                data={chartData}
                config={{
                  ...config,
                  indicators: activeIndicators.filter(i => i.visible && i.id !== 'VOLUME').map(i => i.id),
                  showVolume: activeIndicators.find(i => i.id === 'VOLUME')?.visible ?? true,
                }}
                activeIndicators={activeIndicators}
                onIndicatorSettings={handleIndicatorSettings}
                onIndicatorRemove={handleRemoveIndicator}
                onIndicatorToggle={handleToggleIndicatorVisibility}
                onAddIndicator={() => setShowIndicatorSelector(true)}
                className="h-full"
              />
            )}
          </div>
        </div>
      </div>

      {/* Indicator Selector Modal */}
      <IndicatorSelector
        isOpen={showIndicatorSelector}
        onClose={() => setShowIndicatorSelector(false)}
        selectedIndicators={activeIndicators.map(i => i.id)}
        onIndicatorsChange={handleAddIndicators}
      />

      {/* Indicator Settings Modal */}
      <IndicatorSettings
        isOpen={showIndicatorSettings}
        onClose={() => setShowIndicatorSettings(false)}
        indicator={selectedIndicator}
        onSave={handleSaveIndicatorSettings}
      />
    </div>
  );
}