import React, { useState, useEffect } from 'react'
import { Box, Text } from 'ink'
import SelectInput from 'ink-select-input'
import TextInput from 'ink-text-input'
import fs from 'fs/promises'

/**
 * Settings Page - Configure Aura avatars
 */
const SettingsPage = ({ onBack }) => {
  const [mode, setMode] = useState('menu') // menu | input
  const [inputValue, setInputValue] = useState('')
  const [currentSetting, setCurrentSetting] = useState('')
  const [settings, setSettings] = useState({
    avatars: { aura: '🌀', user: '>' }
  })

  // 載入設定
  useEffect(() => {
    loadSettings()
  }, [])

  // 載入設定函數
  const loadSettings = async () => {
    try {
      const data = await fs.readFile('./.aura.json', 'utf-8')
      setSettings(JSON.parse(data))
    } catch {
      // 使用預設值
    }
  }

  // 儲存設定函數
  const saveSettings = async (newSettings) => {
    try {
      await fs.writeFile('./.aura.json', JSON.stringify(newSettings, null, 2))
    } catch (error) {
      console.error('Failed to save settings:', error)
    }
  }

  // 選單項目
  const menuItems = [
    { 
      label: `${settings.avatars.aura} Set Aura avatar`, 
      value: 'setAura' 
    },
    { 
      label: `${settings.avatars.user} Set User avatar`, 
      value: 'setUser' 
    },
    { 
      label: 'Reset to defaults', 
      value: 'reset' 
    },
    { 
      label: 'Exit', 
      value: 'exit' 
    }
  ]

  // 處理選單選擇
  const handleSelect = async (item) => {
    if (item.value === 'exit') {
      onBack()
    } else if (item.value === 'reset') {
      const defaultSettings = { avatars: { aura: '🌀', user: '>' } }
      await saveSettings(defaultSettings)
      setSettings(defaultSettings)
      onBack()
    } else {
      setCurrentSetting(item.value)
      setMode('input')
      setInputValue('')
    }
  }

  // 處理頭像輸入
  const handleAvatarSubmit = async (value) => {
    if (value && value.length > 0) {
      // 取得第一個完整的字符（包括 emoji）
      const char = value.trim()
      const newSettings = { ...settings }
      
      if (currentSetting === 'setAura') {
        newSettings.avatars.aura = char
      } else if (currentSetting === 'setUser') {
        newSettings.avatars.user = char
      }
      
      await saveSettings(newSettings)
      setSettings(newSettings)
      setMode('menu')
      setInputValue('')
    }
  }

  // 根據模式渲染不同介面
  if (mode === 'input') {
    return (
      <Box flexDirection="column" padding={1}>
        <Box paddingY={1} paddingX={2} borderColor='blue' borderStyle='round' width={'100%'}>
          <Text>
            <Text bold>Settings</Text> - Avatar Configuration
          </Text>
        </Box>
        
        <Box marginTop={2} flexDirection="column">
          <Text>
            {currentSetting === 'setAura' 
              ? 'Enter new Aura avatar (emoji or text):' 
              : 'Enter new User avatar (emoji or text):'}
          </Text>
          <Box marginTop={1} paddingX={1} borderColor='gray' borderStyle='single'>
            <Text color='blue'>{'> '}</Text>
            <TextInput
              value={inputValue}
              onChange={setInputValue}
              onSubmit={handleAvatarSubmit}
              placeholder="Enter avatar (e.g., 🐤, >, 👾)..."
              focus={true}
            />
          </Box>
          <Box marginTop={1}>
            <Text dimColor>Press Enter to save, or Ctrl+C to cancel</Text>
          </Box>
        </Box>
      </Box>
    )
  }

  return (
    <Box flexDirection="column" padding={1}>
      <Box paddingY={1} paddingX={2} borderColor='blue' borderStyle='round' width={'100%'}>
        <Text>
          <Text bold>Settings</Text> - Avatar Configuration
        </Text>
      </Box>
      
      <Box marginTop={2} flexDirection="column">
        <Text color='yellow'>Select an option:</Text>
        <Box marginTop={1}>
          <SelectInput items={menuItems} onSelect={handleSelect} />
        </Box>
      </Box>
      
      <Box marginTop={2}>
        <Text dimColor>
          Current: Aura = {settings.avatars.aura}  User = {settings.avatars.user}
        </Text>
      </Box>
    </Box>
  )
}

export default SettingsPage