import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Settings, Shield, Users, BarChart3, Bell, Database, Globe, 
  Lock, Eye, EyeOff, Save, RotateCcw, Check, X, AlertTriangle,
  Info, Zap, Palette, Monitor, Smartphone, Mail, Key, 
  Download, Upload, Trash2, RefreshCw, Clock, Calendar
} from 'lucide-react';
import styles from '../styles/EnhancedSettings.module.css';

const EnhancedSettings = () => {
  const [settings, setSettings] = useState({
    
    systemName: 'MKCart Admin',
    defaultCurrency: 'INR',
    timeZone: 'Asia/Kolkata',
    language: 'en',
    theme: 'dark',

    sessionTimeout: 30,
    passwordPolicy: 'strong',
    twoFactorAuth: true,
    loginAttempts: 5,
    passwordExpiry: 90,

    defaultUserRole: 'user',
    requireEmailVerification: true,
    autoActivateUsers: false,
    allowRegistration: true,

    dataRetention: 90,
    realTimeAnalytics: true,
    trackUserBehavior: true,
    analyticsEnabled: true,

    emailNotifications: true,
    pushNotifications: true,
    orderAlerts: true,
    systemAlerts: true,

    maintenanceMode: false,
    debugMode: false,
    autoBackup: true,
    backupFrequency: 'daily'
  });

  const [isLoading, setIsLoading] = useState(false);
  const [saveStatus, setSaveStatus] = useState(null);
  const [activeTab, setActiveTab] = useState('general');

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

  const handleSaveSettings = async () => {
    setIsLoading(true);
    setSaveStatus('saving');
    
    try {
      
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      setSaveStatus('success');
      setTimeout(() => setSaveStatus(null), 3000);
    } catch (error) {
      setSaveStatus('error');
      setTimeout(() => setSaveStatus(null), 3000);
    } finally {
      setIsLoading(false);
    }
  };

  const handleResetSettings = () => {
    if (window.confirm('Are you sure you want to reset all settings to defaults?')) {
      setSettings({
        systemName: 'MKCart Admin',
        defaultCurrency: 'INR',
        timeZone: 'Asia/Kolkata',
        language: 'en',
        theme: 'dark',
        sessionTimeout: 30,
        passwordPolicy: 'strong',
        twoFactorAuth: true,
        loginAttempts: 5,
        passwordExpiry: 90,
        defaultUserRole: 'user',
        requireEmailVerification: true,
        autoActivateUsers: false,
        allowRegistration: true,
        dataRetention: 90,
        realTimeAnalytics: true,
        trackUserBehavior: true,
        analyticsEnabled: true,
        emailNotifications: true,
        pushNotifications: true,
        orderAlerts: true,
        systemAlerts: true,
        maintenanceMode: false,
        debugMode: false,
        autoBackup: true,
        backupFrequency: 'daily'
      });
    }
  };

  const settingsTabs = [
    { id: 'general', label: 'General', icon: Settings },
    { id: 'security', label: 'Security', icon: Shield },
    { id: 'users', label: 'Users', icon: Users },
    { id: 'analytics', label: 'Analytics', icon: BarChart3 },
    { id: 'notifications', label: 'Notifications', icon: Bell },
    { id: 'system', label: 'System', icon: Database }
  ];

  const SettingItem = ({ label, type = 'text', value, onChange, options, description, icon: Icon, required = false }) => (
    <motion.div
      className={styles['setting-item-enhanced']}
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
    >
      <div className={styles['setting-label']}>
        {Icon && <Icon size={18} className={styles['setting-icon']} />}
        <label>
          {label}
          {required && <span className={styles['required']}>*</span>}
        </label>
      </div>
      
      {type === 'select' ? (
        <select
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className={styles['setting-input-enhanced']}
        >
          {options.map(option => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      ) : type === 'checkbox' ? (
        <label className={styles['setting-checkbox-enhanced']}>
          <input
            type="checkbox"
            checked={value}
            onChange={(e) => onChange(e.target.checked)}
          />
          <span className={styles['checkmark']}></span>
        </label>
      ) : type === 'number' ? (
        <input
          type="number"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className={styles['setting-input-enhanced']}
          min="1"
          max="1000"
        />
      ) : (
        <input
          type={type}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className={styles['setting-input-enhanced']}
        />
      )}
      
      {description && (
        <p className={styles['setting-description']}>{description}</p>
      )}
    </motion.div>
  );

  return (
    <div className={styles['enhanced-settings']}>
      {}
      <motion.div
        className={styles['settings-header']}
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <div className={styles['header-left']}>
          <h1>System Settings</h1>
          <p>Configure your system preferences and security settings</p>
        </div>
        <div className={styles['header-right']}>
          <div className={styles['save-status']}>
            {saveStatus === 'saving' && (
              <motion.div className={styles['status-saving']} initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
                <RefreshCw size={16} className={styles['spinning']} />
                Saving...
              </motion.div>
            )}
            {saveStatus === 'success' && (
              <motion.div className={styles['status-success']} initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
                <Check size={16} />
                Saved successfully!
              </motion.div>
            )}
            {saveStatus === 'error' && (
              <motion.div className={styles['status-error']} initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
                <X size={16} />
                Save failed
              </motion.div>
            )}
          </div>
        </div>
      </motion.div>

      {}
      <motion.div
        className={styles['settings-tabs']}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5, delay: 0.2 }}
      >
        {settingsTabs.map((tab) => (
          <button
            key={tab.id}
            className={`${styles['settings-tab']} ${activeTab === tab.id ? styles['active'] : ''}`}
            onClick={() => setActiveTab(tab.id)}
          >
            <tab.icon size={20} />
            {tab.label}
          </button>
        ))}
      </motion.div>

      {}
      <motion.div
        className={styles['settings-content-enhanced']}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5, delay: 0.4 }}
      >
        <AnimatePresence mode="wait">
          {activeTab === 'general' && (
            <motion.div
              key="general"
              className={styles['settings-section']}
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -20 }}
              transition={{ duration: 0.3 }}
            >
              <div className={styles['section-header']}>
                <Globe size={24} />
                <h2>General Settings</h2>
              </div>
              
              <div className={styles['settings-grid-enhanced']}>
                <SettingItem
                  label="System Name"
                  type="text"
                  value={settings.systemName}
                  onChange={(value) => handleSettingChange('general', 'systemName', value)}
                  description="The name displayed in the admin panel"
                  icon={Settings}
                  required
                />
                
                <SettingItem
                  label="Default Currency"
                  type="select"
                  value={settings.defaultCurrency}
                  onChange={(value) => handleSettingChange('general', 'defaultCurrency', value)}
                  options={[
                    { value: 'INR', label: 'Indian Rupee (₹)' },
                    { value: 'USD', label: 'US Dollar ($)' },
                    { value: 'EUR', label: 'Euro (€)' },
                    { value: 'GBP', label: 'British Pound (£)' }
                  ]}
                  description="Default currency for transactions"
                  icon={Palette}
                />
                
                <SettingItem
                  label="Time Zone"
                  type="select"
                  value={settings.timeZone}
                  onChange={(value) => handleSettingChange('general', 'timeZone', value)}
                  options={[
                    { value: 'Asia/Kolkata', label: 'Asia/Kolkata (IST)' },
                    { value: 'UTC', label: 'UTC' },
                    { value: 'America/New_York', label: 'America/New_York (EST)' },
                    { value: 'Europe/London', label: 'Europe/London (GMT)' }
                  ]}
                  description="System time zone for date/time display"
                  icon={Clock}
                />
                
                <SettingItem
                  label="Language"
                  type="select"
                  value={settings.language}
                  onChange={(value) => handleSettingChange('general', 'language', value)}
                  options={[
                    { value: 'en', label: 'English' },
                    { value: 'hi', label: 'Hindi' },
                    { value: 'es', label: 'Spanish' },
                    { value: 'fr', label: 'French' }
                  ]}
                  description="Default language for the interface"
                  icon={Globe}
                />
              </div>
            </motion.div>
          )}

          {activeTab === 'security' && (
            <motion.div
              key="security"
              className={styles['settings-section']}
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -20 }}
              transition={{ duration: 0.3 }}
            >
              <div className={styles['section-header']}>
                <Shield size={24} />
                <h2>Security Settings</h2>
              </div>
              
              <div className={styles['settings-grid-enhanced']}>
                <SettingItem
                  label="Session Timeout (minutes)"
                  type="number"
                  value={settings.sessionTimeout}
                  onChange={(value) => handleSettingChange('security', 'sessionTimeout', value)}
                  description="Auto-logout after inactivity"
                  icon={Clock}
                />
                
                <SettingItem
                  label="Password Policy"
                  type="select"
                  value={settings.passwordPolicy}
                  onChange={(value) => handleSettingChange('security', 'passwordPolicy', value)}
                  options={[
                    { value: 'strong', label: 'Strong (8+ chars, symbols)' },
                    { value: 'medium', label: 'Medium (6+ chars)' },
                    { value: 'weak', label: 'Weak (4+ chars)' }
                  ]}
                  description="Minimum password requirements"
                  icon={Lock}
                />
                
                <SettingItem
                  label="Two-Factor Authentication"
                  type="checkbox"
                  value={settings.twoFactorAuth}
                  onChange={(value) => handleSettingChange('security', 'twoFactorAuth', value)}
                  description="Require 2FA for admin accounts"
                  icon={Key}
                />
                
                <SettingItem
                  label="Max Login Attempts"
                  type="number"
                  value={settings.loginAttempts}
                  onChange={(value) => handleSettingChange('security', 'loginAttempts', value)}
                  description="Account lockout threshold"
                  icon={AlertTriangle}
                />
                
                <SettingItem
                  label="Password Expiry (days)"
                  type="number"
                  value={settings.passwordExpiry}
                  onChange={(value) => handleSettingChange('security', 'passwordExpiry', value)}
                  description="Force password change after days"
                  icon={Calendar}
                />
              </div>
            </motion.div>
          )}

          {activeTab === 'users' && (
            <motion.div
              key="users"
              className={styles['settings-section']}
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -20 }}
              transition={{ duration: 0.3 }}
            >
              <div className={styles['section-header']}>
                <Users size={24} />
                <h2>User Management</h2>
              </div>
              
              <div className={styles['settings-grid-enhanced']}>
                <SettingItem
                  label="Default User Role"
                  type="select"
                  value={settings.defaultUserRole}
                  onChange={(value) => handleSettingChange('users', 'defaultUserRole', value)}
                  options={[
                    { value: 'user', label: 'User' },
                    { value: 'admin', label: 'Admin' },
                    { value: 'moderator', label: 'Moderator' }
                  ]}
                  description="Default role for new registrations"
                  icon={Users}
                />
                
                <SettingItem
                  label="Require Email Verification"
                  type="checkbox"
                  value={settings.requireEmailVerification}
                  onChange={(value) => handleSettingChange('users', 'requireEmailVerification', value)}
                  description="Verify email before account activation"
                  icon={Mail}
                />
                
                <SettingItem
                  label="Auto-activate New Users"
                  type="checkbox"
                  value={settings.autoActivateUsers}
                  onChange={(value) => handleSettingChange('users', 'autoActivateUsers', value)}
                  description="Automatically activate new user accounts"
                  icon={Zap}
                />
                
                <SettingItem
                  label="Allow User Registration"
                  type="checkbox"
                  value={settings.allowRegistration}
                  onChange={(value) => handleSettingChange('users', 'allowRegistration', value)}
                  description="Enable public user registration"
                  icon={Users}
                />
              </div>
            </motion.div>
          )}

          {activeTab === 'analytics' && (
            <motion.div
              key="analytics"
              className={styles['settings-section']}
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -20 }}
              transition={{ duration: 0.3 }}
            >
              <div className={styles['section-header']}>
                <BarChart3 size={24} />
                <h2>Analytics Settings</h2>
              </div>
              
              <div className={styles['settings-grid-enhanced']}>
                <SettingItem
                  label="Data Retention Period (days)"
                  type="number"
                  value={settings.dataRetention}
                  onChange={(value) => handleSettingChange('analytics', 'dataRetention', value)}
                  description="How long to keep analytics data"
                  icon={Calendar}
                />
                
                <SettingItem
                  label="Enable Analytics"
                  type="checkbox"
                  value={settings.analyticsEnabled}
                  onChange={(value) => handleSettingChange('analytics', 'analyticsEnabled', value)}
                  description="Enable system analytics tracking"
                  icon={BarChart3}
                />
                
                <SettingItem
                  label="Real-time Analytics"
                  type="checkbox"
                  value={settings.realTimeAnalytics}
                  onChange={(value) => handleSettingChange('analytics', 'realTimeAnalytics', value)}
                  description="Enable real-time data updates"
                  icon={Zap}
                />
                
                <SettingItem
                  label="Track User Behavior"
                  type="checkbox"
                  value={settings.trackUserBehavior}
                  onChange={(value) => handleSettingChange('analytics', 'trackUserBehavior', value)}
                  description="Track user interactions and patterns"
                  icon={Eye}
                />
              </div>
            </motion.div>
          )}

          {activeTab === 'notifications' && (
            <motion.div
              key="notifications"
              className={styles['settings-section']}
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -20 }}
              transition={{ duration: 0.3 }}
            >
              <div className={styles['section-header']}>
                <Bell size={24} />
                <h2>Notification Settings</h2>
              </div>
              
              <div className={styles['settings-grid-enhanced']}>
                <SettingItem
                  label="Email Notifications"
                  type="checkbox"
                  value={settings.emailNotifications}
                  onChange={(value) => handleSettingChange('notifications', 'emailNotifications', value)}
                  description="Send notifications via email"
                  icon={Mail}
                />
                
                <SettingItem
                  label="Push Notifications"
                  type="checkbox"
                  value={settings.pushNotifications}
                  onChange={(value) => handleSettingChange('notifications', 'pushNotifications', value)}
                  description="Enable browser push notifications"
                  icon={Bell}
                />
                
                <SettingItem
                  label="Order Alerts"
                  type="checkbox"
                  value={settings.orderAlerts}
                  onChange={(value) => handleSettingChange('notifications', 'orderAlerts', value)}
                  description="Notify on new orders"
                  icon={AlertTriangle}
                />
                
                <SettingItem
                  label="System Alerts"
                  type="checkbox"
                  value={settings.systemAlerts}
                  onChange={(value) => handleSettingChange('notifications', 'systemAlerts', value)}
                  description="System maintenance and error alerts"
                  icon={Info}
                />
              </div>
            </motion.div>
          )}

          {activeTab === 'system' && (
            <motion.div
              key="system"
              className={styles['settings-section']}
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -20 }}
              transition={{ duration: 0.3 }}
            >
              <div className={styles['section-header']}>
                <Database size={24} />
                <h2>System Settings</h2>
              </div>
              
              <div className={styles['settings-grid-enhanced']}>
                <SettingItem
                  label="Maintenance Mode"
                  type="checkbox"
                  value={settings.maintenanceMode}
                  onChange={(value) => handleSettingChange('system', 'maintenanceMode', value)}
                  description="Enable maintenance mode (restricts access)"
                  icon={AlertTriangle}
                />
                
                <SettingItem
                  label="Debug Mode"
                  type="checkbox"
                  value={settings.debugMode}
                  onChange={(value) => handleSettingChange('system', 'debugMode', value)}
                  description="Enable debug logging (development only)"
                  icon={Monitor}
                />
                
                <SettingItem
                  label="Auto Backup"
                  type="checkbox"
                  value={settings.autoBackup}
                  onChange={(value) => handleSettingChange('system', 'autoBackup', value)}
                  description="Automatically backup system data"
                  icon={Database}
                />
                
                <SettingItem
                  label="Backup Frequency"
                  type="select"
                  value={settings.backupFrequency}
                  onChange={(value) => handleSettingChange('system', 'backupFrequency', value)}
                  options={[
                    { value: 'daily', label: 'Daily' },
                    { value: 'weekly', label: 'Weekly' },
                    { value: 'monthly', label: 'Monthly' }
                  ]}
                  description="How often to create backups"
                  icon={Calendar}
                />
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </motion.div>

      {}
      <motion.div
        className={styles['settings-actions-enhanced']}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5, delay: 0.6 }}
      >
        <button
          className={styles['reset-btn']}
          onClick={handleSaveSettings}
          disabled={isLoading}
        >
          {isLoading ? (
            <>
              <RefreshCw size={16} className={styles['spinning']} />
              Saving...
            </>
          ) : (
            <>
              <Save size={16} />
              Save All Settings
            </>
          )}
        </button>
        
        <button
          className={styles['reset-btn']}
          onClick={handleResetSettings}
          disabled={isLoading}
        >
          <RotateCcw size={16} />
          Reset to Defaults
        </button>
      </motion.div>
    </div>
  );
};

export default EnhancedSettings;