import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { refDebounced } from '@vueuse/core'
import { fetchActiveEncounters } from '@/api/encounters'
import { filterEncounters, hasWardFilters } from '@/composables/wardFilter'
import { sortEncounters } from '@/composables/wardSort'
import { useSettingsStore } from '@/stores/settings'

export const useWardStore = defineStore('ward', () => {
  const encounters = ref([])
  const loading = ref(false)
  const error = ref(null)
  const department = ref(null)
  const searchInput = ref('')
  const debouncedSearch = refDebounced(searchInput, 300)
  const filters = ref({
    hasAlerts: false,
    sepsisActive: false,
    critical: false,
  })
  const settings = useSettingsStore()

  const filteredEncounters = computed(() =>
    filterEncounters(encounters.value, {
      search: debouncedSearch.value,
      ...filters.value,
    }),
  )

  const displayEncounters = computed(() =>
    sortEncounters(
      filteredEncounters.value,
      settings.wardSortField,
      settings.wardSortDirection,
    ),
  )

  const hasActiveFilters = computed(() =>
    hasWardFilters({
      search: debouncedSearch.value,
      ...filters.value,
    }),
  )

  const criticalCount = computed(() =>
    encounters.value.filter(e => (e.news2Score ?? 0) >= 7).length,
  )

  async function loadEncounters() {
    loading.value = true
    error.value = null
    try {
      const data = await fetchActiveEncounters(department.value)
      encounters.value = data.items
    } catch (e) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  function setDepartment(dept) {
    department.value = dept
    loadEncounters()
  }

  function setSort(field) {
    settings.setWardSort(field)
  }

  function setSearchInput(value) {
    searchInput.value = value
  }

  function toggleFilter(key) {
    filters.value[key] = !filters.value[key]
  }

  function clearFilters() {
    searchInput.value = ''
    filters.value = {
      hasAlerts: false,
      sepsisActive: false,
      critical: false,
    }
  }

  return {
    encounters,
    loading,
    error,
    department,
    searchInput,
    filters,
    filteredEncounters,
    displayEncounters,
    hasActiveFilters,
    criticalCount,
    loadEncounters,
    setDepartment,
    setSort,
    setSearchInput,
    toggleFilter,
    clearFilters,
  }
})
