import { computed, onMounted, ref } from 'vue'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'
import { listExternalSystems } from '../services/external-system.service'
import {
  externalSystemStatusLabel,
  getExternalSystemStatus,
} from '../utils/external-system.utils'
import type { ExternalSystem } from '../types/external-system.types'

export function useExternalSystemList() {
  const search = ref('')
  const loading = ref(false)
  const error = ref<string | null>(null)
  const allSystems = ref<ExternalSystem[]>([])

  const systems = computed(() => {
    const query = search.value.trim().toLowerCase()
    if (!query) {
      return allSystems.value
    }

    return allSystems.value.filter((system) => {
      const haystack = [
        system.name,
        system.code,
        system.description,
        externalSystemStatusLabel(getExternalSystemStatus(system)),
      ]
        .join(' ')
        .toLowerCase()

      return haystack.includes(query)
    })
  })

  const availableCount = computed(
    () => systems.value.filter((system) => getExternalSystemStatus(system) === 'available').length,
  )

  function getSystemById(id: string): ExternalSystem | undefined {
    return allSystems.value.find((system) => system.id === id)
  }

  async function fetchSystems() {
    loading.value = true
    error.value = null

    try {
      allSystems.value = await listExternalSystems()
    } catch (err) {
      error.value = getApiErrorMessage(err, 'Gagal memuatkan senarai sistem luaran.')
      allSystems.value = []
    } finally {
      loading.value = false
    }
  }

  onMounted(() => {
    fetchSystems()
  })

  return {
    systems,
    search,
    loading,
    error,
    availableCount,
    getSystemById,
    fetchSystems,
  }
}
