'use client'

import { useState, useEffect } from 'react'

export default function Settings() {
  const [settings, setSettings] = useState(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('settings')
      if (saved) {
        try {
          return JSON.parse(saved)
        } catch (e) {
          return getDefaultSettings()
        }
      }
    }
    return getDefaultSettings()
  })

  // getDefaultSettings
  function getDefaultSettings() {
    return {
      interface: {
        timeBasedGreeting: true,
        compactSidebar: false,
        enableAnimations: true,
        showSnowEffect: false,
      },
      editor: {
        toolbarPosition: 'bottom',
        fontSize: 14,
        tabSize: 2,
        wordWrap: true,
        minimap: false,
        lineNumbers: true,
      },
      layout: {
        scriptsGridColumns: 'auto',
      }
    }
  }

  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('settings', JSON.stringify(settings))
      window.dispatchEvent(new CustomEvent('settingsChanged', { detail: settings }))
    }
  }, [settings])

  // updateSetting
  const updateSetting = (category, key, value) => {
    console.log('updateSetting:', category, key, value)
    setSettings(prev => ({
      ...prev,
      [category]: {
        ...prev[category],
        [key]: value
      }
    }))
  }

  // resetSettings
  const resetSettings = () => {
    const defaults = getDefaultSettings()
    setSettings(defaults)
  }

  return (
    <div className="flex justify-center p-8">
      <div className="max-w-[1100px] w-full">
        <div 
          className="relative rounded-2xl border p-8 mb-6 overflow-hidden"
          style={{
            backgroundColor: 'rgba(10, 10, 10, 0.6)',
            borderColor: '#1a1a1a',
            backdropFilter: 'blur(20px)',
          }}
        >
          <div 
            className="absolute inset-0 opacity-30"
            style={{
              background: 'radial-gradient(circle at 20% 50%, rgba(59, 130, 246, 0.15), transparent 50%), radial-gradient(circle at 80% 50%, rgba(168, 85, 247, 0.15), transparent 50%)',
            }}
          />
          
          <div className="relative z-10">
            <h1 
              className="text-4xl font-bold mb-2"
              style={{ 
                color: '#ffffff',
                textShadow: '0 0 30px rgba(255, 255, 255, 0.1)',
              }}
            >
              Settings
            </h1>
            <p 
              className="text-sm"
              style={{ color: '#6b7280' }}
            >
              Customize your Aetheris experience
            </p>
          </div>
        </div>

        <div className="space-y-4">
          <SettingsSection title="INTERFACE">
            <SettingToggle
              label="Time-based Greeting"
              description="Show personalized greetings based on time of day"
              checked={settings.interface.timeBasedGreeting}
              onChange={(checked) => updateSetting('interface', 'timeBasedGreeting', checked)}
            />
            
            <SettingToggle
              label="Compact Sidebar"
              description="Reduce sidebar width for more workspace"
              checked={settings.interface.compactSidebar}
              onChange={(checked) => updateSetting('interface', 'compactSidebar', checked)}
            />
            
            <SettingToggle
              label="Enable Animations"
              description="Smooth transitions and visual effects"
              checked={settings.interface.enableAnimations}
              onChange={(checked) => updateSetting('interface', 'enableAnimations', checked)}
            />
            
            <SettingToggle
              label="Let it snow!"
              description="❄️"
              checked={settings.interface.showSnowEffect}
              onChange={(checked) => updateSetting('interface', 'showSnowEffect', checked)}
            />
          </SettingsSection>

          <SettingsSection title="EDITOR">
            <SettingSelect
              label="Toolbar Position"
              description="Choose where the toolbar appears"
              value={settings.editor.toolbarPosition}
              options={[
                { value: 'top', label: 'Top' },
                { value: 'bottom', label: 'Bottom' },
              ]}
              onChange={(value) => updateSetting('editor', 'toolbarPosition', value)}
            />
            
            <SettingSlider
              label="Font Size"
              description="Adjust code editor text size"
              value={settings.editor.fontSize}
              min={10}
              max={24}
              step={1}
              unit="px"
              onChange={(value) => updateSetting('editor', 'fontSize', value)}
            />
            
            <SettingSlider
              label="Tab Size"
              description="Number of spaces per tab"
              value={settings.editor.tabSize}
              min={2}
              max={8}
              step={2}
              unit=""
              onChange={(value) => updateSetting('editor', 'tabSize', value)}
            />
            
            <SettingToggle
              label="Word Wrap"
              description="Wrap long lines automatically"
              checked={settings.editor.wordWrap}
              onChange={(checked) => updateSetting('editor', 'wordWrap', checked)}
            />
            
            <SettingToggle
              label="Minimap"
              description="Show code overview minimap"
              checked={settings.editor.minimap}
              onChange={(checked) => updateSetting('editor', 'minimap', checked)}
            />
            
            <SettingToggle
              label="Line Numbers"
              description="Display line numbers in editor"
              checked={settings.editor.lineNumbers}
              onChange={(checked) => updateSetting('editor', 'lineNumbers', checked)}
            />
          </SettingsSection>

          <SettingsSection title="LAYOUT">
            <SettingSelect
              label="Scripts Grid Columns"
              description="Number of columns in scripts view"
              value={settings.layout.scriptsGridColumns}
              options={[
                { value: 'auto', label: 'Auto' },
                { value: '1', label: '1 Column' },
                { value: '2', label: '2 Columns' },
                { value: '3', label: '3 Columns' },
                { value: '4', label: '4 Columns' },
              ]}
              onChange={(value) => updateSetting('layout', 'scriptsGridColumns', value)}
            />
          </SettingsSection>

          <div 
            className="rounded-2xl border p-6"
            style={{
              backgroundColor: 'rgba(10, 10, 10, 0.6)',
              borderColor: '#1a1a1a',
              backdropFilter: 'blur(20px)',
            }}
          >
            <button
              onClick={resetSettings}
              className="px-6 py-3 rounded-xl font-medium transition-all duration-200"
              style={{
                backgroundColor: 'rgba(239, 68, 68, 0.1)',
                border: '1px solid rgba(239, 68, 68, 0.3)',
                color: '#ef4444',
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = 'rgba(239, 68, 68, 0.2)'
                e.currentTarget.style.borderColor = 'rgba(239, 68, 68, 0.5)'
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = 'rgba(239, 68, 68, 0.1)'
                e.currentTarget.style.borderColor = 'rgba(239, 68, 68, 0.3)'
              }}
            >
              Reset to Defaults
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

function SettingsSection({ title, children }) {
  return (
    <div 
      className="rounded-2xl border p-6"
      style={{
        backgroundColor: 'rgba(10, 10, 10, 0.6)',
        borderColor: '#1a1a1a',
        backdropFilter: 'blur(20px)',
      }}
    >
      <h2 
        className="text-xs font-semibold uppercase tracking-wider mb-4"
        style={{ color: '#606060' }}
      >
        {title}
      </h2>
      <div className="space-y-6">
        {children}
      </div>
    </div>
  )
}

function SettingToggle({ label, description, checked, onChange }) {
  return (
    <div className="flex items-center justify-between">
      <div className="flex-1">
        <div 
          className="text-sm font-medium mb-1"
          style={{ color: '#ffffff' }}
        >
          {label}
        </div>
        <div 
          className="text-xs"
          style={{ color: '#a0a0a0' }}
        >
          {description}
        </div>
      </div>
      <button
        onClick={() => onChange(!checked)}
        className="relative w-11 h-6 rounded-full transition-all duration-200"
        style={{
          backgroundColor: checked ? '#3b82f6' : '#2a2a2a',
        }}
      >
        <div
          className="absolute top-1 w-4 h-4 rounded-full transition-all duration-200"
          style={{
            left: checked ? '24px' : '4px',
            backgroundColor: '#ffffff',
          }}
        />
      </button>
    </div>
  )
}

function SettingSelect({ label, description, value, options, onChange }) {
  return (
    <div className="flex items-center justify-between">
      <div className="flex-1">
        <div 
          className="text-sm font-medium mb-1"
          style={{ color: '#ffffff' }}
        >
          {label}
        </div>
        <div 
          className="text-xs"
          style={{ color: '#a0a0a0' }}
        >
          {description}
        </div>
      </div>
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 cursor-pointer"
        style={{
          backgroundColor: '#1a1a1a',
          border: '1px solid #2a2a2a',
          color: '#ffffff',
          outline: 'none',
        }}
      >
        {options.map(option => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
      </select>
    </div>
  )
}

function SettingSlider({ label, description, value, min, max, step, unit, onChange }) {
  return (
    <div>
      <div className="flex items-center justify-between mb-3">
        <div className="flex-1">
          <div 
            className="text-sm font-medium mb-1"
            style={{ color: '#ffffff' }}
          >
            {label}
          </div>
          <div 
            className="text-xs"
            style={{ color: '#a0a0a0' }}
          >
            {description}
          </div>
        </div>
        <div 
          className="text-sm font-medium"
          style={{ color: '#3b82f6' }}
        >
          {value}{unit}
        </div>
      </div>
      <input
        type="range"
        min={min}
        max={max}
        step={step}
        value={value}
        onChange={(e) => onChange(parseInt(e.target.value))}
        className="w-full h-2 rounded-full appearance-none cursor-pointer"
        style={{
          background: `linear-gradient(to right, #3b82f6 0%, #3b82f6 ${((value - min) / (max - min)) * 100}%, #2a2a2a ${((value - min) / (max - min)) * 100}%, #2a2a2a 100%)`,
        }}
      />
    </div>
  )
}
