'use client';

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

const ExportPage: React.FC = () => {
  const [selectedDataType, setSelectedDataType] = useState('users');
  const [exportFormat, setExportFormat] = useState('csv');
  const [dateRange, setDateRange] = useState('all');
  const [customStartDate, setCustomStartDate] = useState('');
  const [customEndDate, setCustomEndDate] = useState('');
  const [selectedFields, setSelectedFields] = useState<string[]>([]);
  const [isExporting, setIsExporting] = useState(false);
  const [exportHistory, setExportHistory] = useState<any[]>([]);

  // Data types configuration
  const dataTypes = [
    {
      value: 'users',
      label: 'Data Pengguna',
      description: 'Informasi pengguna, profil, dan aktivitas',
      icon: '👥',
      fields: [
        { id: 'name', label: 'Nama Lengkap', required: true },
        { id: 'email', label: 'Email', required: true },
        { id: 'nim', label: 'NIM/ID', required: false },
        { id: 'class', label: 'Kelas', required: false },
        { id: 'role', label: 'Role', required: false },
        { id: 'status', label: 'Status', required: false },
        { id: 'created_at', label: 'Tanggal Daftar', required: false },
        { id: 'last_login', label: 'Login Terakhir', required: false },
        { id: 'phone', label: 'No. Telepon', required: false },
        { id: 'address', label: 'Alamat', required: false }
      ]
    },
    {
      value: 'exams',
      label: 'Data Ujian',
      description: 'Informasi ujian, jadwal, dan hasil',
      icon: '📝',
      fields: [
        { id: 'title', label: 'Judul Ujian', required: true },
        { id: 'description', label: 'Deskripsi', required: false },
        { id: 'start_date', label: 'Tanggal Mulai', required: true },
        { id: 'end_date', label: 'Tanggal Selesai', required: true },
        { id: 'duration', label: 'Durasi', required: false },
        { id: 'passing_score', label: 'Nilai Lulus', required: false },
        { id: 'total_questions', label: 'Jumlah Soal', required: false },
        { id: 'participants', label: 'Jumlah Peserta', required: false },
        { id: 'average_score', label: 'Rata-rata Nilai', required: false },
        { id: 'status', label: 'Status', required: false }
      ]
    },
    {
      value: 'results',
      label: 'Hasil Ujian',
      description: 'Skor, jawaban, dan analisis hasil',
      icon: '📊',
      fields: [
        { id: 'user_name', label: 'Nama Peserta', required: true },
        { id: 'user_nim', label: 'NIM', required: true },
        { id: 'exam_title', label: 'Judul Ujian', required: true },
        { id: 'score', label: 'Skor', required: true },
        { id: 'percentage', label: 'Persentase', required: false },
        { id: 'grade', label: 'Grade', required: false },
        { id: 'start_time', label: 'Waktu Mulai', required: false },
        { id: 'end_time', label: 'Waktu Selesai', required: false },
        { id: 'duration_taken', label: 'Durasi Pengerjaan', required: false },
        { id: 'correct_answers', label: 'Jawaban Benar', required: false },
        { id: 'wrong_answers', label: 'Jawaban Salah', required: false }
      ]
    },
    {
      value: 'questions',
      label: 'Bank Soal',
      description: 'Soal, kategori, dan statistik',
      icon: '❓',
      fields: [
        { id: 'title', label: 'Judul Soal', required: true },
        { id: 'type', label: 'Tipe Soal', required: true },
        { id: 'category', label: 'Kategori', required: false },
        { id: 'difficulty', label: 'Tingkat Kesulitan', required: false },
        { id: 'points', label: 'Poin', required: false },
        { id: 'options', label: 'Pilihan Jawaban', required: false },
        { id: 'correct_answer', label: 'Jawaban Benar', required: false },
        { id: 'explanation', label: 'Penjelasan', required: false },
        { id: 'usage_count', label: 'Jumlah Penggunaan', required: false },
        { id: 'success_rate', label: 'Tingkat Keberhasilan', required: false }
      ]
    },
    {
      value: 'analytics',
      label: 'Data Analytics',
      description: 'Statistik dan metrik sistem',
      icon: '📈',
      fields: [
        { id: 'date', label: 'Tanggal', required: true },
        { id: 'total_users', label: 'Total Pengguna', required: false },
        { id: 'active_users', label: 'Pengguna Aktif', required: false },
        { id: 'new_users', label: 'Pengguna Baru', required: false },
        { id: 'total_exams', label: 'Total Ujian', required: false },
        { id: 'completed_exams', label: 'Ujian Selesai', required: false },
        { id: 'average_score', label: 'Rata-rata Skor', required: false },
        { id: 'login_count', label: 'Jumlah Login', required: false },
        { id: 'page_views', label: 'Page Views', required: false }
      ]
    }
  ];

  const exportFormats = [
    { value: 'csv', label: 'CSV', description: 'Comma-separated values', icon: '📋' },
    { value: 'excel', label: 'Excel', description: 'Microsoft Excel format', icon: '📊' },
    { value: 'json', label: 'JSON', description: 'JavaScript Object Notation', icon: '🔧' },
    { value: 'xml', label: 'XML', description: 'Extensible Markup Language', icon: '📄' }
  ];

  const mockExportHistory = [
    {
      id: '1',
      type: 'users',
      format: 'csv',
      filename: 'users_export_2024-01-15.csv',
      size: '2.3 MB',
      records: 1247,
      createdAt: '2024-01-15T10:30:00',
      status: 'completed'
    },
    {
      id: '2',
      type: 'results',
      format: 'excel',
      filename: 'exam_results_2024-01-10.xlsx',
      size: '5.7 MB',
      records: 3456,
      createdAt: '2024-01-10T14:20:00',
      status: 'completed'
    },
    {
      id: '3',
      type: 'questions',
      format: 'json',
      filename: 'questions_export_2024-01-05.json',
      size: '1.2 MB',
      records: 2156,
      createdAt: '2024-01-05T09:15:00',
      status: 'completed'
    }
  ];

  const currentDataType = dataTypes.find(dt => dt.value === selectedDataType);

  const handleFieldSelection = (fieldId: string) => {
    setSelectedFields(prev => 
      prev.includes(fieldId) 
        ? prev.filter(id => id !== fieldId)
        : [...prev, fieldId]
    );
  };

  const handleSelectAllFields = () => {
    if (!currentDataType) return;
    
    if (selectedFields.length === currentDataType.fields.length) {
      setSelectedFields([]);
    } else {
      setSelectedFields(currentDataType.fields.map(field => field.id));
    }
  };

  const handleExport = async () => {
    setIsExporting(true);
    
    // Simulate export process
    setTimeout(() => {
      const newExport = {
        id: Date.now().toString(),
        type: selectedDataType,
        format: exportFormat,
        filename: `${selectedDataType}_export_${new Date().toISOString().split('T')[0]}.${exportFormat}`,
        size: `${(Math.random() * 5 + 1).toFixed(1)} MB`,
        records: Math.floor(Math.random() * 5000 + 100),
        createdAt: new Date().toISOString(),
        status: 'completed'
      };
      
      setExportHistory([newExport, ...exportHistory]);
      setIsExporting(false);
      
      // Auto download simulation
      alert(`Export "${newExport.filename}" berhasil dibuat dan sedang diunduh...`);
    }, 2000);
  };

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

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

  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">Export Data</span>
          </div>
          <h1 className="text-2xl font-bold text-gray-900 mt-1">Export Data</h1>
          <p className="text-gray-600">Download data sistem dalam berbagai format</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Export Configuration */}
        <div className="lg:col-span-2 space-y-6">
          {/* Data 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 Data</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {dataTypes.map((type) => (
                <div
                  key={type.value}
                  className={`p-4 border rounded-lg cursor-pointer transition-colors ${
                    selectedDataType === type.value
                      ? 'border-blue-500 bg-blue-50'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                  onClick={() => {
                    setSelectedDataType(type.value);
                    setSelectedFields([]);
                  }}
                >
                  <div className="flex items-start space-x-3">
                    <div className="text-2xl">{type.icon}</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>

          {/* Field Selection */}
          {currentDataType && (
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-lg font-semibold text-gray-900">Pilih Field</h2>
                <button
                  onClick={handleSelectAllFields}
                  className="text-sm text-blue-600 hover:text-blue-800 transition-colors"
                >
                  {selectedFields.length === currentDataType.fields.length ? 'Unselect All' : 'Select All'}
                </button>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                {currentDataType.fields.map((field) => (
                  <label key={field.id} className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      checked={selectedFields.includes(field.id)}
                      onChange={() => handleFieldSelection(field.id)}
                      className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    />
                    <span className="text-sm text-gray-700">
                      {field.label}
                      {field.required && <span className="text-red-500 ml-1">*</span>}
                    </span>
                  </label>
                ))}
              </div>
              
              <p className="text-xs text-gray-500 mt-3">
                {selectedFields.length > 0 ? `${selectedFields.length} field dipilih` : 'Pilih field yang ingin di-export'}
              </p>
            </div>
          )}

          {/* Date Range Filter */}
          <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 Tanggal</h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Rentang Data
                </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="all">Semua Data</option>
                  <option value="today">Hari Ini</option>
                  <option value="week">7 Hari Terakhir</option>
                  <option value="month">30 Hari Terakhir</option>
                  <option value="quarter">3 Bulan Terakhir</option>
                  <option value="year">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>

          {/* 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">
              {exportFormats.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">{format.icon}</div>
                  <div className="font-medium text-gray-900">{format.label}</div>
                  <div className="text-xs text-gray-600">{format.description}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Export Button */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div className="flex items-center justify-between mb-4">
              <div>
                <h3 className="font-medium text-gray-900">Siap untuk Export</h3>
                <p className="text-sm text-gray-600">
                  {currentDataType?.label} dalam format {exportFormat.toUpperCase()}
                  {selectedFields.length > 0 && ` dengan ${selectedFields.length} field`}
                </p>
              </div>
            </div>
            
            <button
              onClick={handleExport}
              disabled={isExporting || selectedFields.length === 0}
              className={`w-full py-3 px-4 rounded-lg font-medium transition-colors ${
                isExporting || selectedFields.length === 0
                  ? 'bg-gray-400 text-white cursor-not-allowed'
                  : 'bg-blue-600 text-white hover:bg-blue-700'
              }`}
            >
              {isExporting ? (
                <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>Exporting...</span>
                </div>
              ) : (
                '📤 Export Data'
              )}
            </button>
            
            {selectedFields.length === 0 && (
              <p className="text-xs text-red-500 mt-2 text-center">
                Pilih minimal satu field untuk melanjutkan export
              </p>
            )}
          </div>
        </div>

        {/* Export History & Info */}
        <div className="space-y-6">
          {/* Export History */}
          <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">Riwayat Export</h2>
            <div className="space-y-4">
              {mockExportHistory.map((export_item) => (
                <div key={export_item.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">
                        {dataTypes.find(dt => dt.value === export_item.type)?.icon}
                      </span>
                      <div>
                        <div className="font-medium text-gray-900 text-sm">
                          {dataTypes.find(dt => dt.value === export_item.type)?.label}
                        </div>
                        <div className="text-xs text-gray-500">
                          {formatDateTime(export_item.createdAt)}
                        </div>
                      </div>
                    </div>
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                      export_item.status === 'completed' 
                        ? 'bg-green-100 text-green-800'
                        : 'bg-yellow-100 text-yellow-800'
                    }`}>
                      {export_item.status === 'completed' ? 'Selesai' : 'Proses'}
                    </span>
                  </div>
                  
                  <div className="text-xs text-gray-600 mb-2">
                    <div>{export_item.filename}</div>
                    <div className="flex justify-between mt-1">
                      <span>{export_item.size}</span>
                      <span>{formatNumber(export_item.records)} records</span>
                    </div>
                  </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">
                      🗑️
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Export Info */}
          <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">Informasi Export</h2>
            <div className="space-y-3 text-sm text-gray-600">
              <div className="flex items-start space-x-2">
                <span className="text-blue-500">ℹ️</span>
                <div>
                  <div className="font-medium">Format CSV</div>
                  <div>Kompatibel dengan Excel, Google Sheets, dan aplikasi spreadsheet lainnya.</div>
                </div>
              </div>
              
              <div className="flex items-start space-x-2">
                <span className="text-green-500">📊</span>
                <div>
                  <div className="font-medium">Format Excel</div>
                  <div>Termasuk formatting dan chart untuk analisis data.</div>
                </div>
              </div>
              
              <div className="flex items-start space-x-2">
                <span className="text-purple-500">🔧</span>
                <div>
                  <div className="font-medium">Format JSON</div>
                  <div>Ideal untuk integrasi API dan pengembangan aplikasi.</div>
                </div>
              </div>
              
              <div className="flex items-start space-x-2">
                <span className="text-orange-500">📄</span>
                <div>
                  <div className="font-medium">Format XML</div>
                  <div>Struktur data hierarkis untuk sistem enterprise.</div>
                </div>
              </div>
            </div>
          </div>

          {/* Quick Export 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 Cepat</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">👥 Data Mahasiswa Lengkap</div>
                <div className="text-xs text-gray-500">Semua field pengguna dengan role student</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">📊 Hasil Ujian Semester</div>
                <div className="text-xs text-gray-500">Skor dan grade semua ujian semester 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">❓ Bank Soal Aktif</div>
                <div className="text-xs text-gray-500">Semua soal dengan status aktif</div>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ExportPage;