import chadApi from '#shared/chad-api'
import { createGlobalState, useLocalStorage, watchDebounced } from '@vueuse/core'

export interface SyncedPreferences {
  toggleInputHotkey: string
  toggleOutputHotkey: string
  volumes: Record<Client['id'], number>
}

export const usePreferences = createGlobalState(() => {
  const { videoInputs, audioInputs, audioOutputs } = useDevices()

  const synced = ref(false)

  const inputDeviceId = useLocalStorage<MediaDeviceInfo['deviceId']>('INPUT_DEVICE_ID', 'default')
  const outputDeviceId = useLocalStorage<MediaDeviceInfo['deviceId']>('OUTPUT_DEVICE_ID', 'default')
  const videoDeviceId = useLocalStorage<MediaDeviceInfo['deviceId']>('VIDEO_DEVICE_ID', 'default')

  const autoGainControl = useLocalStorage('AUTO_GAIN_CONTROL', false)
  const noiseSuppression = useLocalStorage('NOISE_SUPPRESSION', true)
  const echoCancellation = useLocalStorage('ECHO_CANCELLATION', true)

  const toggleInputHotkey = ref<SyncedPreferences['toggleInputHotkey']>('')
  const toggleOutputHotkey = ref<SyncedPreferences['toggleOutputHotkey']>('')

  const inputDeviceExist = computed(() => {
    return audioInputs.value.some(device => device.deviceId === inputDeviceId.value)
  })

  const outputDeviceExist = computed(() => {
    return audioOutputs.value.some(device => device.deviceId === outputDeviceId.value)
  })

  const videoDeviceExist = computed(() => {
    return videoInputs.value.some(device => device.deviceId === videoDeviceId.value)
  })

  watchDebounced(
    [toggleInputHotkey, toggleOutputHotkey],
    async ([toggleInputHotkey, toggleOutputHotkey]) => {
      try {
        await chadApi(
          '/preferences',
          {
            method: 'PATCH',
            body: {
              toggleInputHotkey,
              toggleOutputHotkey,
            },
          },
        )
      }
      catch {}
    },
    { debounce: 1000 },
  )

  return {
    synced,
    inputDeviceId,
    outputDeviceId,
    videoDeviceId,
    autoGainControl,
    noiseSuppression,
    echoCancellation,
    toggleInputHotkey,
    toggleOutputHotkey,
    inputDeviceExist,
    outputDeviceExist,
    videoDeviceExist,
  }
})
