const settingsService = require('./settings-store.js')
const {
  getWxApi
} = require('../utils/base-utils.js')

const TAB_ITEMS = [
  {
    pagePath: 'pages/home/home',
    text: '连接',
    iconPath: 'assets/tab/home.png',
    selectedIconPath: 'assets/tab/home-active.png',
    darkIconPath: 'assets/tab/home-dark.png',
    darkSelectedIconPath: 'assets/tab/home-active-dark.png'
  },
  {
    pagePath: 'pages/communication/communication',
    text: '通讯',
    iconPath: 'assets/tab/control.png',
    selectedIconPath: 'assets/tab/control-active.png',
    darkIconPath: 'assets/tab/control-dark.png',
    darkSelectedIconPath: 'assets/tab/control-active-dark.png'
  },
  {
    pagePath: 'pages/params/params',
    text: '参数',
    iconPath: 'assets/tab/params.png',
    selectedIconPath: 'assets/tab/params-active.png',
    darkIconPath: 'assets/tab/params-dark.png',
    darkSelectedIconPath: 'assets/tab/params-active-dark.png'
  },
  {
    pagePath: 'pages/settings/settings',
    text: '设置',
    iconPath: 'assets/tab/settings.png',
    selectedIconPath: 'assets/tab/settings-active.png',
    darkIconPath: 'assets/tab/settings-dark.png',
    darkSelectedIconPath: 'assets/tab/settings-active-dark.png'
  }
]

const state = {
  themeMode: 'light',
  themeClass: ''
}

let initialized = false
let unsubscribeSettings = null
const subscribers = []

function normalizeTheme(theme) {
  return theme === 'dark' ? 'dark' : (theme === 'light' ? 'light' : '')
}

function getSystemTheme() {
  try {
    const wxApi = getWxApi()
    const appBaseInfo = typeof wxApi.getAppBaseInfo === 'function' ? wxApi.getAppBaseInfo() : {}
    const appTheme = normalizeTheme(appBaseInfo.theme)
    if (appTheme) return appTheme

    const systemInfo = typeof wxApi.getSystemInfoSync === 'function' ? wxApi.getSystemInfoSync() : {}
    const systemTheme = normalizeTheme(systemInfo.theme)
    if (systemTheme) return systemTheme

    const windowInfo = typeof wxApi.getWindowInfo === 'function' ? wxApi.getWindowInfo() : {}
    const windowTheme = normalizeTheme(windowInfo.theme)
    if (windowTheme) return windowTheme

    return 'light'
  } catch (error) {
    return 'light'
  }
}

function getThemeState(themeMode) {
  const isDark = themeMode === 'dark'

  return {
    themeClass: isDark ? 'theme-dark' : '',
    themeMode: isDark ? 'dark' : 'light'
  }
}

function getEffectiveThemeMode() {
  const settings = settingsService.getState()
  if (settings.nightModeFollowSystem) return getSystemTheme()

  return settings.nightModeEnabled ? 'dark' : 'light'
}

function setState(nextState) {
  Object.assign(state, nextState)
  applyTabBarStyle()

  subscribers.slice().forEach((subscriber) => {
    subscriber(getState())
  })
}

function refreshThemeState() {
  setState(getThemeState(getEffectiveThemeMode()))
}

function applyTabBarStyle() {
  const wxApi = getWxApi()
  if (typeof wxApi.setTabBarStyle !== 'function') return

  const isDark = state.themeMode === 'dark'

  try {
    wxApi.setTabBarStyle({
      backgroundColor: isDark ? '#111827' : '#ffffff',
      borderStyle: isDark ? 'white' : 'black',
      color: isDark ? '#94a3b8' : '#64748b',
      selectedColor: isDark ? '#5eead4' : '#0f766e'
    })
    if (typeof wxApi.setTabBarItem === 'function') {
      TAB_ITEMS.forEach((item, index) => {
        wxApi.setTabBarItem({
          index,
          pagePath: item.pagePath,
          text: item.text,
          iconPath: isDark ? item.darkIconPath : item.iconPath,
          selectedIconPath: isDark ? item.darkSelectedIconPath : item.selectedIconPath
        })
      })
    }
  } catch (error) {}
}

function init() {
  settingsService.init()

  if (!unsubscribeSettings) {
    unsubscribeSettings = settingsService.subscribe(() => {
      refreshThemeState()
    })
  }

  refreshThemeState()

  if (initialized) return

  const wxApi = getWxApi()
  if (typeof wxApi.onThemeChange === 'function') {
    wxApi.onThemeChange((res) => {
      if (!settingsService.getState().nightModeFollowSystem) return

      setState(getThemeState(normalizeTheme(res && res.theme) || getSystemTheme()))
    })
  }

  initialized = true
}

function getState() {
  return {
    ...state
  }
}

function subscribe(subscriber) {
  if (typeof subscriber !== 'function') return () => {}

  subscribers.push(subscriber)
  subscriber(getState())

  return () => {
    const index = subscribers.indexOf(subscriber)
    if (index >= 0) subscribers.splice(index, 1)
  }
}

function syncWithSystemTheme() {
  init()
  refreshThemeState()
}

module.exports = {
  getState,
  init,
  subscribe,
  syncWithSystemTheme
}
