import { useEffect, useMemo, useState } from 'react'
import SimpleKlineChart from './SimpleKlineChart'
import SymbolTimeframeSelector from './SymbolTimeframeSelector'
import { useSSEMultiplexer } from '@/hooks/useSSEMultiplexer'

function tfToSeconds(tf: string): number {
  switch (tf) {
    case '1m': return 60
    case '5m': return 5 * 60
    case '1h': return 60 * 60
    case '4h': return 4 * 60 * 60
    default: return 60
  }
}

type Bar = { time: number; open: number; high: number; low: number; close: number }

function resampleFrom1m(bars1m: Bar[], timeframe: string): Bar[] {
  const tfSec = tfToSeconds(timeframe)
  const buckets = new Map<number, Bar>()
  for (const r of bars1m) {
    const b = Math.floor(r.time / tfSec) * tfSec
    const cur = buckets.get(b)
    if (!cur) {
      buckets.set(b, { time: b, open: r.open, high: r.high, low: r.low, close: r.close })
    } else {
      cur.high = Math.max(cur.high, r.high)
      cur.low = Math.min(cur.low, r.low)
      cur.close = r.close
    }
  }
  return Array.from(buckets.values()).sort((a, b) => a.time - b.time)
}

export default function LiveMarketPanel() {
  const [symbol1, setSymbol1] = useState<string>('BTCUSDT')
  const [tf1, setTf1] = useState<string>('1m')
  const [symbol2, setSymbol2] = useState<string>('XAUUSD')
  const [tf2, setTf2] = useState<string>('1m')

  const symbols = useMemo(() => Array.from(new Set([symbol1, symbol2])), [symbol1, symbol2])
  const { isConnected, lastBySymbol } = useSSEMultiplexer(symbols, '1m')

  const [history1m, setHistory1m] = useState<Record<string, Bar[]>>({})

  // Load initial 1m history for selected symbols
  useEffect(() => {
    let cancelled = false
    ;(async () => {
      const next: Record<string, Bar[]> = { ...history1m }
      for (const s of symbols) {
        if (next[s]?.length) continue
        try {
          const rows = await (await import('@/services/api')).marketDataApi.getOHLCV(s, '1m', 1000)
          next[s] = rows.map(r => ({ time: r.time as number, open: r.open, high: r.high, low: r.low, close: r.close }))
        } catch {
          next[s] = []
        }
      }
      if (!cancelled) setHistory1m(next)
    })()
    return () => { cancelled = true }
  }, [symbols.join(',')])

  // Apply incoming SSE events to 1m history buffers
  useEffect(() => {
    if (!Object.keys(lastBySymbol).length) return
    setHistory1m(prev => {
      const next = { ...prev }
      for (const [sym, evt] of Object.entries(lastBySymbol)) {
        if (!evt) continue
        const t = Math.floor(Date.parse(evt.close_time) / 1000)
        const arr = next[sym] ? [...next[sym]] : []
        if (arr.length && arr[arr.length - 1].time === t) {
          arr[arr.length - 1] = { time: t, open: evt.open, high: evt.high, low: evt.low, close: evt.close }
        } else if (!arr.length || arr[arr.length - 1].time < t) {
          arr.push({ time: t, open: evt.open, high: evt.high, low: evt.low, close: evt.close })
          if (arr.length > 2000) arr.shift()
        }
        next[sym] = arr
      }
      return next
    })
  }, [lastBySymbol])

  const data1 = useMemo(() => {
    const base = history1m[symbol1] || []
    return tf1 === '1m' ? base : resampleFrom1m(base, tf1)
  }, [history1m, symbol1, tf1])

  const data2 = useMemo(() => {
    const base = history1m[symbol2] || []
    return tf2 === '1m' ? base : resampleFrom1m(base, tf2)
  }, [history1m, symbol2, tf2])

  return (
    <div style={{ display: 'grid', gap: 16, gridTemplateColumns: '1fr', paddingBottom: 16 }}>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '0 0 8px 0' }}>
          <SymbolTimeframeSelector symbol={symbol1} timeframe={tf1} onChangeSymbol={setSymbol1} onChangeTimeframe={setTf1} />
          {isConnected ? <span style={{ color: '#10b981' }}>● SSE</span> : <span style={{ color: '#ef4444' }}>● SSE</span>}
        </div>
        <SimpleKlineChart title={`${symbol1} — ${tf1} (SSE)`} data={data1.map(b => ({ ...b, time: b.time as any }))} />
      </div>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '0 0 8px 0' }}>
          <SymbolTimeframeSelector symbol={symbol2} timeframe={tf2} onChangeSymbol={setSymbol2} onChangeTimeframe={setTf2} />
          {isConnected ? <span style={{ color: '#10b981' }}>● SSE</span> : <span style={{ color: '#ef4444' }}>● SSE</span>}
        </div>
        <SimpleKlineChart title={`${symbol2} — ${tf2} (SSE)`} data={data2.map(b => ({ ...b, time: b.time as any }))} />
      </div>
    </div>
  )
}
