import { useEffect, useState } from 'react'
import { ListDevices, ConnectDevice, DisconnectDevice } from '@/wailsjs/go/main/App'
import { EventsOn, EventsOff } from '@/wailsjs/runtime/runtime'
import type { device } from '@/wailsjs/go/models'

export type Device = device.Device

export function useDevices() {
  const [devices, setDevices] = useState<Device[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    ListDevices()
      .then((d) => setDevices(d ?? []))
      .catch((e) => setError(String(e)))
      .finally(() => setLoading(false))

    EventsOn('devices:changed', (d: Device[]) => setDevices(d ?? []))
    return () => EventsOff('devices:changed')
  }, [])

  async function connect(address: string) {
    await ConnectDevice(address)
  }

  async function disconnect(deviceId: string) {
    await DisconnectDevice(deviceId)
  }

  return { devices, loading, error, connect, disconnect }
}
