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

export default function ChartDebug() {
  const chartContainerRef = useRef<HTMLDivElement>(null)
  const [logs, setLogs] = useState<string[]>([])
  const [chartCreated, setChartCreated] = useState(false)

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

  useEffect(() => {
    if (!chartContainerRef.current) {
      addLog('Chart container ref not available')
      return
    }

    const initChart = async () => {
      try {
        addLog('Starting chart initialization...')

        // Dynamic import to avoid SSR issues
        addLog('Importing lightweight-charts...')
        const LightweightChartsModule = await import('lightweight-charts')
        addLog('Import successful')
        
        addLog('Available exports: ' + Object.keys(LightweightChartsModule).join(', '))
        
        const { createChart } = LightweightChartsModule
        addLog('Extracted createChart')

        // Create chart with minimal options
        const chart = createChart(chartContainerRef.current!, {
          width: 600,
          height: 300,
        })
        addLog('Chart created successfully')
        setChartCreated(true)

        // Check what methods are available on the chart
        const chartMethods = Object.getOwnPropertyNames(Object.getPrototypeOf(chart))
        addLog('Chart methods: ' + chartMethods.slice(0, 10).join(', ') + '...')

        // Try to add a candlestick series using the modern API
        let candlestickSeries;
        if ('addCandlestickSeries' in chart) {
          addLog('Using addCandlestickSeries method')
          candlestickSeries = (chart as any).addCandlestickSeries({
            upColor: '#26a69a',
            downColor: '#ef5350',
            borderDownColor: '#ef5350',
            borderUpColor: '#26a69a',
            wickDownColor: '#ef5350',
            wickUpColor: '#26a69a',
          })
        } else {
          addLog('Trying alternative API')
          candlestickSeries = (chart as any).addAreaSeries({
            lineColor: '#26a69a',
            topColor: 'rgba(38, 166, 154, 0.4)',
            bottomColor: 'rgba(38, 166, 154, 0.0)',
          })
        }
        addLog('Candlestick series added')

        // Very simple test data
        const testData = [
          { time: '2023-01-01', open: 100, high: 110, low: 95, close: 105 },
          { time: '2023-01-02', open: 105, high: 115, low: 100, close: 110 },
          { time: '2023-01-03', open: 110, high: 120, low: 105, close: 115 },
          { time: '2023-01-04', open: 115, high: 125, low: 110, close: 120 },
          { time: '2023-01-05', open: 120, high: 130, low: 115, close: 125 },
        ]
        
        addLog(`Setting data with ${testData.length} points`)
        candlestickSeries.setData(testData)
        addLog('Data set successfully - chart should be visible now')

        // Cleanup function
        return () => {
          addLog('Cleaning up chart')
          chart.remove()
        }

      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error)
        addLog(`Error: ${errorMessage}`)
        console.error('Chart error:', error)
      }
    }

    initChart()
  }, [])

  return (
    <div className="min-h-screen bg-gray-900 p-8">
      <h1 className="text-white text-2xl mb-4">Chart Debug Test</h1>
      
      <div className="mb-4">
        <h2 className="text-white text-lg mb-2">Status</h2>
        <div className="text-gray-400">
          Chart Created: {chartCreated ? '✅ Yes' : '❌ No'}
        </div>
      </div>

      <div className="mb-4">
        <h2 className="text-white text-lg mb-2">Chart Container</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 max-h-60 overflow-y-auto">
          {logs.map((log, index) => (
            <div key={index} className="text-gray-300 text-sm font-mono">
              {log}
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
