'use client';

import React, { useState, useEffect } from 'react';
import { 
  Settings, 
  Save, 
  RefreshCw, 
  Eye, 
  EyeOff, 
  Gamepad2,
  Puzzle,
  Users,
  Brain,
  Timer,
  Zap,
  Heart,
  MessageSquare,
  CheckCircle,
  AlertCircle,
  Info
} from 'lucide-react';
import { AdminQuizConfig } from '@/types';

interface InteractiveQuizConfigurationPanelProps {
  config: AdminQuizConfig;
  onConfigChange: (config: AdminQuizConfig) => void;
  onSave: () => void;
  onReset: () => void;
  isLoading?: boolean;
}

const defaultInteractiveConfig: AdminQuizConfig = {
  language: 'id',
  allowHints: true,
  showExplanations: true,
  enableBehaviorTracking: false,
  confidenceRatingRequired: false,
  timeLimit: 3600,
  shuffleQuestions: false,
  shuffleOptions: false,
  allowReview: true,
  showProgressBar: true,
  customInstructions: '',
  behaviorAnalysis: {
    trackMouseMovements: false,
    trackKeystrokes: false,
    trackScrolling: false,
    trackFocusEvents: false,
    analysisDepth: 'basic',
  },
  privacySettings: {
    anonymizeData: true,
    dataRetentionDays: 30,
    allowDataExport: false,
  },
  enabledFeatures: {
    enhancedMCQ: false,
    puzzleQuestions: false,
    scenarioSimulation: false,
    behaviorAnalysis: false,
    timeBasedQuestions: false,
    adaptiveDifficulty: false,
    personalityProfiling: false,
  },
  customSettings: {
    allowRetake: true,
    showResultsImmediately: true,
    generatePersonalityReport: false,
    enableHints: true,
    trackBehaviorMetrics: false,
    requireConfidenceRating: false,
    enableCollaboration: false,
  },
};

export const InteractiveQuizConfigurationPanel: React.FC<InteractiveQuizConfigurationPanelProps> = ({
  config,
  onConfigChange,
  onSave,
  onReset,
  isLoading = false,
}) => {
  const [activeTab, setActiveTab] = useState<'mode' | 'features' | 'settings'>('mode');
  const [hasChanges, setHasChanges] = useState(false);
  const [previewMode, setPreviewMode] = useState(false);
  const [isInteractiveMode, setIsInteractiveMode] = useState(false);

  useEffect(() => {
    const configString = JSON.stringify(config);
    const defaultString = JSON.stringify(defaultInteractiveConfig);
    setHasChanges(configString !== defaultString);
    
    // Check if any interactive features are enabled
    const hasInteractiveFeatures = config.enabledFeatures && (
      config.enabledFeatures.enhancedMCQ ||
      config.enabledFeatures.puzzleQuestions ||
      config.enabledFeatures.scenarioSimulation ||
      config.enabledFeatures.timeBasedQuestions ||
      config.enabledFeatures.adaptiveDifficulty ||
      config.enabledFeatures.personalityProfiling
    );
    setIsInteractiveMode(!!hasInteractiveFeatures);
  }, [config]);

  const handleConfigUpdate = (updates: Partial<AdminQuizConfig>) => {
    const newConfig = { ...config, ...updates };
    onConfigChange(newConfig);
  };

  const handleFeatureToggle = (feature: keyof NonNullable<AdminQuizConfig['enabledFeatures']>, enabled: boolean) => {
    const currentFeatures = config.enabledFeatures || {
      enhancedMCQ: false,
      puzzleQuestions: false,
      scenarioSimulation: false,
      behaviorAnalysis: false,
      timeBasedQuestions: false,
      adaptiveDifficulty: false,
      personalityProfiling: false,
    };
    
    const newFeatures = { 
      ...currentFeatures, 
      [feature]: enabled 
    };
    handleConfigUpdate({ enabledFeatures: newFeatures });
  };

  const handleModeToggle = (interactive: boolean) => {
    setIsInteractiveMode(interactive);
    if (!interactive) {
      // Disable all interactive features when switching to standard mode
      handleConfigUpdate({
        enabledFeatures: {
          enhancedMCQ: false,
          puzzleQuestions: false,
          scenarioSimulation: false,
          behaviorAnalysis: false,
          timeBasedQuestions: false,
          adaptiveDifficulty: false,
          personalityProfiling: false,
        }
      });
    }
  };

  const interactiveFeatures = [
    {
      key: 'enhancedMCQ' as const,
      title: 'Enhanced Multiple Choice',
      description: 'Pilihan ganda dengan multimedia, hints, dan confidence rating',
      icon: CheckCircle,
      color: 'blue',
      difficulty: 'Mudah'
    },
    {
      key: 'puzzleQuestions' as const,
      title: 'Puzzle Questions',
      description: 'Kuis berbentuk puzzle drag-drop dan matching',
      icon: Puzzle,
      color: 'green',
      difficulty: 'Sedang'
    },
    {
      key: 'scenarioSimulation' as const,
      title: 'Scenario Simulation',
      description: 'Simulasi skenario dapur dan situasi kerja',
      icon: Users,
      color: 'purple',
      difficulty: 'Sulit'
    },
    {
      key: 'timeBasedQuestions' as const,
      title: 'Time-Based Questions',
      description: 'Pertanyaan dengan batasan waktu dan reaksi cepat',
      icon: Timer,
      color: 'orange',
      difficulty: 'Sedang'
    },
    {
      key: 'adaptiveDifficulty' as const,
      title: 'Adaptive Difficulty',
      description: 'Tingkat kesulitan yang menyesuaikan dengan performa',
      icon: Brain,
      color: 'indigo',
      difficulty: 'Sulit'
    },
    {
      key: 'personalityProfiling' as const,
      title: 'Personality Profiling',
      description: 'Analisis kepribadian dan gaya belajar',
      icon: Heart,
      color: 'pink',
      difficulty: 'Sulit'
    }
  ];

  const tabs = [
    { id: 'mode', label: 'Quiz Mode', icon: Gamepad2 },
    { id: 'features', label: 'Interactive Features', icon: Zap },
    { id: 'settings', label: 'Advanced Settings', icon: Settings },
  ];

  return (
    <div className="bg-white rounded-lg shadow-sm border">
      {/* Header */}
      <div className="p-6 border-b">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-xl font-semibold text-gray-900">Interactive Quiz Configuration</h2>
            <p className="text-sm text-gray-600 mt-1">
              Konfigurasi mode dan fitur interactive quiz untuk pengalaman belajar yang lebih engaging
            </p>
          </div>
          <div className="flex items-center gap-3">
            <button
              onClick={() => setPreviewMode(!previewMode)}
              className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                previewMode
                  ? 'bg-blue-100 text-blue-700'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              {previewMode ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              {previewMode ? 'Edit Mode' : 'Preview'}
            </button>
            <button
              onClick={onReset}
              disabled={isLoading}
              className="flex items-center gap-2 px-3 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors disabled:opacity-50"
            >
              <RefreshCw className="w-4 h-4" />
              Reset
            </button>
            <button
              onClick={onSave}
              disabled={isLoading || !hasChanges}
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Save className="w-4 h-4" />
              {isLoading ? 'Saving...' : 'Save Changes'}
            </button>
          </div>
        </div>

        {/* Status Indicator */}
        {hasChanges && (
          <div className="mt-3 p-3 bg-amber-50 border border-amber-200 rounded-lg">
            <p className="text-sm text-amber-800">
              You have unsaved changes. Don't forget to save your configuration.
            </p>
          </div>
        )}

        {/* Mode Indicator */}
        <div className="mt-3 flex items-center gap-2">
          <div className={`px-3 py-1 rounded-full text-xs font-medium ${
            isInteractiveMode 
              ? 'bg-green-100 text-green-800' 
              : 'bg-gray-100 text-gray-800'
          }`}>
            {isInteractiveMode ? 'Interactive Mode' : 'Standard Mode'}
          </div>
          {isInteractiveMode && (
            <div className="text-xs text-gray-600">
              {Object.values(config.enabledFeatures || {}).filter(Boolean).length} fitur aktif
            </div>
          )}
        </div>
      </div>

      {/* Tabs */}
      <div className="border-b">
        <nav className="flex space-x-8 px-6">
          {tabs.map((tab) => {
            const Icon = tab.icon;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`flex items-center gap-2 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'
                }`}
              >
                <Icon className="w-4 h-4" />
                {tab.label}
              </button>
            );
          })}
        </nav>
      </div>

      {/* Tab Content */}
      <div className="p-6">
        {activeTab === 'mode' && (
          <div className="space-y-6">
            {/* Quiz Mode Selection */}
            <div>
              <h3 className="text-lg font-medium text-gray-900 mb-4">Quiz Mode</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div 
                  className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                    !isInteractiveMode 
                      ? 'border-blue-500 bg-blue-50' 
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                  onClick={() => handleModeToggle(false)}
                >
                  <div className="flex items-center gap-3 mb-2">
                    <div className="w-8 h-8 bg-gray-100 rounded-lg flex items-center justify-center">
                      <MessageSquare className="w-4 h-4 text-gray-600" />
                    </div>
                    <h4 className="font-medium text-gray-900">Standard Quiz</h4>
                  </div>
                  <p className="text-sm text-gray-600">
                    Kuis tradisional dengan pertanyaan pilihan ganda, essay, dan true/false
                  </p>
                </div>

                <div 
                  className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                    isInteractiveMode 
                      ? 'border-blue-500 bg-blue-50' 
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                  onClick={() => handleModeToggle(true)}
                >
                  <div className="flex items-center gap-3 mb-2">
                    <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
                      <Gamepad2 className="w-4 h-4 text-blue-600" />
                    </div>
                    <h4 className="font-medium text-gray-900">Interactive Quiz</h4>
                  </div>
                  <p className="text-sm text-gray-600">
                    Kuis interaktif dengan multimedia, simulasi, dan fitur engagement tinggi
                  </p>
                </div>
              </div>
            </div>

            {/* Mode Benefits */}
            {isInteractiveMode && (
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div className="flex items-start gap-3">
                  <Info className="w-5 h-5 text-blue-600 mt-0.5" />
                  <div>
                    <h4 className="font-medium text-blue-900 mb-2">Interactive Mode Benefits</h4>
                    <ul className="text-sm text-blue-800 space-y-1">
                      <li>• Engagement rate 3x lebih tinggi</li>
                      <li>• Learning retention meningkat 40%</li>
                      <li>• Real-time feedback dan adaptasi</li>
                      <li>• Analisis behavior dan personality profiling</li>
                    </ul>
                  </div>
                </div>
              </div>
            )}
          </div>
        )}

        {activeTab === 'features' && (
          <div className="space-y-6">
            <div>
              <h3 className="text-lg font-medium text-gray-900 mb-4">Interactive Features</h3>
              {!isInteractiveMode ? (
                <div className="text-center py-8 bg-gray-50 rounded-lg">
                  <Gamepad2 className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                  <p className="text-gray-600 mb-2">Interactive features tidak tersedia</p>
                  <p className="text-sm text-gray-500">Aktifkan Interactive Mode terlebih dahulu</p>
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {interactiveFeatures.map((feature) => {
                    const Icon = feature.icon;
                    const isEnabled = config.enabledFeatures?.[feature.key] || false;
                    
                    return (
                      <div 
                        key={feature.key}
                        className={`p-4 border rounded-lg transition-all ${
                          isEnabled 
                            ? `border-${feature.color}-200 bg-${feature.color}-50` 
                            : 'border-gray-200 hover:border-gray-300'
                        }`}
                      >
                        <div className="flex items-start justify-between mb-3">
                          <div className="flex items-center gap-3">
                            <div className={`w-8 h-8 bg-${feature.color}-100 rounded-lg flex items-center justify-center`}>
                              <Icon className={`w-4 h-4 text-${feature.color}-600`} />
                            </div>
                            <div>
                              <h4 className="font-medium text-gray-900">{feature.title}</h4>
                              <span className={`text-xs px-2 py-1 rounded-full ${
                                feature.difficulty === 'Mudah' ? 'bg-green-100 text-green-800' :
                                feature.difficulty === 'Sedang' ? 'bg-yellow-100 text-yellow-800' :
                                'bg-red-100 text-red-800'
                              }`}>
                                {feature.difficulty}
                              </span>
                            </div>
                          </div>
                          <label className="relative inline-flex items-center cursor-pointer">
                            <input
                              type="checkbox"
                              checked={isEnabled}
                              onChange={(e) => handleFeatureToggle(feature.key, e.target.checked)}
                              disabled={previewMode}
                              className="sr-only peer"
                            />
                            <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                          </label>
                        </div>
                        <p className="text-sm text-gray-600">{feature.description}</p>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        )}

        {activeTab === 'settings' && (
          <div className="space-y-6">
            <div>
              <h3 className="text-lg font-medium text-gray-900 mb-4">Advanced Settings</h3>
              <div className="space-y-4">
                {/* Basic Settings */}
                <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">
                      Time Limit (minutes)
                    </label>
                    <input
                      type="number"
                      value={Math.floor(config.timeLimit / 60)}
                      onChange={(e) => handleConfigUpdate({ timeLimit: parseInt(e.target.value) * 60 })}
                      disabled={previewMode}
                      min="1"
                      max="480"
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-50"
                    />
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Language
                    </label>
                    <select
                      value={config.language}
                      onChange={(e) => handleConfigUpdate({ language: e.target.value as 'id' | 'en' })}
                      disabled={previewMode}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-50"
                    >
                      <option value="id">Indonesian</option>
                      <option value="en">English</option>
                    </select>
                  </div>
                </div>

                {/* Feature Toggles */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {[
                    { key: 'allowHints', label: 'Allow Hints' },
                    { key: 'showExplanations', label: 'Show Explanations' },
                    { key: 'shuffleQuestions', label: 'Shuffle Questions' },
                    { key: 'shuffleOptions', label: 'Shuffle Options' },
                    { key: 'allowReview', label: 'Allow Review' },
                    { key: 'showProgressBar', label: 'Show Progress Bar' },
                  ].map((setting) => (
                    <div key={setting.key} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <span className="text-sm font-medium text-gray-700">{setting.label}</span>
                      <label className="relative inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={config[setting.key as keyof AdminQuizConfig] as boolean}
                          onChange={(e) => handleConfigUpdate({ [setting.key]: e.target.checked })}
                          disabled={previewMode}
                          className="sr-only peer"
                        />
                        <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                      </label>
                    </div>
                  ))}
                </div>

                {/* Custom Instructions */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Custom Instructions
                  </label>
                  <textarea
                    value={config.customInstructions}
                    onChange={(e) => handleConfigUpdate({ customInstructions: e.target.value })}
                    disabled={previewMode}
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-50"
                    placeholder="Masukkan instruksi khusus untuk quiz ini..."
                  />
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};