// ===== ATM ±2 Strikes Enhanced Dashboard =====
// Professional intraday trader view with multiple analysis tabs
// 1. Liquidity Dashboard - bid/ask/spread and liquidity classification
// 2. Spread Trends - Historical spread data and statistics
// 3. Smart Strike Selector - Lot-size based strike recommendation
// 4. Greeks Overlay - Delta, Gamma, Theta, Vega analysis

function AtmStrikesDashboard() {
  const toast = useToast();
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [selectedSymbol, setSelectedSymbol] = React.useState(null);
  const [activeTab, setActiveTab] = React.useState('liquidity'); // Default tab

  // Auto-refresh every 5 seconds (intraday trading speed)
  React.useEffect(() => {
    loadData();
    const interval = setInterval(loadData, 5000);
    return () => clearInterval(interval);
  }, []);

  async function loadData() {
    try {
      const result = await API.get('/api/atm-strikes');
      setData(result);
      setSelectedSymbol(result.symbols?.[0]?.symbol || 'NIFTY');
    } catch (err) {
      toast(err.message || 'Failed to load ATM strikes', 'error');
      setData(null);
    } finally {
      setLoading(false);
    }
  }

  if (loading) {
    return (
      <div style={{ padding: '20px', textAlign: 'center' }}>
        <p>Loading ATM strikes...</p>
      </div>
    );
  }

  if (!data || !data.symbols || data.symbols.length === 0) {
    return (
      <div style={{ padding: '20px', backgroundColor: '#fee', border: '1px solid #f55', borderRadius: '4px' }}>
        <p><strong>⚠ No Data</strong></p>
        <p>Worker service not running or market data not available.</p>
        <p style={{ fontSize: '12px', color: '#666' }}>Check if the Trading.Worker is running and WebSocket feed is active.</p>
      </div>
    );
  }

  const activeSymbol = data.symbols.find(s => s.symbol === selectedSymbol);
  if (!activeSymbol) {
    return <div style={{ padding: '20px', color: '#f00' }}>Symbol not found</div>;
  }

  return (
    <div style={{ padding: '16px', fontFamily: 'monospace' }}>
      {/* Header */}
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h3 style={{ margin: 0 }}>📊 Advanced ATM Strikes Dashboard</h3>
        <div style={{ fontSize: '12px', color: '#666' }}>
          Last Updated: {new Date(data.fetchedAtUtc).toLocaleTimeString('en-IN')}
        </div>
      </div>

      {/* Symbol Tabs */}
      <div style={{ marginBottom: '16px', display: 'flex', gap: '8px' }}>
        {data.symbols.map(sym => (
          <button
            key={sym.symbol}
            onClick={() => setSelectedSymbol(sym.symbol)}
            style={{
              padding: '8px 16px',
              border: selectedSymbol === sym.symbol ? '2px solid #0066cc' : '1px solid #ccc',
              backgroundColor: selectedSymbol === sym.symbol ? '#e6f0ff' : '#fff',
              cursor: 'pointer',
              fontWeight: selectedSymbol === sym.symbol ? 'bold' : 'normal',
              borderRadius: '4px'
            }}
          >
            {sym.symbol} ({sym.spotPrice?.toFixed(0)})
          </button>
        ))}
      </div>

      {/* Feature Tabs */}
      <div style={{ marginBottom: '16px', display: 'flex', gap: '8px', borderBottom: '2px solid #ddd' }}>
        {[
          { id: 'liquidity', label: '💧 Liquidity', icon: 'L' },
          { id: 'spreads', label: '📈 Spread Trends', icon: 'S' },
          { id: 'smart', label: '🎯 Smart Selector', icon: 'SM' },
          { id: 'greeks', label: '📊 Greeks', icon: 'G' }
        ].map(tab => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            style={{
              padding: '10px 16px',
              border: activeTab === tab.id ? '2px solid #ff9800' : '1px solid transparent',
              backgroundColor: activeTab === tab.id ? '#fff3e0' : 'transparent',
              cursor: 'pointer',
              fontWeight: activeTab === tab.id ? 'bold' : 'normal',
              borderRadius: activeTab === tab.id ? '4px 4px 0 0' : '0',
              borderBottom: activeTab === tab.id ? 'none' : '2px solid #ddd',
              color: activeTab === tab.id ? '#ff9800' : '#666'
            }}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Tab Content */}
      <div style={{ backgroundColor: '#fff', padding: '16px', borderRadius: '4px', border: '1px solid #ddd' }}>
        {activeTab === 'liquidity' && (
          <LiquidityTab symbol={selectedSymbol} activeSymbol={activeSymbol} />
        )}
        {activeTab === 'spreads' && (
          <SpreadTrendsTabContent symbol={selectedSymbol} />
        )}
        {activeTab === 'smart' && (
          <SmartStrikeSelectorTabContent symbol={selectedSymbol} />
        )}
        {activeTab === 'greeks' && (
          <GreeksOverlayTabContent symbol={selectedSymbol} />
        )}
      </div>
    </div>
  );
}

/**
 * Liquidity Tab - Original ATM strikes table
 */
function LiquidityTab({ symbol, activeSymbol }) {
  return (
    <div>
      {/* Spot Price & ATM Info */}
      <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#f9f9f9', borderRadius: '4px', border: '1px solid #e0e0e0' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'auto auto', gap: '20px' }}>
          <div>
            <span style={{ color: '#666' }}>Spot Price:</span>
            <strong style={{ marginLeft: '8px', fontSize: '16px' }}>₹{activeSymbol.spotPrice?.toFixed(2)}</strong>
          </div>
          <div>
            <span style={{ color: '#666' }}>ATM Strike:</span>
            <strong style={{ marginLeft: '8px', fontSize: '16px' }}>{activeSymbol.atmStrike}</strong>
          </div>
        </div>
      </div>

      {/* Strikes Table */}
      <div style={{ overflowX: 'auto' }}>
        <table style={{
          width: '100%',
          borderCollapse: 'collapse',
          fontSize: '12px',
          backgroundColor: '#fff',
          border: '1px solid #ddd'
        }}>
          <thead>
            <tr style={{ backgroundColor: '#f0f0f0', borderBottom: '2px solid #333' }}>
              <th style={{ padding: '8px', textAlign: 'left', borderRight: '1px solid #ddd' }}>Strike</th>
              <th colSpan="6" style={{ textAlign: 'center', padding: '8px', borderRight: '1px solid #ddd' }}>CALL (CE)</th>
              <th colSpan="6" style={{ textAlign: 'center', padding: '8px' }}>PUT (PE)</th>
            </tr>
            <tr style={{ backgroundColor: '#f9f9f9', borderBottom: '1px solid #ddd' }}>
              <th style={{ padding: '6px', textAlign: 'left', borderRight: '1px solid #ddd' }}>Price</th>
              {['Bid', 'Ask', 'Spread', 'LTP', 'OI', 'Liquidity'].map(h => (
                <th key={`ce-${h}`} style={{ padding: '6px', textAlign: 'right', borderRight: '1px solid #ddd' }}>
                  {h}
                </th>
              ))}
              {['Bid', 'Ask', 'Spread', 'LTP', 'OI', 'Liquidity'].map(h => (
                <th key={`pe-${h}`} style={{ padding: '6px', textAlign: 'right', borderRight: h === 'Liquidity' ? 'none' : '1px solid #ddd' }}>
                  {h}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {activeSymbol.strikes.map((strike, idx) => (
              <tr
                key={idx}
                style={{
                  backgroundColor: strike.isAtm ? '#ffffcc' : idx % 2 === 0 ? '#f9f9f9' : '#fff',
                  borderBottom: '1px solid #eee',
                  fontWeight: strike.isAtm ? 'bold' : 'normal',
                  border: strike.isAtm ? '2px solid #ff9800' : '1px solid #eee'
                }}
              >
                {/* Strike Price */}
                <td style={{ padding: '6px', textAlign: 'left', borderRight: '1px solid #ddd' }}>
                  {strike.strike} {strike.isAtm && '★'}
                </td>

                {/* CALL (CE) Data */}
                <StrikeLevelCell level={strike.call} />

                {/* PUT (PE) Data */}
                <StrikeLevelCell level={strike.put} />
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Legend */}
      <div style={{ marginTop: '16px', padding: '12px', backgroundColor: '#f0f8ff', borderRadius: '4px', fontSize: '11px' }}>
        <div style={{ marginBottom: '8px' }}>
          <strong>Liquidity Legend (Professional Intraday Standards):</strong>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '8px' }}>
          <div>
            <span style={{
              display: 'inline-block',
              width: '12px',
              height: '12px',
              backgroundColor: '#4caf50',
              marginRight: '6px',
              borderRadius: '2px'
            }}></span>
            <strong>Very Liquid:</strong> Spread &lt; ₹0.05 (best for large orders)
          </div>
          <div>
            <span style={{
              display: 'inline-block',
              width: '12px',
              height: '12px',
              backgroundColor: '#8bc34a',
              marginRight: '6px',
              borderRadius: '2px'
            }}></span>
            <strong>Acceptable:</strong> Spread ₹0.05-₹0.50 (good for intraday)
          </div>
          <div>
            <span style={{
              display: 'inline-block',
              width: '12px',
              height: '12px',
              backgroundColor: '#ff9800',
              marginRight: '6px',
              borderRadius: '2px'
            }}></span>
            <strong>Thin:</strong> Spread ₹0.50-₹2.00 (risky, slippage concern)
          </div>
          <div>
            <span style={{
              display: 'inline-block',
              width: '12px',
              height: '12px',
              backgroundColor: '#f44336',
              marginRight: '6px',
              borderRadius: '2px'
            }}></span>
            <strong>Dangerous:</strong> Spread ≥ ₹2.00 (avoid, high risk)
          </div>
        </div>
      </div>
    </div>
  );
}

// ===== Helper Component: StrikeLevelCell =====
function StrikeLevelCell({ level }) {
  const getLiquidityColor = (status) => {
    switch (status) {
      case 'VeryLiquid': return '#4caf50';
      case 'Acceptable': return '#8bc34a';
      case 'Thin': return '#ff9800';
      case 'Dangerous': return '#f44336';
      default: return '#999';
    }
  };

  const getLiquidityLabel = (status) => {
    switch (status) {
      case 'VeryLiquid': return '✓✓';
      case 'Acceptable': return '✓';
      case 'Thin': return '⚠';
      case 'Dangerous': return '✗';
      default: return '—';
    }
  };

  if (!level) {
    return (
      <>
        <td style={{ padding: '6px', textAlign: 'center', borderRight: '1px solid #ddd' }}>—</td>
        <td style={{ padding: '6px', textAlign: 'center', borderRight: '1px solid #ddd' }}>—</td>
        <td style={{ padding: '6px', textAlign: 'center', borderRight: '1px solid #ddd' }}>—</td>
        <td style={{ padding: '6px', textAlign: 'center', borderRight: '1px solid #ddd' }}>—</td>
        <td style={{ padding: '6px', textAlign: 'center', borderRight: '1px solid #ddd' }}>—</td>
        <td style={{ padding: '6px', textAlign: 'center', borderRight: '1px solid #ddd' }}>—</td>
      </>
    );
  }

  return (
    <>
      <td style={{ padding: '6px', textAlign: 'right', borderRight: '1px solid #ddd' }}>
        {level.bid != null ? `₹${level.bid.toFixed(2)}` : '—'}
      </td>
      <td style={{ padding: '6px', textAlign: 'right', borderRight: '1px solid #ddd' }}>
        {level.ask != null ? `₹${level.ask.toFixed(2)}` : '—'}
      </td>
      <td style={{
        padding: '6px',
        textAlign: 'right',
        fontWeight: 'bold',
        color: getLiquidityColor(level.liquidityStatus),
        borderRight: '1px solid #ddd'
      }}>
        {level.spread != null ? `₹${level.spread.toFixed(2)}` : '—'}
      </td>
      <td style={{ padding: '6px', textAlign: 'right', borderRight: '1px solid #ddd' }}>
        {level.ltp != null ? `₹${level.ltp.toFixed(2)}` : '—'}
      </td>
      <td style={{ padding: '6px', textAlign: 'right', borderRight: '1px solid #ddd' }}>
        {level.openInterest ? (level.openInterest / 1000).toFixed(1) + 'K' : '—'}
      </td>
      <td style={{
        padding: '6px',
        textAlign: 'center',
        backgroundColor: getLiquidityColor(level.liquidityStatus),
        color: '#fff',
        fontWeight: 'bold',
        borderRadius: '3px'
      }}>
        {getLiquidityLabel(level.liquidityStatus)}
      </td>
    </>
  );
}

/**
 * Spread Trends Tab - delegates to SpreadTrendsTab (loaded from spread-trends-tab.jsx)
 */
function SpreadTrendsTabContent({ symbol }) {
  return <SpreadTrendsTab symbol={symbol} />;
}

/**
 * Smart Strike Selector Tab - delegates to SmartStrikeSelectorTab (loaded from smart-strike-selector-tab.jsx)
 */
function SmartStrikeSelectorTabContent({ symbol }) {
  return <SmartStrikeSelectorTab symbol={symbol} />;
}

/**
 * Greeks Overlay Tab - delegates to GreeksOverlayTab (loaded from greeks-overlay-tab.jsx)
 */
function GreeksOverlayTabContent({ symbol }) {
  return <GreeksOverlayTab symbol={symbol} />;
}
