"use client"
import React, { useState } from 'react'

const layouts = (process.env.NEXT_PUBLIC_TRADINGVIEW_LAYOUTS || 'ai,Diy module').split(',').map(l => l.trim())
const timeframes = [
  { label: '1m', value: '1' },
  { label: '5m', value: '5' },
  { label: '15m', value: '15' },
  { label: '1h', value: '60' },
  { label: '4h', value: '240' },
  { label: '1d', value: 'D' },
  { label: '1w', value: 'W' },
  { label: '1M', value: 'M' },
]

export default function AIAnalysisPanel() {
  const [symbol, setSymbol] = useState('BTCUSD')
  const [selectedLayouts, setSelectedLayouts] = useState<string[]>([layouts[0]])
  const [timeframe, setTimeframe] = useState('60')
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<any>(null)
  const [error, setError] = useState<string | null>(null)

  const toggleLayout = (layout: string) => {
    setSelectedLayouts(prev => 
      prev.includes(layout) 
        ? prev.filter(l => l !== layout)
        : [...prev, layout]
    )
  }

  async function handleAnalyze() {
    setLoading(true)
    setError(null)
    setResult(null)
    
    if (selectedLayouts.length === 0) {
      setError('Please select at least one layout')
      setLoading(false)
      return
    }

    try {
      const res = await fetch('/api/analyze', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ symbol, layouts: selectedLayouts, timeframe })
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error || 'Unknown error')
      setResult(data)
    } catch (e: any) {
      setError(e.message)
    }
    setLoading(false)
  }

  return (
    <div className="bg-gray-900 rounded-lg shadow p-6 mb-8">
      <h2 className="text-xl font-bold mb-4 text-white">AI Chart Analysis</h2>
      <div className="flex gap-2 mb-4">
        <input
          className="input input-bordered flex-1"
          value={symbol}
          onChange={e => setSymbol(e.target.value)}
          placeholder="Symbol (e.g. BTCUSD)"
        />
        <select
          className="input input-bordered"
          value={timeframe}
          onChange={e => setTimeframe(e.target.value)}
        >
          {timeframes.map(tf => <option key={tf.value} value={tf.value}>{tf.label}</option>)}
        </select>
        <button className="btn btn-primary" onClick={handleAnalyze} disabled={loading}>
          {loading ? 'Analyzing...' : 'Analyze'}
        </button>
      </div>
      
      {/* Layout selection */}
      <div className="mb-4">
        <label className="block text-sm font-medium text-gray-300 mb-2">
          Select Layouts for Analysis:
        </label>
        <div className="flex flex-wrap gap-2">
          {layouts.map(layout => (
            <label key={layout} className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={selectedLayouts.includes(layout)}
                onChange={() => toggleLayout(layout)}
                className="form-checkbox h-4 w-4 text-blue-600 rounded"
              />
              <span className="text-sm text-gray-300">{layout}</span>
            </label>
          ))}
        </div>
        {selectedLayouts.length > 0 && (
          <div className="text-xs text-gray-400 mt-1">
            Selected: {selectedLayouts.join(', ')}
          </div>
        )}
      </div>
      {error && (
        <div className="text-red-400 mb-2">
          {error.includes('frame was detached') ? (
            <>
              TradingView chart could not be loaded. Please check your symbol and layout, or try again.<br />
              <span className="text-xs">(Technical: {error})</span>
            </>
          ) : error.includes('layout not found') ? (
            <>
              TradingView layout not found. Please select a valid layout.<br />
              <span className="text-xs">(Technical: {error})</span>
            </>
          ) : (
            error
          )}
        </div>
      )}
      {loading && (
        <div className="flex items-center gap-2 text-gray-300 mb-2">
          <svg className="animate-spin h-5 w-5 text-blue-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path></svg>
          Analyzing chart...
        </div>
      )}
      {result && (
        <div className="bg-gray-800 rounded p-4 mt-4">
          {result.layoutsAnalyzed && (
            <div className="mb-3 text-sm text-gray-400">
              <b>Layouts analyzed:</b> {result.layoutsAnalyzed.join(', ')}
            </div>
          )}
          <div className="space-y-2">
            <div><b>Summary:</b> {result.summary}</div>
            <div><b>Sentiment:</b> {result.marketSentiment}</div>
            <div><b>Recommendation:</b> {result.recommendation} ({result.confidence}%)</div>
            <div><b>Support:</b> {result.keyLevels?.support?.join(', ')}</div>
            <div><b>Resistance:</b> {result.keyLevels?.resistance?.join(', ')}</div>
            <div><b>Reasoning:</b> {result.reasoning}</div>
          </div>
        </div>
      )}
    </div>
  )
}
