'use client';

import React, { useState } from 'react';
import Link from 'next/link';

const InsightsPage: React.FC = () => {
  const [selectedInsightType, setSelectedInsightType] = useState('performance');
  const [timeframe, setTimeframe] = useState('month');
  const [isGeneratingInsights, setIsGeneratingInsights] = useState(false);

  // Mock insights data
  const insightTypes = [
    {
      value: 'performance',
      label: 'Analisis Performa',
      description: 'Tren performa ujian dan identifikasi pola',
      icon: '📈'
    },
    {
      value: 'engagement',
      label: 'Tingkat Keterlibatan',
      description: 'Analisis aktivitas dan partisipasi pengguna',
      icon: '👥'
    },
    {
      value: 'difficulty',
      label: 'Analisis Kesulitan Soal',
      description: 'Evaluasi tingkat kesulitan dan efektivitas soal',
      icon: '🎯'
    },
    {
      value: 'trends',
      label: 'Tren & Prediksi',
      description: 'Prediksi performa dan tren masa depan',
      icon: '🔮'
    }
  ];

  const performanceInsights = {
    summary: {
      trend: 'improving',
      change: '+12.5%',
      period: 'bulan ini',
      score: 82.3
    },
    keyFindings: [
      {
        type: 'positive',
        title: 'Peningkatan Performa Signifikan',
        description: 'Rata-rata skor ujian meningkat 12.5% dibanding bulan lalu, menunjukkan efektivitas metode pembelajaran baru.',
        impact: 'high',
        recommendation: 'Pertahankan dan kembangkan metode pembelajaran yang telah terbukti efektif.'
      },
      {
        type: 'warning',
        title: 'Kesenjangan Performa Antar Kelas',
        description: 'Terdapat perbedaan signifikan antara kelas TI-A (avg: 87.2) dan TI-C (avg: 76.8).',
        impact: 'medium',
        recommendation: 'Berikan perhatian khusus dan dukungan tambahan untuk kelas dengan performa rendah.'
      },
      {
        type: 'neutral',
        title: 'Stabilitas Tingkat Kelulusan',
        description: 'Tingkat kelulusan konsisten di 85-87% selama 3 bulan terakhir.',
        impact: 'low',
        recommendation: 'Evaluasi standar kelulusan untuk memastikan tantangan yang tepat.'
      }
    ],
    detailedAnalysis: {
      topPerformers: [
        { name: 'Ahmad Fauzi', class: 'TI-A', avgScore: 94.2, improvement: '+8.5%' },
        { name: 'Siti Nurhaliza', class: 'TI-B', avgScore: 92.8, improvement: '+12.1%' },
        { name: 'Dewi Sartika', class: 'TI-A', avgScore: 91.5, improvement: '+6.3%' }
      ],
      strugglingStudents: [
        { name: 'Budi Santoso', class: 'TI-C', avgScore: 62.3, decline: '-5.2%' },
        { name: 'Eko Prasetyo', class: 'TI-C', avgScore: 65.8, decline: '-2.8%' },
        { name: 'Rina Wati', class: 'TI-B', avgScore: 68.1, decline: '-1.5%' }
      ],
      subjectPerformance: [
        { subject: 'Algoritma', avgScore: 88.5, trend: 'up', difficulty: 'medium' },
        { subject: 'Database', avgScore: 82.1, trend: 'stable', difficulty: 'medium' },
        { subject: 'Web Dev', avgScore: 79.3, trend: 'down', difficulty: 'hard' },
        { subject: 'Sistem Operasi', avgScore: 85.7, trend: 'up', difficulty: 'easy' }
      ]
    }
  };

  const engagementInsights = {
    summary: {
      activeUsers: 892,
      engagementRate: 78.5,
      avgSessionTime: '24 menit',
      trend: 'stable'
    },
    patterns: [
      {
        title: 'Pola Aktivitas Harian',
        description: 'Puncak aktivitas terjadi pada pukul 09:00-11:00 dan 19:00-21:00',
        data: [
          { hour: '08:00', activity: 45 },
          { hour: '09:00', activity: 89 },
          { hour: '10:00', activity: 95 },
          { hour: '11:00', activity: 87 },
          { hour: '19:00', activity: 92 },
          { hour: '20:00', activity: 88 },
          { hour: '21:00', activity: 76 }
        ]
      },
      {
        title: 'Engagement per Fitur',
        description: 'Tingkat penggunaan berbagai fitur sistem',
        data: [
          { feature: 'Ujian Online', usage: 95, satisfaction: 4.2 },
          { feature: 'Bank Soal', usage: 78, satisfaction: 4.0 },
          { feature: 'Hasil & Analisis', usage: 82, satisfaction: 4.3 },
          { feature: 'Forum Diskusi', usage: 34, satisfaction: 3.8 }
        ]
      }
    ]
  };

  const difficultyInsights = {
    overview: {
      totalQuestions: 2156,
      avgDifficulty: 2.8,
      successRate: 76.3,
      needsReview: 234
    },
    questionAnalysis: [
      {
        id: 'Q001',
        title: 'Implementasi Binary Search Tree',
        difficulty: 4.2,
        successRate: 34.5,
        attempts: 156,
        category: 'Algoritma',
        status: 'needs_review',
        recommendation: 'Soal terlalu sulit, pertimbangkan untuk menyederhanakan atau memberikan hint tambahan.'
      },
      {
        id: 'Q045',
        title: 'Konsep Normalisasi Database',
        difficulty: 2.1,
        successRate: 92.8,
        attempts: 142,
        category: 'Database',
        status: 'too_easy',
        recommendation: 'Soal terlalu mudah, tingkatkan kompleksitas untuk memberikan tantangan yang lebih baik.'
      },
      {
        id: 'Q078',
        title: 'Implementasi REST API',
        difficulty: 3.2,
        successRate: 78.5,
        attempts: 134,
        category: 'Web Development',
        status: 'optimal',
        recommendation: 'Tingkat kesulitan optimal, pertahankan soal ini.'
      }
    ],
    categoryAnalysis: [
      { category: 'Algoritma', avgDifficulty: 3.8, successRate: 68.2, questionCount: 456 },
      { category: 'Database', avgDifficulty: 2.9, successRate: 82.1, questionCount: 342 },
      { category: 'Web Development', avgDifficulty: 3.1, successRate: 75.6, questionCount: 389 },
      { category: 'Sistem Operasi', avgDifficulty: 2.7, successRate: 79.8, questionCount: 298 }
    ]
  };

  const trendsInsights = {
    predictions: [
      {
        metric: 'Rata-rata Skor',
        current: 82.3,
        predicted: 85.1,
        confidence: 87,
        timeframe: '3 bulan ke depan',
        factors: ['Peningkatan metode pembelajaran', 'Adaptasi mahasiswa terhadap sistem']
      },
      {
        metric: 'Tingkat Partisipasi',
        current: 89.2,
        predicted: 92.5,
        confidence: 78,
        timeframe: '2 bulan ke depan',
        factors: ['Implementasi gamifikasi', 'Peningkatan engagement']
      }
    ],
    seasonalTrends: [
      {
        period: 'Awal Semester',
        pattern: 'Partisipasi tinggi, performa sedang',
        recommendation: 'Fokus pada orientasi dan adaptasi sistem'
      },
      {
        period: 'Tengah Semester',
        pattern: 'Performa puncak, partisipasi stabil',
        recommendation: 'Waktu optimal untuk ujian penting'
      },
      {
        period: 'Akhir Semester',
        pattern: 'Stress tinggi, performa menurun',
        recommendation: 'Berikan dukungan tambahan dan fleksibilitas'
      }
    ]
  };

  const generateInsights = () => {
    setIsGeneratingInsights(true);
    setTimeout(() => {
      setIsGeneratingInsights(false);
      alert('Insights baru telah dihasilkan berdasarkan data terkini!');
    }, 2000);
  };

  const getInsightIcon = (type: string) => {
    const icons = {
      positive: '✅',
      warning: '⚠️',
      neutral: 'ℹ️',
      negative: '❌'
    };
    return icons[type as keyof typeof icons] || 'ℹ️';
  };

  const getImpactColor = (impact: string) => {
    const colors = {
      high: 'text-red-600 bg-red-100',
      medium: 'text-yellow-600 bg-yellow-100',
      low: 'text-green-600 bg-green-100'
    };
    return colors[impact as keyof typeof colors] || 'text-gray-600 bg-gray-100';
  };

  const getTrendIcon = (trend: string) => {
    const icons = {
      up: '📈',
      down: '📉',
      stable: '➡️',
      improving: '🚀',
      declining: '⬇️'
    };
    return icons[trend as keyof typeof icons] || '➡️';
  };

  const renderPerformanceInsights = () => (
    <div className="space-y-6">
      {/* Summary Card */}
      <div className="bg-gradient-to-r from-blue-500 to-purple-600 rounded-lg p-6 text-white">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-xl font-bold">Performa Keseluruhan</h3>
            <p className="text-blue-100">Analisis komprehensif performa sistem</p>
          </div>
          <div className="text-right">
            <div className="text-3xl font-bold">{performanceInsights.summary.score}</div>
            <div className="text-sm text-blue-100">
              {getTrendIcon(performanceInsights.summary.trend)} {performanceInsights.summary.change} {performanceInsights.summary.period}
            </div>
          </div>
        </div>
      </div>

      {/* Key Findings */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Temuan Utama</h3>
        <div className="space-y-4">
          {performanceInsights.keyFindings.map((finding, index) => (
            <div key={index} className="border border-gray-200 rounded-lg p-4">
              <div className="flex items-start space-x-3">
                <span className="text-xl">{getInsightIcon(finding.type)}</span>
                <div className="flex-1">
                  <div className="flex items-center justify-between mb-2">
                    <h4 className="font-medium text-gray-900">{finding.title}</h4>
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${getImpactColor(finding.impact)}`}>
                      {finding.impact === 'high' ? 'Tinggi' : finding.impact === 'medium' ? 'Sedang' : 'Rendah'}
                    </span>
                  </div>
                  <p className="text-sm text-gray-600 mb-2">{finding.description}</p>
                  <div className="bg-blue-50 p-3 rounded-lg">
                    <p className="text-sm text-blue-800">
                      <strong>Rekomendasi:</strong> {finding.recommendation}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Detailed Analysis */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Top Performers */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">🏆 Top Performers</h3>
          <div className="space-y-3">
            {performanceInsights.detailedAnalysis.topPerformers.map((student, index) => (
              <div key={index} className="flex items-center justify-between p-3 bg-green-50 rounded-lg">
                <div>
                  <div className="font-medium text-gray-900">{student.name}</div>
                  <div className="text-sm text-gray-600">{student.class}</div>
                </div>
                <div className="text-right">
                  <div className="font-bold text-green-600">{student.avgScore}</div>
                  <div className="text-xs text-green-500">{student.improvement}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Struggling Students */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">⚠️ Perlu Perhatian</h3>
          <div className="space-y-3">
            {performanceInsights.detailedAnalysis.strugglingStudents.map((student, index) => (
              <div key={index} className="flex items-center justify-between p-3 bg-red-50 rounded-lg">
                <div>
                  <div className="font-medium text-gray-900">{student.name}</div>
                  <div className="text-sm text-gray-600">{student.class}</div>
                </div>
                <div className="text-right">
                  <div className="font-bold text-red-600">{student.avgScore}</div>
                  <div className="text-xs text-red-500">{student.decline}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Subject Performance */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">📚 Performa per Mata Kuliah</h3>
        <div className="space-y-4">
          {performanceInsights.detailedAnalysis.subjectPerformance.map((subject, index) => (
            <div key={index} className="flex items-center justify-between p-4 border border-gray-200 rounded-lg">
              <div className="flex items-center space-x-3">
                <span className="text-lg">{getTrendIcon(subject.trend)}</span>
                <div>
                  <div className="font-medium text-gray-900">{subject.subject}</div>
                  <div className="text-sm text-gray-600">Kesulitan: {subject.difficulty}</div>
                </div>
              </div>
              <div className="text-right">
                <div className="font-bold text-gray-900">{subject.avgScore}</div>
                <div className="text-sm text-gray-600">Rata-rata</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );

  const renderCurrentInsights = () => {
    switch (selectedInsightType) {
      case 'performance':
        return renderPerformanceInsights();
      case 'engagement':
        return (
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Analisis Keterlibatan</h3>
            <p className="text-gray-600">Fitur analisis keterlibatan akan segera tersedia...</p>
          </div>
        );
      case 'difficulty':
        return (
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Analisis Kesulitan Soal</h3>
            <p className="text-gray-600">Fitur analisis kesulitan soal akan segera tersedia...</p>
          </div>
        );
      case 'trends':
        return (
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Tren & Prediksi</h3>
            <p className="text-gray-600">Fitur tren dan prediksi akan segera tersedia...</p>
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <div className="flex items-center space-x-2">
            <Link
              href="/admin/analytics"
              className="text-blue-600 hover:text-blue-800 transition-colors"
            >
              ← Analytics
            </Link>
            <span className="text-gray-400">/</span>
            <span className="text-gray-600">Insights</span>
          </div>
          <h1 className="text-2xl font-bold text-gray-900 mt-1">AI-Powered Insights</h1>
          <p className="text-gray-600">Analisis mendalam dan rekomendasi berbasis data</p>
        </div>
        <div className="flex items-center space-x-3">
          <select
            value={timeframe}
            onChange={(e) => setTimeframe(e.target.value)}
            className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          >
            <option value="week">Minggu Ini</option>
            <option value="month">Bulan Ini</option>
            <option value="quarter">Kuartal Ini</option>
            <option value="year">Tahun Ini</option>
          </select>
          <button
            onClick={generateInsights}
            disabled={isGeneratingInsights}
            className={`px-4 py-2 rounded-lg font-medium transition-colors ${
              isGeneratingInsights
                ? 'bg-gray-400 text-white cursor-not-allowed'
                : 'bg-blue-600 text-white hover:bg-blue-700'
            }`}
          >
            {isGeneratingInsights ? (
              <div className="flex items-center space-x-2">
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                <span>Generating...</span>
              </div>
            ) : (
              '🔄 Refresh Insights'
            )}
          </button>
        </div>
      </div>

      {/* Insight Type Selection */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">Pilih Jenis Analisis</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {insightTypes.map((type) => (
            <div
              key={type.value}
              className={`p-4 border rounded-lg cursor-pointer transition-colors ${
                selectedInsightType === type.value
                  ? 'border-blue-500 bg-blue-50'
                  : 'border-gray-200 hover:border-gray-300'
              }`}
              onClick={() => setSelectedInsightType(type.value)}
            >
              <div className="text-center">
                <div className="text-3xl mb-2">{type.icon}</div>
                <div className="font-medium text-gray-900">{type.label}</div>
                <div className="text-sm text-gray-600 mt-1">{type.description}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Insights Content */}
      {renderCurrentInsights()}

      {/* AI Recommendations */}
      <div className="bg-gradient-to-r from-purple-500 to-pink-500 rounded-lg p-6 text-white">
        <div className="flex items-start space-x-4">
          <div className="text-4xl">🤖</div>
          <div>
            <h3 className="text-xl font-bold mb-2">Rekomendasi AI</h3>
            <div className="space-y-2 text-purple-100">
              <p>• Implementasikan sistem reminder otomatis untuk meningkatkan partisipasi ujian</p>
              <p>• Berikan feedback real-time untuk soal dengan tingkat kesulitan tinggi</p>
              <p>• Pertimbangkan sistem adaptive learning berdasarkan performa individual</p>
              <p>• Optimalkan jadwal ujian berdasarkan pola aktivitas mahasiswa</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default InsightsPage;