'use client'

import { useEffect, useState } from 'react'

interface AnalysisResult {
  name: string
  description: string
  status: 'loading' | 'success' | 'error'
  data: any
  recommendation?: string
  action?: string
}

export default function OptimizationPage() {
  const [analyses, setAnalyses] = useState<AnalysisResult[]>([])
  const [loading, setLoading] = useState(true)
  const [lastRefresh, setLastRefresh] = useState<Date | null>(null)

  const loadAnalyses = async () => {
    setLoading(true)
    try {
      const response = await fetch('/api/optimization/analyze')
      const data = await response.json()
      setAnalyses(data.analyses)
      setLastRefresh(new Date())
    } catch (error) {
      console.error('Failed to load analyses:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadAnalyses()
  }, [])

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 text-white p-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-4xl font-bold mb-2">🔬 Optimization Analytics Dashboard</h1>
              <p className="text-slate-400">
                Data-driven analysis for trading system improvements based on roadmaps and SQL queries
              </p>
            </div>
            <a
              href="/"
              className="px-4 py-2 bg-slate-700 hover:bg-slate-600 rounded-lg transition-colors flex items-center gap-2"
            >
              ← Home
            </a>
          </div>
          {lastRefresh && (
            <p className="text-sm text-slate-500 mt-2">
              Last refresh: {lastRefresh.toLocaleTimeString()}
            </p>
          )}
        </div>

        {/* Refresh Button */}
        <div className="mb-6">
          <button
            onClick={loadAnalyses}
            disabled={loading}
            className="px-6 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-slate-600 rounded-lg font-medium transition-colors"
          >
            {loading ? '🔄 Analyzing...' : '🔄 Refresh All Analyses'}
          </button>
        </div>

        {/* Loading State */}
        {loading && analyses.length === 0 && (
          <div className="text-center py-20">
            <div className="text-6xl mb-4">⏳</div>
            <p className="text-xl text-slate-400">Running SQL analyses...</p>
          </div>
        )}

        {/* Analysis Results */}
        <div className="space-y-6">
          {analyses.map((analysis, index) => (
            <AnalysisCard key={index} analysis={analysis} />
          ))}
        </div>

        {/* Roadmap Links */}
        <div className="mt-12 p-6 bg-slate-800/50 rounded-lg border border-slate-700">
          <h2 className="text-2xl font-bold mb-4">📚 Optimization Roadmaps</h2>
          <div className="grid md:grid-cols-3 gap-4">
            <RoadmapLink
              title="Signal Quality"
              file="SIGNAL_QUALITY_OPTIMIZATION_ROADMAP.md"
              status="Phase 1 - Collecting Data"
              progress="8/20 blocked signals"
            />
            <RoadmapLink
              title="Position Scaling"
              file="POSITION_SCALING_ROADMAP.md"
              status="Phase 1 - Data Collection"
              progress="Collecting MAE/MFE data"
            />
            <RoadmapLink
              title="ATR-Based Targets"
              file="ATR_BASED_TP_ROADMAP.md"
              status="Phase 1 - Collecting ATR"
              progress="Need 50+ trades"
            />
          </div>
        </div>
      </div>
    </div>
  )
}

function AnalysisCard({ analysis }: { analysis: AnalysisResult }) {
  const statusColors = {
    loading: 'border-yellow-500 bg-yellow-500/10',
    success: 'border-green-500 bg-green-500/10',
    error: 'border-red-500 bg-red-500/10'
  }

  const statusIcons = {
    loading: '⏳',
    success: '✅',
    error: '❌'
  }

  return (
    <div className={`p-6 rounded-lg border-2 ${statusColors[analysis.status]}`}>
      <div className="flex items-start justify-between mb-4">
        <div className="flex-1">
          <h3 className="text-xl font-bold mb-1 flex items-center gap-2">
            {statusIcons[analysis.status]} {analysis.name}
          </h3>
          <p className="text-sm text-slate-400">{analysis.description}</p>
        </div>
      </div>

      {/* Data Display */}
      {analysis.status === 'success' && analysis.data && (
        <div className="mt-4">
          {/* Table */}
          {Array.isArray(analysis.data) && analysis.data.length > 0 && (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-slate-700">
                    {Object.keys(analysis.data[0]).map(key => (
                      <th key={key} className="text-left py-2 px-3 font-medium text-slate-300">
                        {key}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {analysis.data.map((row: any, i: number) => (
                    <tr key={i} className="border-b border-slate-800">
                      {Object.values(row).map((value: any, j: number) => (
                        <td key={j} className="py-2 px-3">
                          {typeof value === 'number' ? value.toFixed(2) : String(value)}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {/* Summary Stats */}
          {typeof analysis.data === 'object' && !Array.isArray(analysis.data) && (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              {Object.entries(analysis.data).map(([key, value]) => (
                <div key={key} className="bg-slate-800/50 p-4 rounded">
                  <div className="text-xs text-slate-400 mb-1">{key}</div>
                  <div className="text-2xl font-bold">
                    {typeof value === 'number' ? value.toFixed(2) : String(value)}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Recommendation */}
      {analysis.recommendation && (
        <div className="mt-4 p-4 bg-blue-900/30 border border-blue-500/30 rounded-lg">
          <div className="text-sm font-medium text-blue-300 mb-1">💡 Recommendation</div>
          <p className="text-sm">{analysis.recommendation}</p>
        </div>
      )}

      {/* Action */}
      {analysis.action && (
        <div className="mt-4 p-4 bg-purple-900/30 border border-purple-500/30 rounded-lg">
          <div className="text-sm font-medium text-purple-300 mb-1">🎯 Action Required</div>
          <p className="text-sm">{analysis.action}</p>
        </div>
      )}

      {/* Error */}
      {analysis.status === 'error' && (
        <div className="mt-4 p-4 bg-red-900/30 border border-red-500/30 rounded-lg">
          <p className="text-sm text-red-300">{analysis.data?.error || 'Analysis failed'}</p>
        </div>
      )}
    </div>
  )
}

function RoadmapLink({ title, file, status, progress }: {
  title: string
  file: string
  status: string
  progress: string
}) {
  return (
    <div className="p-4 bg-slate-700/30 rounded-lg border border-slate-600 hover:border-slate-500 transition-colors">
      <h3 className="font-bold mb-2">{title}</h3>
      <p className="text-xs text-slate-400 mb-1">{status}</p>
      <p className="text-xs text-green-400">{progress}</p>
    </div>
  )
}
