'use client';

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

const ReportsPage: React.FC = () => {
  const [reportType, setReportType] = useState('exam_performance');
  const [dateRange, setDateRange] = useState('30');
  const [customStartDate, setCustomStartDate] = useState('');
  const [customEndDate, setCustomEndDate] = useState('');
  const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
  const [selectedExams, setSelectedExams] = useState<string[]>([]);
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [exportFormat, setExportFormat] = useState('pdf');
  const [isGenerating, setIsGenerating] = useState(false);
  const [generatedReports, setGeneratedReports] = useState<any[]>([]);

  // Mock data
  const reportTypes = [
    { value: 'exam_performance', label: 'Performa Ujian', description: 'Analisis hasil dan statistik ujian' },
    { value: 'user_activity', label: 'Aktivitas Pengguna', description: 'Laporan login dan aktivitas pengguna' },
    { value: 'question_analysis', label: 'Analisis Soal', description: 'Statistik tingkat kesulitan dan jawaban' },
    { value: 'attendance', label: 'Kehadiran', description: 'Laporan kehadiran ujian dan partisipasi' },
    { value: 'grade_distribution', label: 'Distribusi Nilai', description: 'Analisis sebaran nilai dan ranking' },
    { value: 'system_usage', label: 'Penggunaan Sistem', description: 'Statistik penggunaan fitur dan modul' }
  ];

  const mockUsers = [
    { id: '1', name: 'Ahmad Fauzi', nim: '2021001', class: 'TI-A' },
    { id: '2', name: 'Siti Nurhaliza', nim: '2021002', class: 'TI-A' },
    { id: '3', name: 'Budi Santoso', nim: '2021003', class: 'TI-B' },
    { id: '4', name: 'Dewi Sartika', nim: '2021004', class: 'TI-B' },
    { id: '5', name: 'Eko Prasetyo', nim: '2021005', class: 'TI-C' }
  ];

  const mockExams = [
    { id: '1', title: 'Algoritma dan Struktur Data', date: '2024-01-10' },
    { id: '2', title: 'Database Management', date: '2024-01-12' },
    { id: '3', title: 'Pemrograman Web', date: '2024-01-15' },
    { id: '4', title: 'Sistem Operasi', date: '2024-01-18' },
    { id: '5', title: 'Jaringan Komputer', date: '2024-01-20' }
  ];

  const mockCategories = [
    { id: '1', name: 'Algoritma' },
    { id: '2', name: 'Database' },
    { id: '3', name: 'Web Development' },
    { id: '4', name: 'Sistem' },
    { id: '5', name: 'Jaringan' }
  ];

  const mockGeneratedReports = [
    {
      id: '1',
      title: 'Laporan Performa Ujian - Januari 2024',
      type: 'exam_performance',
      generatedAt: '2024-01-15T10:30:00',
      format: 'pdf',
      size: '2.3 MB',
      status: 'completed'
    },
    {
      id: '2',
      title: 'Aktivitas Pengguna - Desember 2023',
      type: 'user_activity',
      generatedAt: '2024-01-10T14:20:00',
      format: 'excel',
      size: '1.8 MB',
      status: 'completed'
    },
    {
      id: '3',
      title: 'Analisis Soal - Q4 2023',
      type: 'question_analysis',
      generatedAt: '2024-01-05T09:15:00',
      format: 'pdf',
      size: '3.1 MB',
      status: 'completed'
    }
  ];

  const handleGenerateReport = async () => {
    setIsGenerating(true);
    
    // Simulate report generation
    setTimeout(() => {
      const newReport = {
        id: Date.now().toString(),
        title: `${reportTypes.find(t => t.value === reportType)?.label} - ${new Date().toLocaleDateString('id-ID')}`,
        type: reportType,
        generatedAt: new Date().toISOString(),
        format: exportFormat,
        size: `${(Math.random() * 3 + 1).toFixed(1)} MB`,
        status: 'completed'
      };
      
      setGeneratedReports([newReport, ...generatedReports]);
      setIsGenerating(false);
      
      // Auto download simulation
      alert(`Laporan "${newReport.title}" berhasil dibuat dan sedang diunduh...`);
    }, 3000);
  };

  const handleUserSelection = (userId: string) => {
    setSelectedUsers(prev => 
      prev.includes(userId) 
        ? prev.filter(id => id !== userId)
        : [...prev, userId]
    );
  };

  const handleExamSelection = (examId: string) => {
    setSelectedExams(prev => 
      prev.includes(examId) 
        ? prev.filter(id => id !== examId)
        : [...prev, examId]
    );
  };

  const handleCategorySelection = (categoryId: string) => {
    setSelectedCategories(prev => 
      prev.includes(categoryId) 
        ? prev.filter(id => id !== categoryId)
        : [...prev, categoryId]
    );
  };

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

  const getReportTypeIcon = (type: string) => {
    const icons = {
      exam_performance: '📊',
      user_activity: '👥',
      question_analysis: '❓',
      attendance: '✅',
      grade_distribution: '📈',
      system_usage: '💻'
    };
    return icons[type as keyof typeof icons] || '📄';
  };

  const getFormatIcon = (format: string) => {
    const icons = {
      pdf: '📄',
      excel: '📊',
      csv: '📋',
      json: '🔧'
    };
    return icons[format as keyof typeof icons] || '📄';
  };

  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">Reports</span>
          </div>
          <h1 className="text-2xl font-bold text-gray-900 mt-1">Generate Reports</h1>
          <p className="text-gray-600">Buat laporan custom dengan filter dan format yang diinginkan</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Report Configuration */}
        <div className="lg:col-span-2 space-y-6">
          {/* Report 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">Jenis Laporan</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {reportTypes.map((type) => (
                <div
                  key={type.value}
                  className={`p-4 border rounded-lg cursor-pointer transition-colors ${
                    reportType === type.value
                      ? 'border-blue-500 bg-blue-50'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                  onClick={() => setReportType(type.value)}
                >
                  <div className="flex items-start space-x-3">
                    <div className="text-2xl">{getReportTypeIcon(type.value)}</div>
                    <div>
                      <div className="font-medium text-gray-900">{type.label}</div>
                      <div className="text-sm text-gray-600">{type.description}</div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Date Range */}
          <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">Rentang Waktu</h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Periode Laporan
                </label>
                <select
                  value={dateRange}
                  onChange={(e) => setDateRange(e.target.value)}
                  className="w-full 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="180">6 Bulan Terakhir</option>
                  <option value="365">1 Tahun Terakhir</option>
                  <option value="custom">Custom Range</option>
                </select>
              </div>

              {dateRange === 'custom' && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Tanggal Mulai
                    </label>
                    <input
                      type="date"
                      value={customStartDate}
                      onChange={(e) => setCustomStartDate(e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Tanggal Selesai
                    </label>
                    <input
                      type="date"
                      value={customEndDate}
                      onChange={(e) => setCustomEndDate(e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    />
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Filters */}
          <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">Filter Data</h2>
            
            {/* User Filter */}
            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Pilih Pengguna (Opsional)
              </label>
              <div className="max-h-40 overflow-y-auto border border-gray-200 rounded-lg p-3">
                {mockUsers.map((user) => (
                  <label key={user.id} className="flex items-center space-x-2 py-1">
                    <input
                      type="checkbox"
                      checked={selectedUsers.includes(user.id)}
                      onChange={() => handleUserSelection(user.id)}
                      className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    />
                    <span className="text-sm text-gray-700">
                      {user.name} ({user.nim}) - {user.class}
                    </span>
                  </label>
                ))}
              </div>
              <p className="text-xs text-gray-500 mt-1">
                {selectedUsers.length > 0 ? `${selectedUsers.length} pengguna dipilih` : 'Semua pengguna akan disertakan'}
              </p>
            </div>

            {/* Exam Filter */}
            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Pilih Ujian (Opsional)
              </label>
              <div className="max-h-40 overflow-y-auto border border-gray-200 rounded-lg p-3">
                {mockExams.map((exam) => (
                  <label key={exam.id} className="flex items-center space-x-2 py-1">
                    <input
                      type="checkbox"
                      checked={selectedExams.includes(exam.id)}
                      onChange={() => handleExamSelection(exam.id)}
                      className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    />
                    <span className="text-sm text-gray-700">
                      {exam.title} ({exam.date})
                    </span>
                  </label>
                ))}
              </div>
              <p className="text-xs text-gray-500 mt-1">
                {selectedExams.length > 0 ? `${selectedExams.length} ujian dipilih` : 'Semua ujian akan disertakan'}
              </p>
            </div>

            {/* Category Filter */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Pilih Kategori (Opsional)
              </label>
              <div className="flex flex-wrap gap-2">
                {mockCategories.map((category) => (
                  <label key={category.id} className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      checked={selectedCategories.includes(category.id)}
                      onChange={() => handleCategorySelection(category.id)}
                      className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    />
                    <span className="text-sm text-gray-700">{category.name}</span>
                  </label>
                ))}
              </div>
              <p className="text-xs text-gray-500 mt-1">
                {selectedCategories.length > 0 ? `${selectedCategories.length} kategori dipilih` : 'Semua kategori akan disertakan'}
              </p>
            </div>
          </div>

          {/* Export Format */}
          <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">Format Export</h2>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              {[
                { value: 'pdf', label: 'PDF', description: 'Dokumen siap cetak' },
                { value: 'excel', label: 'Excel', description: 'Spreadsheet dengan chart' },
                { value: 'csv', label: 'CSV', description: 'Data mentah' },
                { value: 'json', label: 'JSON', description: 'Format API' }
              ].map((format) => (
                <div
                  key={format.value}
                  className={`p-3 border rounded-lg cursor-pointer transition-colors text-center ${
                    exportFormat === format.value
                      ? 'border-blue-500 bg-blue-50'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                  onClick={() => setExportFormat(format.value)}
                >
                  <div className="text-2xl mb-1">{getFormatIcon(format.value)}</div>
                  <div className="font-medium text-gray-900">{format.label}</div>
                  <div className="text-xs text-gray-600">{format.description}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Generate Button */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <button
              onClick={handleGenerateReport}
              disabled={isGenerating}
              className={`w-full py-3 px-4 rounded-lg font-medium transition-colors ${
                isGenerating
                  ? 'bg-gray-400 text-white cursor-not-allowed'
                  : 'bg-blue-600 text-white hover:bg-blue-700'
              }`}
            >
              {isGenerating ? (
                <div className="flex items-center justify-center space-x-2">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                  <span>Generating Report...</span>
                </div>
              ) : (
                '📊 Generate Report'
              )}
            </button>
          </div>
        </div>

        {/* Generated Reports History */}
        <div className="space-y-6">
          <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">Laporan Terbaru</h2>
            <div className="space-y-4">
              {mockGeneratedReports.map((report) => (
                <div key={report.id} className="border border-gray-200 rounded-lg p-4">
                  <div className="flex items-start justify-between mb-2">
                    <div className="flex items-start space-x-2">
                      <span className="text-lg">{getReportTypeIcon(report.type)}</span>
                      <div>
                        <div className="font-medium text-gray-900 text-sm">{report.title}</div>
                        <div className="text-xs text-gray-500">
                          {formatDateTime(report.generatedAt)}
                        </div>
                      </div>
                    </div>
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                      report.status === 'completed' 
                        ? 'bg-green-100 text-green-800'
                        : 'bg-yellow-100 text-yellow-800'
                    }`}>
                      {report.status === 'completed' ? 'Selesai' : 'Proses'}
                    </span>
                  </div>
                  
                  <div className="flex items-center justify-between text-xs text-gray-500 mb-3">
                    <span className="flex items-center space-x-1">
                      <span>{getFormatIcon(report.format)}</span>
                      <span>{report.format.toUpperCase()}</span>
                    </span>
                    <span>{report.size}</span>
                  </div>
                  
                  <div className="flex space-x-2">
                    <button className="flex-1 px-3 py-1 bg-blue-600 text-white text-xs rounded hover:bg-blue-700 transition-colors">
                      📥 Download
                    </button>
                    <button className="px-3 py-1 border border-gray-300 text-gray-700 text-xs rounded hover:bg-gray-50 transition-colors">
                      👁️ Preview
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Report Templates */}
          <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">Template Laporan</h2>
            <div className="space-y-3">
              <button className="w-full p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors text-left">
                <div className="font-medium text-gray-900 text-sm">📊 Laporan Bulanan</div>
                <div className="text-xs text-gray-500">Ringkasan performa bulan ini</div>
              </button>
              
              <button className="w-full p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors text-left">
                <div className="font-medium text-gray-900 text-sm">📈 Analisis Semester</div>
                <div className="text-xs text-gray-500">Laporan komprehensif semester</div>
              </button>
              
              <button className="w-full p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors text-left">
                <div className="font-medium text-gray-900 text-sm">👥 Laporan Kelas</div>
                <div className="text-xs text-gray-500">Performa per kelas</div>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ReportsPage;