'use client'

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

/**
 * AI Learning Dashboard
 * 
 * Beautiful dashboard to display stop loss decision learning insights
 */

interface LearningInsights {
  success: boolean
  timestamp: string
  learningSystem: {
    status: string
    confidence: string
    totalDecisions: number
    pendingAssessments: number
    currentThresholds: {
      emergency: number
      risk: number
      mediumRisk: number
    }
    lastAnalysis: any
  }
  decisionPatterns: {
    successful: Array<{
      decisionType: string
      successRate: number
      avgScore: number
      sampleSize: number
    }>
    failures: Array<{
      decisionType: string
      successRate: number
      sampleSize: number
    }>
    optimalTiming: any
    distanceOptimization: any
  }
  performanceMetrics: {
    overallSuccessRate: number
    mostSuccessfulDecision: {
      type: string
      rate: string
      samples: number
    }
    improvementTrend: string
    confidenceLevel: number
  }
  recommendations: Array<{
    type: string
    priority: string
    message: string
    actionable: boolean
  }>
  systemHealth: {
    learningActive: boolean
    dataQuality: string
    systemMaturity: string
    readyForAutonomy: boolean
  }
}

export default function AILearningDashboard() {
  const [insights, setInsights] = useState<LearningInsights | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null)

  useEffect(() => {
    fetchLearningInsights()
    const interval = setInterval(fetchLearningInsights, 30000) // Update every 30 seconds
    return () => clearInterval(interval)
  }, [])

  const fetchLearningInsights = async () => {
    try {
      const response = await fetch('/api/ai/learning')
      const data = await response.json()
      
      if (data.success) {
        setInsights(data)
        setError(null)
        setLastUpdate(new Date())
      } else {
        setError(data.error || 'Failed to load learning insights')
      }
    } catch (err: any) {
      setError(err.message || 'Network error')
    } finally {
      setLoading(false)
    }
  }

  const triggerAction = async (action: string, parameters?: any) => {
    try {
      const response = await fetch('/api/ai/learning', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action, parameters })
      })
      
      const result = await response.json()
      if (result.success) {
        fetchLearningInsights() // Refresh data
      }
    } catch (err) {
      console.error('Action failed:', err)
    }
  }

  if (loading) {
    return (
      <div className="bg-gray-900 border border-gray-700 rounded-lg p-6">
        <div className="animate-pulse space-y-4">
          <div className="h-4 bg-gray-700 rounded w-1/4"></div>
          <div className="h-8 bg-gray-700 rounded w-1/2"></div>
          <div className="h-32 bg-gray-700 rounded"></div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="bg-red-900/20 border border-red-700 rounded-lg p-6">
        <div className="flex items-center space-x-2">
          <span className="text-red-400">❌</span>
          <h3 className="text-red-400 font-semibold">Learning System Error</h3>
        </div>
        <p className="text-red-300 mt-2">{error}</p>
        <button 
          onClick={fetchLearningInsights}
          className="mt-4 px-4 py-2 bg-red-700 hover:bg-red-600 rounded text-white transition-colors"
        >
          Retry
        </button>
      </div>
    )
  }

  if (!insights) return null

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'ACTIVE': return 'text-green-400'
      case 'INACTIVE': return 'text-red-400'
      default: return 'text-yellow-400'
    }
  }

  const getMaturityColor = (maturity: string) => {
    switch (maturity) {
      case 'EXPERT': return 'text-purple-400'
      case 'INTERMEDIATE': return 'text-blue-400'
      case 'NOVICE': return 'text-green-400'
      case 'BEGINNER': return 'text-yellow-400'
      default: return 'text-gray-400'
    }
  }

  const getDataQualityColor = (quality: string) => {
    switch (quality) {
      case 'HIGH': return 'text-green-400'
      case 'MEDIUM': return 'text-yellow-400'
      case 'LOW': return 'text-orange-400'
      default: return 'text-red-400'
    }
  }

  const getTrendIcon = (trend: string) => {
    switch (trend) {
      case 'EXCELLENT': return '🚀'
      case 'IMPROVING': return '📈'
      case 'LEARNING': return '🧠'
      case 'INITIALIZING': return '🌱'
      default: return '❓'
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="bg-gray-900 border border-gray-700 rounded-lg p-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold text-white flex items-center space-x-2">
              <span>🧠</span>
              <span>AI Learning Dashboard</span>
            </h2>
            <p className="text-gray-400 mt-1">Stop Loss Decision Learning System</p>
          </div>
          <div className="text-right">
            <div className={`text-lg font-semibold ${getStatusColor(insights.learningSystem.status)}`}>
              {insights.learningSystem.status}
            </div>
            <div className="text-sm text-gray-400">
              Last Update: {lastUpdate?.toLocaleTimeString()}
            </div>
          </div>
        </div>
      </div>

      {/* System Overview */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-gray-900 border border-gray-700 rounded-lg p-4">
          <div className="text-gray-400 text-sm">System Confidence</div>
          <div className="text-2xl font-bold text-blue-400">{insights.learningSystem.confidence}</div>
          <div className="text-xs text-gray-500 mt-1">
            {getTrendIcon(insights.performanceMetrics.improvementTrend)} {insights.performanceMetrics.improvementTrend}
          </div>
        </div>

        <div className="bg-gray-900 border border-gray-700 rounded-lg p-4">
          <div className="text-gray-400 text-sm">Total Decisions</div>
          <div className="text-2xl font-bold text-green-400">{insights.learningSystem.totalDecisions}</div>
          <div className="text-xs text-gray-500 mt-1">
            Pending: {insights.learningSystem.pendingAssessments}
          </div>
        </div>

        <div className="bg-gray-900 border border-gray-700 rounded-lg p-4">
          <div className="text-gray-400 text-sm">Success Rate</div>
          <div className="text-2xl font-bold text-purple-400">{insights.performanceMetrics.overallSuccessRate}%</div>
          <div className="text-xs text-gray-500 mt-1">
            Best: {insights.performanceMetrics.mostSuccessfulDecision.type}
          </div>
        </div>

        <div className="bg-gray-900 border border-gray-700 rounded-lg p-4">
          <div className="text-gray-400 text-sm">System Maturity</div>
          <div className={`text-2xl font-bold ${getMaturityColor(insights.systemHealth.systemMaturity)}`}>
            {insights.systemHealth.systemMaturity}
          </div>
          <div className="text-xs text-gray-500 mt-1">
            Quality: <span className={getDataQualityColor(insights.systemHealth.dataQuality)}>
              {insights.systemHealth.dataQuality}
            </span>
          </div>
        </div>
      </div>

      {/* Learning Thresholds */}
      <div className="bg-gray-900 border border-gray-700 rounded-lg p-6">
        <h3 className="text-lg font-semibold text-white mb-4 flex items-center space-x-2">
          <span>🎯</span>
          <span>Current Learning Thresholds</span>
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-red-900/20 border border-red-700 rounded-lg p-4">
            <div className="text-red-400 font-semibold">🚨 Emergency</div>
            <div className="text-2xl font-bold text-white">{insights.learningSystem.currentThresholds.emergency}%</div>
            <div className="text-sm text-red-300">Immediate action required</div>
          </div>
          <div className="bg-yellow-900/20 border border-yellow-700 rounded-lg p-4">
            <div className="text-yellow-400 font-semibold">⚠️ High Risk</div>
            <div className="text-2xl font-bold text-white">{insights.learningSystem.currentThresholds.risk}%</div>
            <div className="text-sm text-yellow-300">Enhanced monitoring</div>
          </div>
          <div className="bg-blue-900/20 border border-blue-700 rounded-lg p-4">
            <div className="text-blue-400 font-semibold">🟡 Medium Risk</div>
            <div className="text-2xl font-bold text-white">{insights.learningSystem.currentThresholds.mediumRisk}%</div>
            <div className="text-sm text-blue-300">Standard monitoring</div>
          </div>
        </div>
      </div>

      {/* Decision Patterns */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Successful Patterns */}
        <div className="bg-gray-900 border border-gray-700 rounded-lg p-6">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center space-x-2">
            <span>✅</span>
            <span>Successful Decision Patterns</span>
          </h3>
          <div className="space-y-3">
            {insights.decisionPatterns.successful.length > 0 ? (
              insights.decisionPatterns.successful.map((pattern, index) => (
                <div key={index} className="bg-green-900/20 border border-green-700 rounded-lg p-3">
                  <div className="flex justify-between items-center">
                    <div className="text-green-400 font-semibold">{pattern.decisionType}</div>
                    <div className="text-green-300">{pattern.successRate.toFixed(1)}%</div>
                  </div>
                  <div className="text-sm text-gray-400">
                    Sample Size: {pattern.sampleSize} | Avg Score: {pattern.avgScore.toFixed(2)}
                  </div>
                </div>
              ))
            ) : (
              <div className="text-gray-400 text-center py-8">
                No successful patterns identified yet
                <br />
                <span className="text-sm">Keep making decisions to build learning data</span>
              </div>
            )}
          </div>
        </div>

        {/* Failure Patterns */}
        <div className="bg-gray-900 border border-gray-700 rounded-lg p-6">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center space-x-2">
            <span>❌</span>
            <span>Areas for Improvement</span>
          </h3>
          <div className="space-y-3">
            {insights.decisionPatterns.failures.length > 0 ? (
              insights.decisionPatterns.failures.map((pattern, index) => (
                <div key={index} className="bg-red-900/20 border border-red-700 rounded-lg p-3">
                  <div className="flex justify-between items-center">
                    <div className="text-red-400 font-semibold">{pattern.decisionType}</div>
                    <div className="text-red-300">{pattern.successRate.toFixed(1)}%</div>
                  </div>
                  <div className="text-sm text-gray-400">
                    Sample Size: {pattern.sampleSize} | Needs improvement
                  </div>
                </div>
              ))
            ) : (
              <div className="text-gray-400 text-center py-8">
                No failure patterns identified
                <br />
                <span className="text-sm text-green-400">Great! System is performing well</span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Recommendations */}
      {insights.recommendations.length > 0 && (
        <div className="bg-gray-900 border border-gray-700 rounded-lg p-6">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center space-x-2">
            <span>💡</span>
            <span>AI Recommendations</span>
          </h3>
          <div className="space-y-3">
            {insights.recommendations.map((rec, index) => (
              <div key={index} className={`rounded-lg p-3 border ${
                rec.priority === 'HIGH' ? 'bg-red-900/20 border-red-700' :
                rec.priority === 'MEDIUM' ? 'bg-yellow-900/20 border-yellow-700' :
                'bg-blue-900/20 border-blue-700'
              }`}>
                <div className="flex justify-between items-start">
                  <div className={`text-sm font-semibold ${
                    rec.priority === 'HIGH' ? 'text-red-400' :
                    rec.priority === 'MEDIUM' ? 'text-yellow-400' :
                    'text-blue-400'
                  }`}>
                    {rec.type} - {rec.priority} PRIORITY
                  </div>
                  {rec.actionable && (
                    <span className="text-xs bg-green-700 text-green-200 px-2 py-1 rounded">
                      Actionable
                    </span>
                  )}
                </div>
                <div className="text-gray-300 mt-1">{rec.message}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* System Health */}
      <div className="bg-gray-900 border border-gray-700 rounded-lg p-6">
        <h3 className="text-lg font-semibold text-white mb-4 flex items-center space-x-2">
          <span>🏥</span>
          <span>System Health</span>
        </h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="text-center">
            <div className={`text-2xl ${insights.systemHealth.learningActive ? 'text-green-400' : 'text-red-400'}`}>
              {insights.systemHealth.learningActive ? '🟢' : '🔴'}
            </div>
            <div className="text-sm text-gray-400">Learning Active</div>
          </div>
          <div className="text-center">
            <div className={`text-2xl ${getDataQualityColor(insights.systemHealth.dataQuality)}`}>
              📊
            </div>
            <div className="text-sm text-gray-400">Data Quality</div>
            <div className={`text-xs ${getDataQualityColor(insights.systemHealth.dataQuality)}`}>
              {insights.systemHealth.dataQuality}
            </div>
          </div>
          <div className="text-center">
            <div className={`text-2xl ${getMaturityColor(insights.systemHealth.systemMaturity)}`}>
              🎓
            </div>
            <div className="text-sm text-gray-400">Maturity</div>
            <div className={`text-xs ${getMaturityColor(insights.systemHealth.systemMaturity)}`}>
              {insights.systemHealth.systemMaturity}
            </div>
          </div>
          <div className="text-center">
            <div className={`text-2xl ${insights.systemHealth.readyForAutonomy ? 'text-green-400' : 'text-yellow-400'}`}>
              {insights.systemHealth.readyForAutonomy ? '🚀' : '⚠️'}
            </div>
            <div className="text-sm text-gray-400">Beach Ready</div>
            <div className={`text-xs ${insights.systemHealth.readyForAutonomy ? 'text-green-400' : 'text-yellow-400'}`}>
              {insights.systemHealth.readyForAutonomy ? 'YES' : 'LEARNING'}
            </div>
          </div>
        </div>
      </div>

      {/* Action Buttons */}
      <div className="bg-gray-900 border border-gray-700 rounded-lg p-6">
        <h3 className="text-lg font-semibold text-white mb-4 flex items-center space-x-2">
          <span>⚡</span>
          <span>Learning System Actions</span>
        </h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <button
            onClick={() => triggerAction('updateThresholds')}
            className="px-4 py-2 bg-blue-700 hover:bg-blue-600 rounded text-white transition-colors"
          >
            🔄 Update Thresholds
          </button>
          <button
            onClick={() => triggerAction('generateReport')}
            className="px-4 py-2 bg-green-700 hover:bg-green-600 rounded text-white transition-colors"
          >
            📊 Generate Report
          </button>
          <button
            onClick={() => triggerAction('assessPendingDecisions')}
            className="px-4 py-2 bg-yellow-700 hover:bg-yellow-600 rounded text-white transition-colors"
          >
            ⚖️ Assess Pending
          </button>
          <button
            onClick={fetchLearningInsights}
            className="px-4 py-2 bg-purple-700 hover:bg-purple-600 rounded text-white transition-colors"
          >
            🔃 Refresh Data
          </button>
        </div>
      </div>
    </div>
  )
}
