'use client';

import React, { useState, useEffect } from 'react';
import { 
  Settings, 
  Save, 
  RefreshCw, 
  Eye, 
  EyeOff, 
  Clock, 
  Users, 
  Shield, 
  BarChart3,
  Globe,
  HelpCircle,
  BookOpen,
  MousePointer,
  Keyboard,
  ScrollText,
  Focus,
  Download,
  Trash2,
  Plus,
  Minus
} from 'lucide-react';
import { AdminQuizConfig, BehaviorAnalysisConfig, BehaviorPrivacySettings } from '@/types';

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

const defaultConfig: AdminQuizConfig = {
  language: 'id',
  allowHints: true,
  showExplanations: true,
  enableBehaviorTracking: true,
  confidenceRatingRequired: true,
  timeLimit: 3600,
  shuffleQuestions: false,
  shuffleOptions: false,
  allowReview: true,
  showProgressBar: true,
  customInstructions: '',
  behaviorAnalysis: {
    trackMouseMovements: true,
    trackKeystrokes: true,
    trackScrolling: true,
    trackFocusEvents: true,
    analysisDepth: 'detailed',
  },
  privacySettings: {
    anonymizeData: false,
    dataRetentionDays: 30,
    allowDataExport: true,
  },
};

export const QuizConfigurationPanel: React.FC<QuizConfigurationPanelProps> = ({
  config,
  onConfigChange,
  onSave,
  onReset,
  isLoading = false,
}) => {
  const [activeTab, setActiveTab] = useState<'general' | 'behavior' | 'privacy'>('general');
  const [hasChanges, setHasChanges] = useState(false);
  const [previewMode, setPreviewMode] = useState(false);

  useEffect(() => {
    const configString = JSON.stringify(config);
    const defaultString = JSON.stringify(defaultConfig);
    setHasChanges(configString !== defaultString);
  }, [config]);

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

  const handleBehaviorAnalysisUpdate = (updates: Partial<BehaviorAnalysisConfig>) => {
    handleConfigUpdate({
      behaviorAnalysis: { ...config.behaviorAnalysis, ...updates }
    });
  };

  const handlePrivacySettingsUpdate = (updates: Partial<BehaviorPrivacySettings>) => {
    handleConfigUpdate({
      privacySettings: { ...config.privacySettings, ...updates }
    });
  };

  const formatTimeLimit = (seconds: number): string => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
  };

  const tabs = [
    { id: 'general', label: 'General Settings', icon: Settings },
    { id: 'behavior', label: 'Behavior Tracking', icon: BarChart3 },
    { id: 'privacy', label: 'Privacy & Security', icon: Shield },
  ];

  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">Quiz Configuration</h2>
            <p className="text-sm text-gray-600 mt-1">
              Configure interactive quiz settings and behavior tracking
            </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>
        )}
      </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 === 'general' && (
          <div className="space-y-6">
            {/* Basic Settings */}
            <div>
              <h3 className="text-lg font-medium text-gray-900 mb-4">Basic Settings</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    <Globe className="w-4 h-4 inline mr-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>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    <Clock className="w-4 h-4 inline mr-2" />
                    Time Limit
                  </label>
                  <div className="flex items-center gap-2">
                    <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="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-50"
                    />
                    <span className="text-sm text-gray-500">minutes</span>
                  </div>
                  <p className="text-xs text-gray-500 mt-1">
                    Current: {formatTimeLimit(config.timeLimit)}
                  </p>
                </div>
              </div>
            </div>

            {/* Quiz Features */}
            <div>
              <h3 className="text-lg font-medium text-gray-900 mb-4">Quiz Features</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {[
                  { key: 'allowHints', label: 'Allow Hints', icon: HelpCircle },
                  { key: 'showExplanations', label: 'Show Explanations', icon: BookOpen },
                  { key: 'confidenceRatingRequired', label: 'Require Confidence Rating', icon: BarChart3 },
                  { key: 'shuffleQuestions', label: 'Shuffle Questions', icon: RefreshCw },
                  { key: 'shuffleOptions', label: 'Shuffle Answer Options', icon: RefreshCw },
                  { key: 'allowReview', label: 'Allow Review', icon: Eye },
                  { key: 'showProgressBar', label: 'Show Progress Bar', icon: BarChart3 },
                ].map((feature) => {
                  const Icon = feature.icon;
                  return (
                    <div key={feature.key} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <div className="flex items-center gap-2">
                        <Icon className="w-4 h-4 text-gray-600" />
                        <span className="text-sm font-medium text-gray-700">{feature.label}</span>
                      </div>
                      <label className="relative inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={config[feature.key as keyof AdminQuizConfig] as boolean}
                          onChange={(e) => handleConfigUpdate({ [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>
                  );
                })}
              </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={4}
                placeholder="Enter custom instructions for quiz takers..."
                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>
        )}

        {activeTab === 'behavior' && (
          <div className="space-y-6">
            {/* Behavior Tracking Toggle */}
            <div className="flex items-center justify-between p-4 bg-blue-50 rounded-lg border border-blue-200">
              <div>
                <h3 className="text-lg font-medium text-gray-900">Enable Behavior Tracking</h3>
                <p className="text-sm text-gray-600">
                  Track user interactions to analyze learning patterns and provide insights
                </p>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={config.enableBehaviorTracking}
                  onChange={(e) => handleConfigUpdate({ enableBehaviorTracking: 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>

            {config.enableBehaviorTracking && (
              <>
                {/* Tracking Options */}
                <div>
                  <h3 className="text-lg font-medium text-gray-900 mb-4">Tracking Options</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {[
                      { key: 'trackMouseMovements', label: 'Mouse Movements', icon: MousePointer },
                      { key: 'trackKeystrokes', label: 'Keystrokes', icon: Keyboard },
                      { key: 'trackScrolling', label: 'Scrolling Behavior', icon: ScrollText },
                      { key: 'trackFocusEvents', label: 'Focus Events', icon: Focus },
                    ].map((option) => {
                      const Icon = option.icon;
                      return (
                        <div key={option.key} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                          <div className="flex items-center gap-2">
                            <Icon className="w-4 h-4 text-gray-600" />
                            <span className="text-sm font-medium text-gray-700">{option.label}</span>
                          </div>
                          <label className="relative inline-flex items-center cursor-pointer">
                            <input
                              type="checkbox"
                              checked={config.behaviorAnalysis[option.key as keyof BehaviorAnalysisConfig] as boolean}
                              onChange={(e) => handleBehaviorAnalysisUpdate({ [option.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>
                </div>

                {/* Analysis Depth */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Analysis Depth
                  </label>
                  <select
                    value={config.behaviorAnalysis.analysisDepth}
                    onChange={(e) => handleBehaviorAnalysisUpdate({ analysisDepth: e.target.value as 'basic' | 'detailed' | 'comprehensive' })}
                    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="basic">Basic - Essential metrics only</option>
                    <option value="detailed">Detailed - Comprehensive analysis</option>
                    <option value="comprehensive">Comprehensive - Full behavioral profiling</option>
                  </select>
                </div>
              </>
            )}
          </div>
        )}

        {activeTab === 'privacy' && (
          <div className="space-y-6">
            {/* Privacy Settings */}
            <div>
              <h3 className="text-lg font-medium text-gray-900 mb-4">Privacy Settings</h3>
              <div className="space-y-4">
                <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <div>
                    <span className="text-sm font-medium text-gray-700">Anonymize Data</span>
                    <p className="text-xs text-gray-500">Remove personally identifiable information</p>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={config.privacySettings.anonymizeData}
                      onChange={(e) => handlePrivacySettingsUpdate({ anonymizeData: 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 className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <div>
                    <span className="text-sm font-medium text-gray-700">Allow Data Export</span>
                    <p className="text-xs text-gray-500">Users can export their behavioral data</p>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={config.privacySettings.allowDataExport}
                      onChange={(e) => handlePrivacySettingsUpdate({ allowDataExport: 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>
            </div>

            {/* Data Retention */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Data Retention Period
              </label>
              <div className="flex items-center gap-2">
                <input
                  type="number"
                  value={config.privacySettings.dataRetentionDays}
                  onChange={(e) => handlePrivacySettingsUpdate({ dataRetentionDays: parseInt(e.target.value) })}
                  disabled={previewMode}
                  min="1"
                  max="365"
                  className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-50"
                />
                <span className="text-sm text-gray-500">days</span>
              </div>
              <p className="text-xs text-gray-500 mt-1">
                Data will be automatically deleted after this period
              </p>
            </div>

            {/* Compliance Information */}
            <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
              <h4 className="text-sm font-medium text-blue-900 mb-2">Privacy Compliance</h4>
              <ul className="text-xs text-blue-800 space-y-1">
                <li>• All data collection follows GDPR and local privacy regulations</li>
                <li>• Users are informed about data collection before quiz starts</li>
                <li>• Behavioral data is used only for educational insights</li>
                <li>• Data can be deleted upon user request</li>
              </ul>
            </div>
          </div>
        )}
      </div>

      {/* Preview Mode Overlay */}
      {previewMode && (
        <div className="absolute inset-0 bg-blue-50 bg-opacity-50 flex items-center justify-center rounded-lg">
          <div className="bg-white p-6 rounded-lg shadow-lg border border-blue-200">
            <div className="flex items-center gap-3 mb-4">
              <Eye className="w-6 h-6 text-blue-600" />
              <h3 className="text-lg font-medium text-gray-900">Preview Mode</h3>
            </div>
            <p className="text-gray-600 mb-4">
              You are viewing the configuration in preview mode. 
              Switch to edit mode to make changes.
            </p>
            <button
              onClick={() => setPreviewMode(false)}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              Switch to Edit Mode
            </button>
          </div>
        </div>
      )}
    </div>
  );
};