import { useEffect, useRef, useState, Fragment } from 'react'
import { tvInterval, TIMEFRAMES } from '@/lib/assets'
import { useTradingStore } from '@/store/tradingStore'
import { useStore } from '@/store'

const TV_SRC = 'https://s3.tradingview.com/tv.js'
let scriptPromise = null

function loadTradingViewScript() {
  if (window.TradingView) return Promise.resolve()
  if (scriptPromise) return scriptPromise

  scriptPromise = new Promise((resolve, reject) => {
    const existing = document.querySelector(`script[src="${TV_SRC}"]`)
    if (existing) {
      existing.addEventListener('load', () => resolve())
      existing.addEventListener('error', () => reject(new Error('Failed to load tv.js')))
      return
    }
    const s = document.createElement('script')
    s.src = TV_SRC
    s.async = true
    s.onload = () => resolve()
    s.onerror = () => reject(new Error('Failed to load tv.js'))
    document.head.appendChild(s)
  })
  return scriptPromise
}

function useIsMobile() {
  const [mobile, setMobile] = useState(() => window.innerWidth < 768)
  useEffect(() => {
    const check = () => setMobile(window.innerWidth < 768)
    window.addEventListener('resize', check)
    return () => window.removeEventListener('resize', check)
  }, [])
  return mobile
}

let CONTAINER_ID_SEQ = 0

function LivePnL({ trade }) {
  const [timeLeft, setTimeLeft] = useState(0)
  const [elapsed, setElapsed] = useState(0)

  useEffect(() => {
    const tick = () => {
      const now = Date.now()
      const total = trade.expiresAt - trade.placedAt
      const remaining = Math.max(0, trade.expiresAt - now)
      setTimeLeft(Math.ceil(remaining / 1000))
      setElapsed(total > 0 ? (now - trade.placedAt) / total : 0)
    }
    tick()
    const id = setInterval(tick, 1000)
    return () => clearInterval(id)
  }, [trade])

  const potentialProfit = trade.amount * (trade.payout / 100)

  return (
    <div style={{
      position: 'absolute',
      top: '60px',
      right: '90px',
      zIndex: 100,
      pointerEvents: 'none',
      background: 'rgba(10,14,26,0.9)',
      border: '1px solid rgba(255,255,255,0.1)',
      borderRadius: '8px',
      padding: '8px 12px',
      fontSize: '12px',
      color: '#F0F4FF',
      minWidth: '140px',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
        <span style={{ color: '#6B7A9F' }}>Profit if wins</span>
        <span style={{ color: '#00E676' }}>+${potentialProfit.toFixed(2)}</span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>
        <span style={{ color: '#6B7A9F' }}>Time left</span>
        <span style={{ color: timeLeft < 10 ? '#FF3D57' : '#F0F4FF' }}>{timeLeft}s</span>
      </div>
      <div style={{ background: 'rgba(255,255,255,0.1)', borderRadius: '2px', height: '3px' }}>
        <div style={{
          width: Math.min(100, elapsed * 100) + '%',
          height: '100%',
          background: timeLeft < 10 ? '#FF3D57' : '#00E676',
          borderRadius: '2px',
          transition: 'width 1s linear',
        }} />
      </div>
    </div>
  )
}

export function TradingChart({ tvSymbol, tf, containerId }) {
  const containerRef = useRef(null)
  const widgetRef    = useRef(null)
  const idRef        = useRef(containerId ?? `tv_chart_${++CONTAINER_ID_SEQ}`)
  const [hoveredTf, setHoveredTf] = useState(null)

  const isMobile = useIsMobile()
  const { selectedAsset, setTimeframe } = useTradingStore()
  const active = useStore((s) => s.active)
  const chartTrades = active.filter((t) => t.asset === selectedAsset?.symbol)

  useEffect(() => {
    const onResize = () => {
      if (widgetRef.current?.resize && containerRef.current) {
        widgetRef.current.resize(containerRef.current.clientWidth, containerRef.current.clientHeight)
      }
    }
    window.addEventListener('resize', onResize)
    return () => window.removeEventListener('resize', onResize)
  }, [])

  useEffect(() => {
    let cancelled = false

    const mount = async () => {
      try { await loadTradingViewScript() } catch { return }
      if (cancelled || !window.TradingView || !containerRef.current) return

      if (widgetRef.current?.remove) {
        try { widgetRef.current.remove() } catch { /* ignore */ }
        widgetRef.current = null
      }
      containerRef.current.innerHTML = ''

      const DISABLED = [
        'header_symbol_search','header_compare','header_undo_redo','header_saveload',
        'header_screenshot','header_widget','header_toolbar_intervals','header_toolbar_chart_type',
        'header_toolbar_indicators','header_toolbar_settings','header_toolbar_fullscreen_button',
        'header_indicators','header_chart_type','header_resolutions','header_interval_dialog_button',
        'show_interval_dialog_on_key_press','timeframes_toolbar','legend_widget','left_toolbar',
        'context_menus','edit_buttons_in_legend','control_bar','border_around_the_chart',
        'volume_force_overlay','create_volume_indicator_by_default','go_to_date','symbol_info',
        'chart_property_page_trading','source_selection_markers','display_market_status',
      ]

      widgetRef.current = new window.TradingView.widget({
        autosize: true,
        container_id: idRef.current,
        symbol: tvSymbol,
        interval: tvInterval(tf),
        theme: 'dark',
        style: '1',
        locale: 'en',
        toolbar_bg: '#0A0E1A',
        enable_publishing: false,
        save_image: false,
        hide_side_toolbar: true,
        disabled_features: DISABLED,
        studies: [],
        studies_overrides: {},
        charts_storage_url: null,
        overrides: {
          'paneProperties.background': '#0A0E1A',
          'paneProperties.backgroundType': 'solid',
          'scalesProperties.backgroundColor': '#0A0E1A',
          'paneProperties.legendProperties.showLegend': false,
          'paneProperties.legendProperties.showStudyArguments': false,
          'paneProperties.legendProperties.showStudyTitles': false,
          'paneProperties.legendProperties.showStudyValues': false,
          'paneProperties.legendProperties.showSeriesTitle': false,
          'paneProperties.legendProperties.showSeriesOHLC': false,
          'paneProperties.legendProperties.showBarChange': false,
          'paneProperties.legendProperties.showOnlyPriceSource': false,
        },
      })
    }

    mount().then(() => {
      if (!cancelled && widgetRef.current?.resize && containerRef.current) {
        widgetRef.current.resize(containerRef.current.clientWidth, containerRef.current.clientHeight)
      }
    })

    return () => {
      cancelled = true
      if (widgetRef.current?.remove) {
        try { widgetRef.current.remove() } catch { /* ignore */ }
        widgetRef.current = null
      }
      if (containerRef.current) containerRef.current.innerHTML = ''
    }
  }, [tvSymbol, tf, isMobile])

  const overlayBase = {
    position: 'absolute',
    zIndex: 10000,
    pointerEvents: 'none',
    background: '#0A0E1A',
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', width: '100%', height: '100%' }}>
      <div style={{
        display: 'flex',
        gap: 4,
        padding: '6px 8px',
        background: '#0A0E1A',
        borderBottom: '1px solid rgba(255,255,255,0.06)',
        flexShrink: 0,
      }}>
        {TIMEFRAMES.map((t) => (
          <button
            key={t}
            onClick={() => setTimeframe(t)}
            onMouseEnter={() => setHoveredTf(t)}
            onMouseLeave={() => setHoveredTf(null)}
            style={{
              color: tf === t ? '#000000' : '#FFFFFF',
              background: tf === t ? '#00E676' : hoveredTf === t ? 'rgba(255,255,255,0.08)' : 'transparent',
              border: '1px solid ' + (tf === t ? '#00E676' : 'rgba(255,255,255,0.2)'),
              borderRadius: 6,
              padding: '3px 10px',
              fontSize: 12,
              cursor: 'pointer',
              fontWeight: tf === t ? 600 : 400,
            }}
          >
            {t}
          </button>
        ))}
      </div>

      <div style={{ position: 'relative', flex: 1, minHeight: 0 }}>
        <div id={idRef.current} ref={containerRef} style={{ width: '100%', height: '100%' }} />

        {chartTrades.map((trade) => (
          <Fragment key={trade.id}>
            {/* Entry price badge — right side only, no horizontal line */}
            <div style={{
              position: 'absolute',
              right: '82px',
              top: '45%',
              zIndex: 100,
              pointerEvents: 'none',
              background: '#FFD700',
              color: '#000',
              fontSize: '11px',
              fontWeight: '700',
              padding: '2px 6px',
              borderRadius: '3px',
              whiteSpace: 'nowrap',
            }}>
              ── {trade.entryPrice?.toFixed(5)}
            </div>
            {/* Direction badge */}
            <div style={{
              position: 'absolute',
              top: '62px',
              left: '12px',
              zIndex: 100,
              pointerEvents: 'none',
            }}>
              <div style={{
                background: trade.dir === 'UP' ? 'rgba(0,230,118,0.15)' : 'rgba(255,61,87,0.15)',
                border: '1px solid ' + (trade.dir === 'UP' ? '#00E676' : '#FF3D57'),
                borderRadius: '8px',
                padding: '6px 10px',
                fontSize: '12px',
                color: trade.dir === 'UP' ? '#00E676' : '#FF3D57',
                display: 'flex',
                alignItems: 'center',
                gap: '6px',
              }}>
                <span>{trade.dir === 'UP' ? '↑ UP' : '↓ DOWN'}</span>
                <span style={{ color: '#888', fontSize: '11px' }}>
                  ${trade.amount} · {Math.round(trade.duration / 1000)}s
                </span>
              </div>
            </div>
            {/* Live P&L countdown */}
            <LivePnL trade={trade} />
          </Fragment>
        ))}

        {isMobile ? (
          <>
            <div style={{ ...overlayBase, left: 0, top: 0, width: 'calc(100% - 60px)', height: 56 }} />
            <div style={{ ...overlayBase, left: 0, top: 0, width: 1, height: '100%' }} />
            <div style={{ ...overlayBase, bottom: 0, left: 0, width: '100%', height: 52 }} />
          </>
        ) : (
          <>
            <div style={{ ...overlayBase, top: 0, left: 0, width: 'calc(100% - 80px)', height: 60 }} />
            <div style={{ ...overlayBase, bottom: 0, left: 0, width: 180, height: 52 }} />
            <div style={{ ...overlayBase, right: 0, top: 0, width: 1, height: '100%' }} />
          </>
        )}
      </div>
    </div>
  )
}
