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

interface LearningData {
  totalAnalyses: number
  totalTrades: number
  avgAccuracy: number
  winRate: number
  confidenceLevel: number
  phase: string
  phaseDescription: string
  strengths: string[]
  improvements: string[]
  nextMilestone: string
  recommendation: string
  daysActive: number
}

interface LearningInsights {
  totalAnalyses: number
  avgAccuracy: number
  bestTimeframe: string
  worstTimeframe: string
  recommendations: string[]
}

export default function CompleteLearningPage() {
  const [learningData, setLearningData] = useState<LearningData | null>(null)
  const [learningInsights, setLearningInsights] = useState<LearningInsights | null>(null)
  const [loading, setLoading] = useState(true)
  const [lastRefresh, setLastRefresh] = useState<Date>(new Date())

  // Auto-refresh every 30 seconds
  useEffect(() => {
    fetchLearningData()
    
    const interval = setInterval(() => {
      fetchLearningData()
    }, 30000)
    
    return () => clearInterval(interval)
  }, [])

  const fetchLearningData = async () => {
    try {
      setLoading(true)
      
      // Fetch AI learning status
      const [statusResponse, insightsResponse] = await Promise.all([
        fetch('/api/ai-learning-status'),
        fetch('/api/automation/learning-insights')
      ])
      
      if (statusResponse.ok) {
        const statusData = await statusResponse.json()
        if (statusData.success) {
          setLearningData(statusData.data)
        }
      }
      
      if (insightsResponse.ok) {
        const insightsData = await insightsResponse.json()
        if (insightsData.success) {
          setLearningInsights(insightsData.insights)
        }
      }
      
      setLastRefresh(new Date())
    } catch (error) {
      console.error('Failed to fetch learning data:', error)
    } finally {
      setLoading(false)
    }
  }

  const getPhaseColor = (phase: string) => {
    switch (phase) {
      case 'EXPERT': return 'text-green-400'
      case 'ADVANCED': return 'text-blue-400'
      case 'PATTERN_RECOGNITION': return 'text-yellow-400'
      default: return 'text-gray-400'
    }
  }

  const getPhaseIcon = (phase: string) => {
    switch (phase) {
      case 'EXPERT': return '🚀'
      case 'ADVANCED': return '🌳'
      case 'PATTERN_RECOGNITION': return '🌿'
      default: return '🌱'
    }
  }

  if (loading && !learningData) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900 p-6">
        <div className="max-w-6xl mx-auto">
          <div className="flex items-center justify-center py-20">
            <div className="spinner border-blue-500"></div>
            <span className="ml-3 text-white">Loading comprehensive learning data...</span>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900 p-6">
      <div className="max-w-6xl mx-auto space-y-6">
        
        {/* Header */}
        <div className="text-center mb-8">
          <h1 className="text-4xl font-bold text-white mb-4">🧠 Complete AI Learning Status</h1>
          <p className="text-gray-300 text-lg">Comprehensive overview of your AI's learning progress and capabilities</p>
          <div className="text-sm text-gray-400 mt-2">
            Last updated: {lastRefresh.toLocaleTimeString()} 
            <span className="ml-3 text-blue-400">⟳ Auto-refreshes every 30 seconds</span>
          </div>
        </div>

        {/* Quick Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6 text-center">
            <div className="text-3xl font-bold text-blue-400">{learningData?.totalAnalyses || 0}</div>
            <div className="text-gray-300 text-sm">Total Analyses</div>
          </div>
          <div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6 text-center">
            <div className="text-3xl font-bold text-green-400">{learningData?.totalTrades || 0}</div>
            <div className="text-gray-300 text-sm">Total Trades</div>
          </div>
          <div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6 text-center">
            <div className="text-3xl font-bold text-purple-400">{((learningData?.avgAccuracy || 0) * 100).toFixed(1)}%</div>
            <div className="text-gray-300 text-sm">Avg Accuracy</div>
          </div>
          <div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6 text-center">
            <div className="text-3xl font-bold text-yellow-400">{((learningData?.winRate || 0) * 100).toFixed(1)}%</div>
            <div className="text-gray-300 text-sm">Win Rate</div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          
          {/* AI Learning Phase */}
          {learningData && (
            <div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6">
              <h2 className="text-2xl font-bold text-white mb-6 flex items-center">
                <span className="mr-3">{getPhaseIcon(learningData.phase)}</span>
                AI Learning Phase
              </h2>
              
              <div className="space-y-6">
                {/* Current Phase */}
                <div className="text-center">
                  <div className={`text-3xl font-bold ${getPhaseColor(learningData.phase)} mb-2`}>
                    {learningData.phase}
                  </div>
                  <div className="text-white text-lg mb-4">{learningData.phaseDescription}</div>
                  <div className="text-gray-300 text-sm">Active for {learningData.daysActive} days</div>
                </div>

                {/* Performance Metrics */}
                <div className="grid grid-cols-2 gap-4">
                  <div className="text-center bg-gray-700/30 rounded-lg p-3">
                    <div className="text-xl font-bold text-white">{learningData.confidenceLevel.toFixed(1)}%</div>
                    <div className="text-xs text-gray-400">Confidence Level</div>
                  </div>
                  <div className="text-center bg-gray-700/30 rounded-lg p-3">
                    <div className="text-xl font-bold text-white">{((learningData.avgAccuracy || 0) * 100).toFixed(1)}%</div>
                    <div className="text-xs text-gray-400">Accuracy</div>
                  </div>
                </div>

                {/* Next Milestone */}
                <div className="bg-blue-900/20 border border-blue-600/30 rounded-lg p-4">
                  <div className="text-sm font-medium text-blue-400 mb-2">Next Milestone</div>
                  <div className="text-white">{learningData.nextMilestone}</div>
                </div>

                {/* AI Recommendation */}
                <div className="bg-green-900/20 border border-green-600/30 rounded-lg p-4">
                  <div className="text-sm font-medium text-green-400 mb-2">AI Recommendation</div>
                  <div className="text-white text-sm">{learningData.recommendation}</div>
                </div>
              </div>
            </div>
          )}

          {/* Strengths & Improvements */}
          {learningData && (
            <div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6">
              <h2 className="text-2xl font-bold text-white mb-6">📈 Performance Analysis</h2>
              
              <div className="grid grid-cols-1 gap-6">
                {/* Strengths */}
                <div>
                  <h3 className="text-green-400 font-semibold mb-3 flex items-center">
                    <span className="mr-2">✅</span>
                    Current Strengths
                  </h3>
                  <ul className="space-y-2">
                    {learningData.strengths.map((strength, idx) => (
                      <li key={idx} className="text-sm text-gray-300 flex items-start">
                        <span className="text-green-400 mr-2 mt-0.5">✓</span>
                        {strength}
                      </li>
                    ))}
                  </ul>
                </div>

                {/* Improvements */}
                <div>
                  <h3 className="text-yellow-400 font-semibold mb-3 flex items-center">
                    <span className="mr-2">🎯</span>
                    Areas for Improvement
                  </h3>
                  <ul className="space-y-2">
                    {learningData.improvements.map((improvement, idx) => (
                      <li key={idx} className="text-sm text-gray-300 flex items-start">
                        <span className="text-yellow-400 mr-2 mt-0.5">•</span>
                        {improvement}
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </div>
          )}

          {/* Learning Insights */}
          {learningInsights && (
            <div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6">
              <h2 className="text-2xl font-bold text-white mb-6">🎯 Learning Insights</h2>
              
              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">Total Analyses:</span>
                  <span className="text-white font-semibold">{learningInsights.totalAnalyses}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">Avg Accuracy:</span>
                  <span className="text-white font-semibold">{(learningInsights.avgAccuracy * 100).toFixed(1)}%</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">Best Timeframe:</span>
                  <span className="text-green-400 font-semibold">{learningInsights.bestTimeframe}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">Worst Timeframe:</span>
                  <span className="text-red-400 font-semibold">{learningInsights.worstTimeframe}</span>
                </div>
                
                {learningInsights.recommendations.length > 0 && (
                  <div className="mt-6">
                    <h4 className="text-lg font-semibold text-white mb-3">💡 AI Recommendations</h4>
                    <ul className="space-y-2">
                      {learningInsights.recommendations.map((rec, idx) => (
                        <li key={idx} className="text-sm text-gray-300 flex items-start">
                          <span className="text-blue-400 mr-2 mt-0.5">💡</span>
                          {rec}
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Refresh Control */}
          <div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6">
            <h2 className="text-2xl font-bold text-white mb-6">🔄 Data Controls</h2>
            
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-gray-300">Auto Refresh:</span>
                <span className="text-green-400 font-semibold">Every 30 seconds</span>
              </div>
              
              <div className="flex items-center justify-between">
                <span className="text-gray-300">Last Updated:</span>
                <span className="text-blue-400 font-semibold">{lastRefresh.toLocaleTimeString()}</span>
              </div>
              
              <button
                onClick={fetchLearningData}
                disabled={loading}
                className="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 text-white font-semibold py-3 px-4 rounded-lg transition-colors duration-200 flex items-center justify-center"
              >
                {loading ? (
                  <>
                    <div className="spinner border-white mr-2"></div>
                    Refreshing...
                  </>
                ) : (
                  <>
                    <span className="mr-2">🔄</span>
                    Refresh Now
                  </>
                )}
              </button>
              
              <div className="text-xs text-gray-400 text-center mt-2">
                Data refreshes automatically to show the latest AI learning progress
              </div>
            </div>
          </div>
        </div>

        {/* Status Messages */}
        {!learningData && !loading && (
          <div className="bg-yellow-900/20 border border-yellow-600/30 rounded-lg p-4 text-center">
            <div className="text-yellow-400 font-semibold mb-2">⚠️ No Learning Data Available</div>
            <div className="text-gray-300 text-sm">
              The AI hasn't started learning yet. Run some analyses to see learning progress here.
            </div>
          </div>
        )}

        {/* Footer Info */}
        <div className="text-center text-gray-400 text-sm border-t border-gray-700 pt-6">
          <p>This page automatically refreshes every 30 seconds to show real-time AI learning progress.</p>
          <p className="mt-1">Navigate to <span className="text-blue-400">/automation</span> to start the AI learning process.</p>
        </div>
      </div>

      <style jsx>{`
        .spinner {
          width: 16px;
          height: 16px;
          border: 2px solid transparent;
          border-top: 2px solid currentColor;
          border-radius: 50%;
          animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  )
}
