import { ref, computed, watch } from 'vue'

export function useResourceFilter (store, opts = {}) {
  const selectedResIds = ref(JSON.parse(localStorage.getItem('sbv2-resIds') || '[]'))
  const filterStatus = ref(localStorage.getItem('sbv2-filterStatus') || '')
  const filterGroup = ref(localStorage.getItem('sbv2-filterGroup') || '')
  const filterTags = ref(JSON.parse(localStorage.getItem('sbv2-filterTags') || '[]'))
  // Default 'human' = show only techs. Materials are secondary and
  // accessed via the resource-type dropdown when needed. Once the user
  // explicitly picks something else (incl. ''), it's persisted.
  const filterResourceType = ref(localStorage.getItem('sbv2-filterResType') ?? 'human')  // '' | 'human' | 'material'
  const searchQuery = ref('')
  const techSort = ref(localStorage.getItem('sbv2-techSort') || 'default')
  const manualOrder = ref(JSON.parse(localStorage.getItem('sbv2-techOrder') || '[]'))
  const resSelectorOpen = ref(false)
  const tempSelectedIds = ref([])
  const dragReorderTech = ref(null)
  const hideAbsent = ref(false)  // Quick toggle: hide techs absent on current day

  watch(selectedResIds, v => localStorage.setItem('sbv2-resIds', JSON.stringify(v)), { deep: true })
  watch(filterStatus, v => localStorage.setItem('sbv2-filterStatus', v))
  watch(filterGroup, v => localStorage.setItem('sbv2-filterGroup', v))
  watch(filterResourceType, v => localStorage.setItem('sbv2-filterResType', v))
  watch(techSort, v => localStorage.setItem('sbv2-techSort', v))

  // Unique groups extracted from technicians
  const availableGroups = computed(() => {
    const groups = new Set()
    for (const t of store.technicians) {
      if (t.group) groups.add(t.group)
    }
    return [...groups].sort()
  })

  // Resource categories for material resources
  const availableCategories = computed(() => {
    const cats = new Set()
    for (const t of store.technicians) {
      if (t.resourceCategory) cats.add(t.resourceCategory)
    }
    return [...cats].sort()
  })

  // Count by type
  const humanCount = computed(() => store.technicians.filter(t => t.resourceType !== 'material').length)
  const materialCount = computed(() => store.technicians.filter(t => t.resourceType === 'material').length)

  const showInactive = ref(false)

  const filteredResources = computed(() => {
    let list = store.technicians
    // Hide permanently inactive techs unless explicitly showing them or filtering for them
    // Temporarily absent (off) techs stay visible so absence blocks render on the timeline
    if (!showInactive.value && filterStatus.value !== 'inactive') list = list.filter(t => t.status !== 'inactive')
    if (filterResourceType.value) list = list.filter(t => (t.resourceType || 'human') === filterResourceType.value)
    if (searchQuery.value) { const q = searchQuery.value.toLowerCase(); list = list.filter(t => t.fullName.toLowerCase().includes(q)) }
    if (filterStatus.value) list = list.filter(t => (t.status||'available') === filterStatus.value)
    if (filterGroup.value) list = list.filter(t => t.group === filterGroup.value)
    if (selectedResIds.value.length) list = list.filter(t => selectedResIds.value.includes(t.id))
    if (filterTags.value.length) list = list.filter(t => filterTags.value.every(ft => (t.tags||[]).includes(ft)))
    // Quick toggle: hide techs absent on the current viewed day
    if (hideAbsent.value && opts.isAbsentOnDay) list = list.filter(t => !opts.isAbsentOnDay(t))
    // Sort: humans first, then material; within each, apply chosen sort
    list = [...list].sort((a, b) => {
      const aType = a.resourceType === 'material' ? 1 : 0
      const bType = b.resourceType === 'material' ? 1 : 0
      if (aType !== bType) return aType - bType
      if (techSort.value === 'alpha') return a.fullName.split(' ').pop().toLowerCase().localeCompare(b.fullName.split(' ').pop().toLowerCase())
      if (techSort.value === 'load' && opts.getLoadH) return (opts.getLoadH(a) || 0) - (opts.getLoadH(b) || 0)
      if (techSort.value === 'manual' && manualOrder.value.length) {
        const order = manualOrder.value
        return (order.indexOf(a.id) === -1 ? 999 : order.indexOf(a.id)) - (order.indexOf(b.id) === -1 ? 999 : order.indexOf(b.id))
      }
      return 0
    })
    return list
  })

  // Resources grouped by tech_group for visual grouping
  const groupedResources = computed(() => {
    const groups = new Map()
    for (const t of filteredResources.value) {
      const g = t.group || ''
      if (!groups.has(g)) groups.set(g, [])
      groups.get(g).push(t)
    }
    // Sort: named groups first (alphabetically), then ungrouped last
    const sorted = [...groups.entries()].sort((a, b) => {
      if (!a[0] && b[0]) return 1
      if (a[0] && !b[0]) return -1
      return a[0].localeCompare(b[0])
    })
    return sorted.map(([name, techs]) => ({ name, label: name || 'Non assigné', techs }))
  })

  function onTechReorderStart (e, tech) {
    dragReorderTech.value = tech
    e.dataTransfer.effectAllowed = 'move'
    e.dataTransfer.setData('text/plain', 'reorder')
  }
  function onTechReorderDrop (e, targetTech) {
    e.preventDefault()
    if (!dragReorderTech.value || dragReorderTech.value.id === targetTech.id) { dragReorderTech.value = null; return }
    techSort.value = 'manual'
    const ids = filteredResources.value.map(t => t.id)
    const fromIdx = ids.indexOf(dragReorderTech.value.id), toIdx = ids.indexOf(targetTech.id)
    ids.splice(fromIdx, 1); ids.splice(toIdx, 0, dragReorderTech.value.id)
    manualOrder.value = ids; localStorage.setItem('sbv2-techOrder', JSON.stringify(ids))
    dragReorderTech.value = null
  }

  function openResSelector () { tempSelectedIds.value = [...selectedResIds.value]; resSelectorOpen.value = true }
  function applyResSelector () { selectedResIds.value = [...tempSelectedIds.value]; resSelectorOpen.value = false }
  function toggleTempRes (id) {
    const idx = tempSelectedIds.value.indexOf(id)
    if (idx >= 0) tempSelectedIds.value.splice(idx, 1); else tempSelectedIds.value.push(id)
  }
  function clearFilters () { selectedResIds.value = []; filterStatus.value = ''; filterGroup.value = ''; filterResourceType.value = ''; searchQuery.value = ''; filterTags.value = []; showInactive.value = false; hideAbsent.value = false; localStorage.removeItem('sbv2-filterTags'); localStorage.removeItem('sbv2-filterGroup'); localStorage.removeItem('sbv2-filterResType') }

  // Count of inactive techs (for UI indicator)
  const inactiveCount = computed(() => store.technicians.filter(t => !t.active).length)

  return {
    selectedResIds, filterStatus, filterGroup, filterResourceType, filterTags, searchQuery, techSort, manualOrder,
    showInactive, hideAbsent, inactiveCount, humanCount, materialCount, availableCategories,
    filteredResources, groupedResources, availableGroups, resSelectorOpen, tempSelectedIds, dragReorderTech,
    openResSelector, applyResSelector, toggleTempRes, clearFilters,
    onTechReorderStart, onTechReorderDrop,
  }
}
