import { createContext, useContext, useState, useEffect, ReactNode } from 'react'

export interface AutopilotSettings {
  autoExecute: boolean
  // Intelligent mode settings
  interval: number
  timeframe: string
  exchange_id: number
}

const DEFAULT_SETTINGS: AutopilotSettings = {
  autoExecute: false,
  interval: 60.0,
  timeframe: '1h',
  exchange_id: 1,
}


const STORAGE_KEY = 'autopilot_settings'

interface AutopilotSettingsContextType {
  settings: AutopilotSettings
  updateSettings: (updates: Partial<AutopilotSettings>) => void
  resetSettings: () => void
}

const AutopilotSettingsContext = createContext<AutopilotSettingsContextType | undefined>(undefined)

export function AutopilotSettingsProvider({ children }: { children: ReactNode }) {
  const [settings, setSettings] = useState<AutopilotSettings>(() => {
    // Load from localStorage on initialization
    try {
      const stored = localStorage.getItem(STORAGE_KEY)
      if (stored) {
        const parsed = JSON.parse(stored)
        return { ...DEFAULT_SETTINGS, ...parsed }
      }
    } catch (error) {
      console.error('Failed to load autopilot settings from localStorage:', error)
    }
    return DEFAULT_SETTINGS
  })

  // Save to localStorage whenever settings change
  useEffect(() => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(settings))
    } catch (error) {
      console.error('Failed to save autopilot settings to localStorage:', error)
    }
  }, [settings])

  const updateSettings = (updates: Partial<AutopilotSettings>) => {
    setSettings((prev) => ({ ...prev, ...updates }))
  }

  const resetSettings = () => {
    setSettings(DEFAULT_SETTINGS)
    try {
      localStorage.removeItem(STORAGE_KEY)
    } catch (error) {
      console.error('Failed to remove autopilot settings from localStorage:', error)
    }
  }

  return (
    <AutopilotSettingsContext.Provider value={{ settings, updateSettings, resetSettings }}>
      {children}
    </AutopilotSettingsContext.Provider>
  )
}

export function useAutopilotSettings() {
  const context = useContext(AutopilotSettingsContext)
  if (context === undefined) {
    throw new Error('useAutopilotSettings must be used within an AutopilotSettingsProvider')
  }
  return context.settings
}

export function useUpdateAutopilotSettings() {
  const context = useContext(AutopilotSettingsContext)
  if (context === undefined) {
    throw new Error('useUpdateAutopilotSettings must be used within an AutopilotSettingsProvider')
  }
  return context.updateSettings
}

export function useAutopilotSettingsContext() {
  const context = useContext(AutopilotSettingsContext)
  if (context === undefined) {
    throw new Error('useAutopilotSettingsContext must be used within an AutopilotSettingsProvider')
  }
  return context
}

