'use client'
import React, { useEffect, useRef, useState } from 'react'

export default function DebugChart() {
  const chartContainerRef = useRef<HTMLDivElement>(null)
  const [logs, setLogs] = useState<string[]>([])
  const [error, setError] = useState<string | null>(null)

  const addLog = (message: string) => {
    console.log(message)
    setLogs(prev => [...prev, `${new Date().toLocaleTimeString()}: ${message}`])
  }

  useEffect(() => {
    addLog('Component mounted')
    
    if (!chartContainerRef.current) {
      addLog('ERROR: No chart container ref')
      return
    }

    addLog('Chart container found')

    const initChart = async () => {
      try {
        addLog('Starting chart initialization...')
        
        addLog('Importing lightweight-charts...')
        const LightweightChartsModule = await import('lightweight-charts')
        addLog('Import successful')
        
        addLog('Available exports: ' + Object.keys(LightweightChartsModule).join(', '))
        
        const { createChart, ColorType, CrosshairMode } = LightweightChartsModule
        addLog('Extracted createChart and other components')
        
        addLog('Creating chart...')
        const chart = createChart(chartContainerRef.current!, {
          width: 600,
          height: 300,
          layout: {
            textColor: '#ffffff',
            background: { color: '#1a1a1a' },
          },
        })
        addLog('Chart created successfully')

        addLog('Adding candlestick series...')
        const candlestickSeries = chart.addCandlestickSeries({
          upColor: '#26a69a',
          downColor: '#ef5350',
        })
        addLog('Series added successfully')

        addLog('Generating test data...')
        const data = [
          { time: '2025-07-10', open: 100, high: 110, low: 95, close: 105 },
          { time: '2025-07-11', open: 105, high: 115, low: 100, close: 110 },
          { time: '2025-07-12', open: 110, high: 120, low: 105, close: 115 },
          { time: '2025-07-13', open: 115, high: 125, low: 110, close: 118 },
          { time: '2025-07-14', open: 118, high: 128, low: 113, close: 122 },
          { time: '2025-07-15', open: 122, high: 132, low: 117, close: 125 },
          { time: '2025-07-16', open: 125, high: 135, low: 120, close: 130 },
        ]
        addLog(`Generated ${data.length} data points`)

        addLog('Setting data on series...')
        candlestickSeries.setData(data)
        addLog('Data set successfully - chart should be visible!')

        addLog('Chart initialization complete')

      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : String(err)
        const errorStack = err instanceof Error ? err.stack : 'No stack trace'
        addLog(`ERROR: ${errorMessage}`)
        console.error('Chart initialization error:', err)
        setError(`${errorMessage}\n\nStack: ${errorStack}`)
      }
    }

    initChart()
  }, [])

  return (
    <div className="min-h-screen bg-gray-900 p-8">
      <h1 className="text-white text-2xl mb-4">Debug Chart Test</h1>
      
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <div>
          <h2 className="text-white text-lg mb-2">Chart</h2>
          <div 
            ref={chartContainerRef} 
            className="bg-gray-800 border border-gray-600 rounded"
            style={{ width: '600px', height: '300px' }}
          />
        </div>

        <div>
          <h2 className="text-white text-lg mb-2">Debug Logs</h2>
          <div className="bg-gray-800 p-4 rounded h-80 overflow-y-auto">
            {logs.map((log, index) => (
              <div key={index} className="text-gray-300 text-sm font-mono mb-1">
                {log}
              </div>
            ))}
          </div>
          
          {error && (
            <div className="mt-4 bg-red-900/20 border border-red-500 p-4 rounded">
              <h3 className="text-red-400 font-semibold mb-2">Error Details:</h3>
              <pre className="text-red-300 text-xs whitespace-pre-wrap">{error}</pre>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
