'use client';

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

const AnalyticsPage: React.FC = () => {
  const [dateRange, setDateRange] = useState('30');
  const [selectedMetric, setSelectedMetric] = useState('overview');

  // Mock analytics data
  const analyticsData = {
    overview: {
      totalUsers: 1247,
      totalExams: 89,
      totalQuestions: 2156,
      averageScore: 78.5,
      completionRate: 85.2,
      activeUsers: 892
    },
    examStats: {
      totalExams: 89,
      completedExams: 76,
      ongoingExams: 8,
      scheduledExams: 5,
      averageScore: 78.5,
      passRate: 82.1
    },
    userStats: {
      totalStudents: 1198,
      totalAdmins: 49,
      activeToday: 234,
      newThisMonth: 67,
      loginRate: 89.3
    },
    questionStats: {
      totalQuestions: 2156,
      multipleChoice: 1543,
      essay: 456,
      trueFalse: 157,
      averageDifficulty: 2.8
    }
  };

  // Mock chart data
  const examPerformanceData = [
    { month: 'Jan', score: 75, participants: 120 },
    { month: 'Feb', score: 78, participants: 135 },
    { month: 'Mar', score: 82, participants: 142 },
    { month: 'Apr', score: 79, participants: 128 },
    { month: 'May', score: 85, participants: 156 },
    { month: 'Jun', score: 83, participants: 149 }
  ];

  const userGrowthData = [
    { month: 'Jan', users: 980, active: 756 },
    { month: 'Feb', users: 1045, active: 812 },
    { month: 'Mar', users: 1123, active: 889 },
    { month: 'Apr', users: 1187, active: 934 },
    { month: 'May', users: 1234, active: 967 },
    { month: 'Jun', users: 1247, active: 892 }
  ];

  const topPerformingExams = [
    { id: '1', title: 'Teknik Dasar Memasak', avgScore: 92.5, participants: 156, passRate: 94.2 },
    { id: '2', title: 'Food Safety & Hygiene', avgScore: 88.3, participants: 142, passRate: 89.4 },
    { id: '3', title: 'Kuliner Internasional', avgScore: 85.7, participants: 134, passRate: 86.6 },
    { id: '4', title: 'Pastry & Bakery', avgScore: 82.1, participants: 128, passRate: 82.8 },
    { id: '5', title: 'Menu Planning & Costing', avgScore: 79.4, participants: 119, passRate: 78.2 }
  ];

  const recentActivities = [
    {
      id: '1',
      type: 'exam_completed',
      title: 'Ujian Teknik Dasar Memasak selesai',
      description: '23 peserta menyelesaikan ujian',
      timestamp: '2024-01-15T10:30:00',
      score: 85.2
    },
    {
      id: '2',
      type: 'user_registered',
      title: 'Peserta baru terdaftar',
      description: '5 peserta pelatihan baru bergabung',
      timestamp: '2024-01-15T09:15:00'
    },
    {
      id: '3',
      type: 'exam_created',
      title: 'Ujian baru dibuat',
      description: 'Quiz Food Safety & Hygiene',
      timestamp: '2024-01-15T08:45:00'
    },
    {
      id: '4',
      type: 'high_score',
      title: 'Skor tinggi dicapai',
      description: 'Andi Wijaya - 98/100 pada Ujian Teknik Dasar Memasak',
      timestamp: '2024-01-15T08:20:00'
    }
  ];

  const formatNumber = (num: number) => {
    return new Intl.NumberFormat('id-ID').format(num);
  };

  const formatPercentage = (num: number) => {
    return `${num.toFixed(1)}%`;
  };

  const formatDateTime = (dateString: string) => {
    return new Date(dateString).toLocaleString('id-ID', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const getActivityIcon = (type: string) => {
    const icons = {
      exam_completed: '✅',
      user_registered: '👤',
      exam_created: '📝',
      high_score: '🏆',
      system: '⚙️'
    };
    return icons[type as keyof typeof icons] || '📊';
  };

  const getScoreColor = (score: number) => {
    if (score >= 90) return 'text-green-600';
    if (score >= 80) return 'text-blue-600';
    if (score >= 70) return 'text-yellow-600';
    return 'text-red-600';
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Analytics & Reports</h1>
          <p className="text-gray-600 mt-1">Dashboard analitik dan laporan sistem pelatihan Dapur MBG</p>
        </div>
        <div className="flex items-center space-x-3">
          <select
            value={dateRange}
            onChange={(e) => setDateRange(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="7">7 Hari Terakhir</option>
            <option value="30">30 Hari Terakhir</option>
            <option value="90">3 Bulan Terakhir</option>
            <option value="365">1 Tahun Terakhir</option>
          </select>
          <Link
            href="/admin/analytics/reports"
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            📊 Generate Report
          </Link>
        </div>
      </div>

      {/* Key Metrics */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-6">
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-blue-600">{formatNumber(analyticsData.overview.totalUsers)}</div>
          <div className="text-sm text-gray-600">Total Pengguna</div>
          <div className="text-xs text-green-600 mt-1">↗ +5.2% dari bulan lalu</div>
        </div>
        
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-green-600">{formatNumber(analyticsData.overview.totalExams)}</div>
          <div className="text-sm text-gray-600">Total Ujian</div>
          <div className="text-xs text-green-600 mt-1">↗ +12.8% dari bulan lalu</div>
        </div>
        
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-purple-600">{formatNumber(analyticsData.overview.totalQuestions)}</div>
          <div className="text-sm text-gray-600">Total Soal</div>
          <div className="text-xs text-green-600 mt-1">↗ +8.4% dari bulan lalu</div>
        </div>
        
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-orange-600">{analyticsData.overview.averageScore.toFixed(1)}</div>
          <div className="text-sm text-gray-600">Rata-rata Nilai</div>
          <div className="text-xs text-green-600 mt-1">↗ +2.1% dari bulan lalu</div>
        </div>
        
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-teal-600">{formatPercentage(analyticsData.overview.completionRate)}</div>
          <div className="text-sm text-gray-600">Tingkat Penyelesaian</div>
          <div className="text-xs text-green-600 mt-1">↗ +3.7% dari bulan lalu</div>
        </div>
        
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-indigo-600">{formatNumber(analyticsData.overview.activeUsers)}</div>
          <div className="text-sm text-gray-600">Pengguna Aktif</div>
          <div className="text-xs text-green-600 mt-1">↗ +7.3% dari bulan lalu</div>
        </div>
      </div>

      {/* Charts Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Exam Performance Chart */}
        <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">Performa Ujian (6 Bulan Terakhir)</h2>
          <div className="space-y-4">
            {examPerformanceData.map((data, index) => (
              <div key={index} className="flex items-center justify-between">
                <div className="flex items-center space-x-3">
                  <div className="w-12 text-sm text-gray-600">{data.month}</div>
                  <div className="flex-1">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm font-medium text-gray-900">Rata-rata: {data.score}</span>
                      <span className="text-xs text-gray-500">{data.participants} peserta</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div
                        className="bg-blue-600 h-2 rounded-full"
                        style={{ width: `${(data.score / 100) * 100}%` }}
                      ></div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* User Growth Chart */}
        <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">Pertumbuhan Pengguna</h2>
          <div className="space-y-4">
            {userGrowthData.map((data, index) => (
              <div key={index} className="flex items-center justify-between">
                <div className="flex items-center space-x-3">
                  <div className="w-12 text-sm text-gray-600">{data.month}</div>
                  <div className="flex-1">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm font-medium text-gray-900">Total: {formatNumber(data.users)}</span>
                      <span className="text-xs text-gray-500">Aktif: {formatNumber(data.active)}</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div
                        className="bg-green-600 h-2 rounded-full"
                        style={{ width: `${(data.active / data.users) * 100}%` }}
                      ></div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Top Performing Exams & Recent Activities */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Top Performing Exams */}
        <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">Ujian Terbaik</h2>
          <div className="space-y-4">
            {topPerformingExams.map((exam, index) => (
              <div key={exam.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                <div className="flex items-center space-x-3">
                  <div className="flex-shrink-0 w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                    <span className="text-sm font-bold text-blue-600">#{index + 1}</span>
                  </div>
                  <div>
                    <div className="text-sm font-medium text-gray-900">{exam.title}</div>
                    <div className="text-xs text-gray-500">{exam.participants} peserta</div>
                  </div>
                </div>
                <div className="text-right">
                  <div className={`text-sm font-bold ${getScoreColor(exam.avgScore)}`}>
                    {exam.avgScore.toFixed(1)}
                  </div>
                  <div className="text-xs text-gray-500">{formatPercentage(exam.passRate)} lulus</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Recent Activities */}
        <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">Aktivitas Terbaru</h2>
          <div className="space-y-4">
            {recentActivities.map((activity) => (
              <div key={activity.id} className="flex items-start space-x-3">
                <div className="flex-shrink-0 w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                  <span className="text-sm">{getActivityIcon(activity.type)}</span>
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between">
                    <p className="text-sm font-medium text-gray-900 truncate">
                      {activity.title}
                    </p>
                    <span className="text-xs text-gray-500">
                      {formatDateTime(activity.timestamp)}
                    </span>
                  </div>
                  <p className="text-sm text-gray-600">{activity.description}</p>
                  {activity.score && (
                    <p className={`text-xs font-medium ${getScoreColor(activity.score)}`}>
                      Skor: {activity.score}
                    </p>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Detailed Statistics */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {/* Exam Statistics */}
        <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">Statistik Ujian</h3>
          <div className="space-y-3">
            <div className="flex justify-between">
              <span className="text-gray-600">Total Ujian:</span>
              <span className="font-medium">{analyticsData.examStats.totalExams}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Selesai:</span>
              <span className="font-medium text-green-600">{analyticsData.examStats.completedExams}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Berlangsung:</span>
              <span className="font-medium text-yellow-600">{analyticsData.examStats.ongoingExams}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Terjadwal:</span>
              <span className="font-medium text-blue-600">{analyticsData.examStats.scheduledExams}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Tingkat Kelulusan:</span>
              <span className="font-medium">{formatPercentage(analyticsData.examStats.passRate)}</span>
            </div>
          </div>
        </div>

        {/* User Statistics */}
        <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">Statistik Pengguna</h3>
          <div className="space-y-3">
            <div className="flex justify-between">
              <span className="text-gray-600">Mahasiswa:</span>
              <span className="font-medium">{formatNumber(analyticsData.userStats.totalStudents)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Admin:</span>
              <span className="font-medium">{analyticsData.userStats.totalAdmins}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Aktif Hari Ini:</span>
              <span className="font-medium text-green-600">{analyticsData.userStats.activeToday}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Baru Bulan Ini:</span>
              <span className="font-medium text-blue-600">{analyticsData.userStats.newThisMonth}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Tingkat Login:</span>
              <span className="font-medium">{formatPercentage(analyticsData.userStats.loginRate)}</span>
            </div>
          </div>
        </div>

        {/* Question Statistics */}
        <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">Statistik Soal</h3>
          <div className="space-y-3">
            <div className="flex justify-between">
              <span className="text-gray-600">Total Soal:</span>
              <span className="font-medium">{formatNumber(analyticsData.questionStats.totalQuestions)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Pilihan Ganda:</span>
              <span className="font-medium">{formatNumber(analyticsData.questionStats.multipleChoice)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Essay:</span>
              <span className="font-medium">{formatNumber(analyticsData.questionStats.essay)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Benar/Salah:</span>
              <span className="font-medium">{formatNumber(analyticsData.questionStats.trueFalse)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600">Rata-rata Kesulitan:</span>
              <span className="font-medium">{analyticsData.questionStats.averageDifficulty}/5</span>
            </div>
          </div>
        </div>
      </div>

      {/* Quick Actions */}
      <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">Aksi Cepat</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <Link
            href="/admin/analytics/reports"
            className="p-4 bg-blue-50 rounded-lg border border-blue-200 hover:bg-blue-100 transition-colors group"
          >
            <div className="flex items-center space-x-3">
              <div className="p-2 bg-blue-100 rounded-lg group-hover:bg-blue-200 transition-colors">
                📊
              </div>
              <div>
                <h3 className="font-semibold text-blue-900">Generate Report</h3>
                <p className="text-sm text-blue-700">Buat laporan custom</p>
              </div>
            </div>
          </Link>

          <Link
            href="/admin/analytics/export"
            className="p-4 bg-green-50 rounded-lg border border-green-200 hover:bg-green-100 transition-colors group"
          >
            <div className="flex items-center space-x-3">
              <div className="p-2 bg-green-100 rounded-lg group-hover:bg-green-200 transition-colors">
                📤
              </div>
              <div>
                <h3 className="font-semibold text-green-900">Export Data</h3>
                <p className="text-sm text-green-700">Download data analytics</p>
              </div>
            </div>
          </Link>

          <Link
            href="/admin/analytics/insights"
            className="p-4 bg-purple-50 rounded-lg border border-purple-200 hover:bg-purple-100 transition-colors group"
          >
            <div className="flex items-center space-x-3">
              <div className="p-2 bg-purple-100 rounded-lg group-hover:bg-purple-200 transition-colors">
                🧠
              </div>
              <div>
                <h3 className="font-semibold text-purple-900">AI Insights</h3>
                <p className="text-sm text-purple-700">Analisis mendalam</p>
              </div>
            </div>
          </Link>

          <Link
            href="/admin/analytics/settings"
            className="p-4 bg-gray-50 rounded-lg border border-gray-200 hover:bg-gray-100 transition-colors group"
          >
            <div className="flex items-center space-x-3">
              <div className="p-2 bg-gray-100 rounded-lg group-hover:bg-gray-200 transition-colors">
                ⚙️
              </div>
              <div>
                <h3 className="font-semibold text-gray-900">Settings</h3>
                <p className="text-sm text-gray-700">Konfigurasi analytics</p>
              </div>
            </div>
          </Link>
        </div>
      </div>
    </div>
  );
};

export default AnalyticsPage;