'use client'

import { useState, useEffect } from 'react'
import type { TrumpPost, BotTrade, BotPerformance, Candle } from '@/types'
import { useDashboardStore } from '@/store/dashboard'
import { usePriceSocket } from '@/lib/useRealtimeData'
import { getPrices } from '@/lib/api'
import KpiRow from '@/components/dashboard/KpiRow'
import ChartPanel from '@/components/dashboard/ChartPanel'
import BotPanel from '@/components/dashboard/BotPanel'
import TradesTable from '@/components/trades/TradesTable'

interface Props {
  initialPosts: TrumpPost[]
  initialPerformance?: BotPerformance
  initialTrades: BotTrade[]
}

export default function DashboardClient({ initialPosts, initialPerformance, initialTrades }: Props) {
  const { asset, timeframe, setLivePrice } = useDashboardStore()
  const [posts, setPosts] = useState<TrumpPost[]>(initialPosts)
  const [candles, setCandles] = useState<Candle[]>([])
  const [candlesLoading, setCandlesLoading] = useState(false)

  usePriceSocket({
    onPrice: (a, price) => setLivePrice(a, price),
    onNewPost: (post) => setPosts((prev) => [post as TrumpPost, ...prev].slice(0, 50)),
  })

  useEffect(() => {
    setCandles([])
    setCandlesLoading(true)
    getPrices(asset, timeframe)
      .then(setCandles)
      .catch(() => {})
      .finally(() => setCandlesLoading(false))
  }, [asset, timeframe])

  return (
    <div className="pt-14">
      <div className="max-w-[1400px] mx-auto px-6 py-6 flex flex-col gap-4">
        {/* KPI 行 */}
        <KpiRow performance={initialPerformance} postsCount={posts.length} />

        {/* 主内容区：图表 + Bot 面板 */}
        <div className="flex gap-4 items-start w-full">
          <div className="flex-1 min-w-0 relative">
            <ChartPanel posts={posts} candles={candles} />
            {candlesLoading && (
              <div className="absolute inset-0 flex items-center justify-center bg-black/40 rounded-[10px] pointer-events-none">
                <span className="text-[#555555] text-sm">Loading...</span>
              </div>
            )}
          </div>
          <div className="w-[280px] shrink-0">
            <BotPanel performance={initialPerformance} />
          </div>
        </div>

        {/* 交易记录 */}
        <TradesTable trades={initialTrades} />
      </div>
    </div>
  )
}
