'use client';

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

const AnalyticsSettingsPage: React.FC = () => {
  const [settings, setSettings] = useState({
    // Data Collection Settings
    enableUserTracking: true,
    enablePerformanceTracking: true,
    enableEngagementTracking: true,
    enableSystemMetrics: true,
    dataRetentionDays: 365,
    
    // Privacy Settings
    anonymizeUserData: false,
    enableGDPRCompliance: true,
    allowDataExport: true,
    requireConsentForTracking: true,
    
    // Report Settings
    defaultReportFormat: 'pdf',
    autoGenerateReports: true,
    reportFrequency: 'weekly',
    emailReports: true,
    reportRecipients: ['admin@university.edu'],
    
    // Dashboard Settings
    defaultTimeRange: '30',
    refreshInterval: 300, // seconds
    enableRealTimeUpdates: true,
    showAdvancedMetrics: true,
    
    // Notification Settings
    enableAlerts: true,
    performanceThreshold: 70,
    engagementThreshold: 60,
    alertMethods: ['email', 'dashboard'],
    
    // Integration Settings
    enableAPIAccess: false,
    apiRateLimit: 1000,
    webhookURL: '',
    enableThirdPartyIntegrations: false
  });

  const [isSaving, setIsSaving] = useState(false);
  const [activeTab, setActiveTab] = useState('data-collection');

  const handleSettingChange = (key: string, value: any) => {
    setSettings(prev => ({
      ...prev,
      [key]: value
    }));
  };

  const handleArraySettingChange = (key: string, value: string, checked: boolean) => {
    setSettings(prev => ({
      ...prev,
      [key]: checked 
        ? [...(prev[key as keyof typeof prev] as string[]), value]
        : (prev[key as keyof typeof prev] as string[]).filter(item => item !== value)
    }));
  };

  const handleSaveSettings = async () => {
    setIsSaving(true);
    
    // Simulate API call
    setTimeout(() => {
      setIsSaving(false);
      alert('Pengaturan berhasil disimpan!');
    }, 1500);
  };

  const resetToDefaults = () => {
    if (confirm('Apakah Anda yakin ingin mengembalikan ke pengaturan default?')) {
      // Reset to default values
      setSettings({
        enableUserTracking: true,
        enablePerformanceTracking: true,
        enableEngagementTracking: true,
        enableSystemMetrics: true,
        dataRetentionDays: 365,
        anonymizeUserData: false,
        enableGDPRCompliance: true,
        allowDataExport: true,
        requireConsentForTracking: true,
        defaultReportFormat: 'pdf',
        autoGenerateReports: true,
        reportFrequency: 'weekly',
        emailReports: true,
        reportRecipients: ['admin@university.edu'],
        defaultTimeRange: '30',
        refreshInterval: 300,
        enableRealTimeUpdates: true,
        showAdvancedMetrics: true,
        enableAlerts: true,
        performanceThreshold: 70,
        engagementThreshold: 60,
        alertMethods: ['email', 'dashboard'],
        enableAPIAccess: false,
        apiRateLimit: 1000,
        webhookURL: '',
        enableThirdPartyIntegrations: false
      });
    }
  };

  const tabs = [
    { id: 'data-collection', label: 'Pengumpulan Data', icon: '📊' },
    { id: 'privacy', label: 'Privasi & Keamanan', icon: '🔒' },
    { id: 'reports', label: 'Laporan', icon: '📄' },
    { id: 'dashboard', label: 'Dashboard', icon: '📈' },
    { id: 'notifications', label: 'Notifikasi', icon: '🔔' },
    { id: 'integrations', label: 'Integrasi', icon: '🔗' }
  ];

  const renderDataCollectionSettings = () => (
    <div className="space-y-6">
      <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">Tracking Data</h3>
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">User Activity Tracking</label>
              <p className="text-sm text-gray-600">Lacak aktivitas login, navigasi, dan interaksi pengguna</p>
            </div>
            <input
              type="checkbox"
              checked={settings.enableUserTracking}
              onChange={(e) => handleSettingChange('enableUserTracking', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
          
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">Performance Tracking</label>
              <p className="text-sm text-gray-600">Lacak skor ujian, waktu pengerjaan, dan performa akademik</p>
            </div>
            <input
              type="checkbox"
              checked={settings.enablePerformanceTracking}
              onChange={(e) => handleSettingChange('enablePerformanceTracking', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
          
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">Engagement Tracking</label>
              <p className="text-sm text-gray-600">Lacak tingkat keterlibatan dan partisipasi dalam sistem</p>
            </div>
            <input
              type="checkbox"
              checked={settings.enableEngagementTracking}
              onChange={(e) => handleSettingChange('enableEngagementTracking', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
          
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">System Metrics</label>
              <p className="text-sm text-gray-600">Lacak performa sistem, load time, dan error rate</p>
            </div>
            <input
              type="checkbox"
              checked={settings.enableSystemMetrics}
              onChange={(e) => handleSettingChange('enableSystemMetrics', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
        </div>
      </div>

      <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">Data Retention</h3>
        <div className="space-y-4">
          <div>
            <label className="block font-medium text-gray-900 mb-2">
              Periode Penyimpanan Data (hari)
            </label>
            <select
              value={settings.dataRetentionDays}
              onChange={(e) => handleSettingChange('dataRetentionDays', parseInt(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={30}>30 Hari</option>
              <option value={90}>90 Hari</option>
              <option value={180}>6 Bulan</option>
              <option value={365}>1 Tahun</option>
              <option value={730}>2 Tahun</option>
              <option value={-1}>Permanent</option>
            </select>
            <p className="text-sm text-gray-600 mt-1">
              Data akan otomatis dihapus setelah periode ini berakhir
            </p>
          </div>
        </div>
      </div>
    </div>
  );

  const renderPrivacySettings = () => (
    <div className="space-y-6">
      <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">Pengaturan Privasi</h3>
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">Anonimisasi Data Pengguna</label>
              <p className="text-sm text-gray-600">Hapus informasi identitas dari data analytics</p>
            </div>
            <input
              type="checkbox"
              checked={settings.anonymizeUserData}
              onChange={(e) => handleSettingChange('anonymizeUserData', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
          
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">GDPR Compliance</label>
              <p className="text-sm text-gray-600">Aktifkan fitur kepatuhan terhadap regulasi GDPR</p>
            </div>
            <input
              type="checkbox"
              checked={settings.enableGDPRCompliance}
              onChange={(e) => handleSettingChange('enableGDPRCompliance', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
          
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">Izinkan Export Data</label>
              <p className="text-sm text-gray-600">Pengguna dapat mengunduh data pribadi mereka</p>
            </div>
            <input
              type="checkbox"
              checked={settings.allowDataExport}
              onChange={(e) => handleSettingChange('allowDataExport', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
          
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">Persetujuan Tracking</label>
              <p className="text-sm text-gray-600">Minta persetujuan pengguna sebelum tracking</p>
            </div>
            <input
              type="checkbox"
              checked={settings.requireConsentForTracking}
              onChange={(e) => handleSettingChange('requireConsentForTracking', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
        </div>
      </div>
    </div>
  );

  const renderReportSettings = () => (
    <div className="space-y-6">
      <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">Pengaturan Laporan</h3>
        <div className="space-y-4">
          <div>
            <label className="block font-medium text-gray-900 mb-2">
              Format Laporan Default
            </label>
            <select
              value={settings.defaultReportFormat}
              onChange={(e) => handleSettingChange('defaultReportFormat', 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="pdf">PDF</option>
              <option value="excel">Excel</option>
              <option value="csv">CSV</option>
              <option value="json">JSON</option>
            </select>
          </div>
          
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">Auto-Generate Reports</label>
              <p className="text-sm text-gray-600">Buat laporan otomatis secara berkala</p>
            </div>
            <input
              type="checkbox"
              checked={settings.autoGenerateReports}
              onChange={(e) => handleSettingChange('autoGenerateReports', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
          
          {settings.autoGenerateReports && (
            <div>
              <label className="block font-medium text-gray-900 mb-2">
                Frekuensi Laporan
              </label>
              <select
                value={settings.reportFrequency}
                onChange={(e) => handleSettingChange('reportFrequency', 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="daily">Harian</option>
                <option value="weekly">Mingguan</option>
                <option value="monthly">Bulanan</option>
                <option value="quarterly">Kuartalan</option>
              </select>
            </div>
          )}
          
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">Email Reports</label>
              <p className="text-sm text-gray-600">Kirim laporan via email secara otomatis</p>
            </div>
            <input
              type="checkbox"
              checked={settings.emailReports}
              onChange={(e) => handleSettingChange('emailReports', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
          
          {settings.emailReports && (
            <div>
              <label className="block font-medium text-gray-900 mb-2">
                Penerima Email (satu per baris)
              </label>
              <textarea
                value={settings.reportRecipients.join('\n')}
                onChange={(e) => handleSettingChange('reportRecipients', e.target.value.split('\n').filter(email => email.trim()))}
                rows={3}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="admin@university.edu&#10;manager@university.edu"
              />
            </div>
          )}
        </div>
      </div>
    </div>
  );

  const renderDashboardSettings = () => (
    <div className="space-y-6">
      <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">Pengaturan Dashboard</h3>
        <div className="space-y-4">
          <div>
            <label className="block font-medium text-gray-900 mb-2">
              Rentang Waktu Default
            </label>
            <select
              value={settings.defaultTimeRange}
              onChange={(e) => handleSettingChange('defaultTimeRange', 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="365">1 Tahun Terakhir</option>
            </select>
          </div>
          
          <div>
            <label className="block font-medium text-gray-900 mb-2">
              Interval Refresh (detik)
            </label>
            <select
              value={settings.refreshInterval}
              onChange={(e) => handleSettingChange('refreshInterval', parseInt(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={60}>1 Menit</option>
              <option value={300}>5 Menit</option>
              <option value={600}>10 Menit</option>
              <option value={1800}>30 Menit</option>
              <option value={3600}>1 Jam</option>
            </select>
          </div>
          
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">Real-time Updates</label>
              <p className="text-sm text-gray-600">Update data secara real-time</p>
            </div>
            <input
              type="checkbox"
              checked={settings.enableRealTimeUpdates}
              onChange={(e) => handleSettingChange('enableRealTimeUpdates', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
          
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">Advanced Metrics</label>
              <p className="text-sm text-gray-600">Tampilkan metrik lanjutan di dashboard</p>
            </div>
            <input
              type="checkbox"
              checked={settings.showAdvancedMetrics}
              onChange={(e) => handleSettingChange('showAdvancedMetrics', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
        </div>
      </div>
    </div>
  );

  const renderNotificationSettings = () => (
    <div className="space-y-6">
      <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">Pengaturan Notifikasi</h3>
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">Enable Alerts</label>
              <p className="text-sm text-gray-600">Aktifkan sistem peringatan otomatis</p>
            </div>
            <input
              type="checkbox"
              checked={settings.enableAlerts}
              onChange={(e) => handleSettingChange('enableAlerts', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
          
          {settings.enableAlerts && (
            <>
              <div>
                <label className="block font-medium text-gray-900 mb-2">
                  Threshold Performa (%)
                </label>
                <input
                  type="number"
                  min="0"
                  max="100"
                  value={settings.performanceThreshold}
                  onChange={(e) => handleSettingChange('performanceThreshold', parseInt(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"
                />
                <p className="text-sm text-gray-600 mt-1">
                  Alert jika rata-rata performa di bawah nilai ini
                </p>
              </div>
              
              <div>
                <label className="block font-medium text-gray-900 mb-2">
                  Threshold Engagement (%)
                </label>
                <input
                  type="number"
                  min="0"
                  max="100"
                  value={settings.engagementThreshold}
                  onChange={(e) => handleSettingChange('engagementThreshold', parseInt(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"
                />
                <p className="text-sm text-gray-600 mt-1">
                  Alert jika tingkat engagement di bawah nilai ini
                </p>
              </div>
              
              <div>
                <label className="block font-medium text-gray-900 mb-2">
                  Metode Alert
                </label>
                <div className="space-y-2">
                  {['email', 'dashboard', 'sms', 'webhook'].map((method) => (
                    <label key={method} className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        checked={settings.alertMethods.includes(method)}
                        onChange={(e) => handleArraySettingChange('alertMethods', method, e.target.checked)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="text-sm text-gray-700 capitalize">{method}</span>
                    </label>
                  ))}
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );

  const renderIntegrationSettings = () => (
    <div className="space-y-6">
      <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">API & Integrasi</h3>
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">Enable API Access</label>
              <p className="text-sm text-gray-600">Izinkan akses data melalui REST API</p>
            </div>
            <input
              type="checkbox"
              checked={settings.enableAPIAccess}
              onChange={(e) => handleSettingChange('enableAPIAccess', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
          
          {settings.enableAPIAccess && (
            <>
              <div>
                <label className="block font-medium text-gray-900 mb-2">
                  API Rate Limit (requests/hour)
                </label>
                <input
                  type="number"
                  min="100"
                  max="10000"
                  value={settings.apiRateLimit}
                  onChange={(e) => handleSettingChange('apiRateLimit', parseInt(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 className="bg-blue-50 p-4 rounded-lg">
                <h4 className="font-medium text-blue-900 mb-2">API Endpoints</h4>
                <div className="text-sm text-blue-800 space-y-1">
                  <div><code>GET /api/analytics/users</code> - Data pengguna</div>
                  <div><code>GET /api/analytics/exams</code> - Data ujian</div>
                  <div><code>GET /api/analytics/results</code> - Hasil ujian</div>
                  <div><code>GET /api/analytics/metrics</code> - Metrik sistem</div>
                </div>
              </div>
            </>
          )}
          
          <div>
            <label className="block font-medium text-gray-900 mb-2">
              Webhook URL
            </label>
            <input
              type="url"
              value={settings.webhookURL}
              onChange={(e) => handleSettingChange('webhookURL', e.target.value)}
              placeholder="https://your-system.com/webhook"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
            <p className="text-sm text-gray-600 mt-1">
              URL untuk menerima notifikasi real-time
            </p>
          </div>
          
          <div className="flex items-center justify-between">
            <div>
              <label className="font-medium text-gray-900">Third-party Integrations</label>
              <p className="text-sm text-gray-600">Izinkan integrasi dengan sistem eksternal</p>
            </div>
            <input
              type="checkbox"
              checked={settings.enableThirdPartyIntegrations}
              onChange={(e) => handleSettingChange('enableThirdPartyIntegrations', e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          </div>
        </div>
      </div>
    </div>
  );

  const renderTabContent = () => {
    switch (activeTab) {
      case 'data-collection':
        return renderDataCollectionSettings();
      case 'privacy':
        return renderPrivacySettings();
      case 'reports':
        return renderReportSettings();
      case 'dashboard':
        return renderDashboardSettings();
      case 'notifications':
        return renderNotificationSettings();
      case 'integrations':
        return renderIntegrationSettings();
      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">Settings</span>
          </div>
          <h1 className="text-2xl font-bold text-gray-900 mt-1">Analytics Settings</h1>
          <p className="text-gray-600">Konfigurasi pengaturan analytics dan laporan</p>
        </div>
        <div className="flex items-center space-x-3">
          <button
            onClick={resetToDefaults}
            className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
          >
            🔄 Reset Default
          </button>
          <button
            onClick={handleSaveSettings}
            disabled={isSaving}
            className={`px-4 py-2 rounded-lg font-medium transition-colors ${
              isSaving
                ? 'bg-gray-400 text-white cursor-not-allowed'
                : 'bg-blue-600 text-white hover:bg-blue-700'
            }`}
          >
            {isSaving ? (
              <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>Saving...</span>
              </div>
            ) : (
              '💾 Save Settings'
            )}
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200">
        <div className="border-b border-gray-200">
          <nav className="flex space-x-8 px-6">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors ${
                  activeTab === tab.id
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
              >
                <span className="mr-2">{tab.icon}</span>
                {tab.label}
              </button>
            ))}
          </nav>
        </div>
        
        <div className="p-6">
          {renderTabContent()}
        </div>
      </div>

      {/* Settings Summary */}
      <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">Ringkasan Pengaturan</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 text-sm">
          <div className="p-3 bg-gray-50 rounded-lg">
            <div className="font-medium text-gray-900">Data Tracking</div>
            <div className="text-gray-600">
              {[
                settings.enableUserTracking && 'User',
                settings.enablePerformanceTracking && 'Performance',
                settings.enableEngagementTracking && 'Engagement',
                settings.enableSystemMetrics && 'System'
              ].filter(Boolean).join(', ') || 'None'}
            </div>
          </div>
          
          <div className="p-3 bg-gray-50 rounded-lg">
            <div className="font-medium text-gray-900">Data Retention</div>
            <div className="text-gray-600">
              {settings.dataRetentionDays === -1 ? 'Permanent' : `${settings.dataRetentionDays} days`}
            </div>
          </div>
          
          <div className="p-3 bg-gray-50 rounded-lg">
            <div className="font-medium text-gray-900">Auto Reports</div>
            <div className="text-gray-600">
              {settings.autoGenerateReports ? settings.reportFrequency : 'Disabled'}
            </div>
          </div>
          
          <div className="p-3 bg-gray-50 rounded-lg">
            <div className="font-medium text-gray-900">API Access</div>
            <div className="text-gray-600">
              {settings.enableAPIAccess ? 'Enabled' : 'Disabled'}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AnalyticsSettingsPage;