import { useCallback, useEffect, useMemo, useState } from 'react'
import SimpleKlineChart from './SimpleKlineChart'
import WatchlistPanel, { useWatchlist } from './WatchlistPanel'
import { useSSEMultiplexer } from '@/hooks/useSSEMultiplexer'
import { marketDataApi } from '@/services/api'

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

export default function MultiChartSSEPanel() {
  const { symbols, setSymbols } = useWatchlist()
  const { isConnected, lastBySymbol } = useSSEMultiplexer(symbols, '1m')
  const [history, setHistory] = useState<Record<string, Bar[]>>({})
  const [lastBars, setLastBars] = useState<Record<string, Bar | undefined>>({})

  // Load initial 1m history for each symbol
  useEffect(() => {
    let cancelled = false
    ;(async () => {
      const next: Record<string, Bar[]> = {}
      for (const s of symbols) {
        try {
          const rows = await marketDataApi.getOHLCV(s, '1m', 1000)
          next[s] = rows.map(r => ({ time: r.time, open: r.open, high: r.high, low: r.low, close: r.close }))
        } catch {
          next[s] = []
        }
      }
      if (!cancelled) setHistory(next)
    })()
    return () => { cancelled = true }
  }, [symbols.join(',')])

  // Apply incoming SSE events to lastBars and extend history when a new minute closes
  useEffect(() => {
    const updated: Record<string, Bar | undefined> = {}
    const newHistory: Record<string, Bar[]> = { ...history }
    for (const [sym, evt] of Object.entries(lastBySymbol)) {
      if (!evt) continue
      const t = Math.floor(Date.parse(evt.close_time) / 1000)
      const bar: Bar = { time: t, open: evt.open, high: evt.high, low: evt.low, close: evt.close }
      updated[sym] = bar
      // Append or update last element of history if new minute
      const arr = newHistory[sym] || []
      if (arr.length && arr[arr.length - 1].time === bar.time) {
        arr[arr.length - 1] = bar
      } else if (!arr.length || arr[arr.length - 1].time < bar.time) {
        arr.push(bar)
        if (arr.length > 2000) arr.shift()
      }
      newHistory[sym] = arr
    }
    if (Object.keys(updated).length) {
      setLastBars(prev => ({ ...prev, ...updated }))
      setHistory(newHistory)
    }
  }, [lastBySymbol])

  const onWatchlistChange = useCallback((s: string[]) => setSymbols(s), [setSymbols])

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <WatchlistPanel onChange={onWatchlistChange} />
      <div className="card" style={{ padding: 8 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
          <span className="title">Live SSE Watchlist</span>
          {isConnected ? <span style={{ color: '#10b981' }}>● Connected</span> : <span style={{ color: '#ef4444' }}>● Disconnected</span>}
        </div>
        <div style={{ display: 'grid', gap: 16, gridTemplateColumns: '1fr', }}>
          {symbols.map(sym => (
            <SimpleKlineChart
              key={sym}
              title={`${sym} — 1m (SSE)`}
              data={(history[sym] || []).map(b => ({ time: b.time as any, open: b.open, high: b.high, low: b.low, close: b.close }))}
              lastBar={lastBars[sym] ? { ...lastBars[sym], time: lastBars[sym]!.time as any } : undefined}
            />
          ))}
        </div>
      </div>
    </div>
  )
}
