import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'
import { endpoints, getCurrentDataLanguage, setCurrentDataLanguage } from '../api/client'

type DataLanguage = 'he' | 'en'

interface DataLanguageContextValue {
  dataLanguage: DataLanguage
  setDataLanguage: (language: DataLanguage) => Promise<boolean>
  isSavingLanguage: boolean
}

const initialLanguage = (window.bmaiSettings?.dataLanguage === 'en' ? 'en' : 'he') as DataLanguage
setCurrentDataLanguage(initialLanguage)

const DataLanguageContext = createContext<DataLanguageContextValue>({
  dataLanguage: initialLanguage,
  setDataLanguage: async () => false,
  isSavingLanguage: false,
})

export function DataLanguageProvider({ children }: { children: ReactNode }) {
  const [dataLanguage, setDataLanguageState] = useState<DataLanguage>(initialLanguage)
  const [isSavingLanguage, setIsSavingLanguage] = useState(false)

  const setDataLanguage = useCallback(async (language: DataLanguage) => {
    const nextLanguage = language === 'en' ? 'en' : 'he'
    const previousLanguage = getCurrentDataLanguage() === 'en' ? 'en' : 'he'

    if (nextLanguage === previousLanguage) {
      return true
    }

    setDataLanguageState(nextLanguage)
    setCurrentDataLanguage(nextLanguage)
    if (window.bmaiSettings) {
      window.bmaiSettings.dataLanguage = nextLanguage
    }
    setIsSavingLanguage(true)

    try {
      await endpoints.updateSettings({ data_language: nextLanguage })
      return true
    } catch {
      setDataLanguageState(previousLanguage)
      setCurrentDataLanguage(previousLanguage)
      if (window.bmaiSettings) {
        window.bmaiSettings.dataLanguage = previousLanguage
      }
      return false
    } finally {
      setIsSavingLanguage(false)
    }
  }, [])

  const value = useMemo<DataLanguageContextValue>(() => ({
    dataLanguage,
    setDataLanguage,
    isSavingLanguage,
  }), [dataLanguage, isSavingLanguage, setDataLanguage])

  return (
    <DataLanguageContext.Provider value={value}>
      {children}
    </DataLanguageContext.Provider>
  )
}

export function useDataLanguage() {
  return useContext(DataLanguageContext)
}
