import { computed, ref } from 'vue'

import { isPlaceholderManagerName, normalizeText } from './employeeManagementModel.js'

export function useEmployeeManagementPickers(options = {}) {
  const selectedEmployee = options.selectedEmployee
  const employees = options.employees
  const employeeForm = options.employeeForm
  const organizationUnitOptions = options.organizationUnitOptions
  const managerPickerOpen = ref(false)
  const managerSearchKeyword = ref('')
  const departmentPickerOpen = ref(false)
  const departmentSearchKeyword = ref('')

  const managerOptions = computed(() => {
    const currentId = selectedEmployee.value?.id
    return employees.value.filter((item) => item.id !== currentId)
  })
  const filteredManagerOptions = computed(() => {
    const keyword = managerSearchKeyword.value.trim().toLowerCase()
    if (!keyword) {
      return managerOptions.value.slice(0, 20)
    }

    return managerOptions.value
      .filter((item) => {
        const haystack = [item.name, item.employeeNo, item.department, item.position, item.email]
          .filter(Boolean)
          .join(' ')
          .toLowerCase()

        return haystack.includes(keyword)
      })
      .slice(0, 20)
  })
  const managerDisplayLabel = computed(() => {
    const managerNo = normalizeText(employeeForm.value.managerEmployeeNo)
    const managerName = normalizeText(employeeForm.value.manager)

    if (managerNo) {
      const matched =
        managerOptions.value.find((item) => item.employeeNo === managerNo) ||
        employees.value.find((item) => item.employeeNo === managerNo)

      if (matched) {
        return `${matched.name}（${matched.employeeNo}）`
      }

      return managerName ? `${managerName}（${managerNo}）` : managerNo
    }

    if (!isPlaceholderManagerName(managerName)) {
      return managerName
    }

    return '未设置直属上级'
  })
  const filteredDepartmentOptions = computed(() => {
    const keyword = departmentSearchKeyword.value.trim().toLowerCase()
    const sourceOptions = organizationUnitOptions.value

    if (!keyword) {
      return sourceOptions.slice(0, 20)
    }

    return sourceOptions
      .filter((item) => {
        const haystack = [item.name, item.code, item.unitType, item.label]
          .filter(Boolean)
          .join(' ')
          .toLowerCase()

        return haystack.includes(keyword)
      })
      .slice(0, 20)
  })
  const departmentDisplayLabel = computed(() => {
    const code = normalizeText(employeeForm.value.organizationUnitCode)
    const name = normalizeText(employeeForm.value.department)

    if (code) {
      const matched = organizationUnitOptions.value.find((item) => item.code === code)
      if (matched) {
        return matched.label
      }

      return name ? `${name}（${code}）` : code
    }

    return name || '请选择所属部门'
  })
  const hasManagerAssignment = computed(() => {
    return (
      Boolean(normalizeText(employeeForm.value.managerEmployeeNo)) ||
      !isPlaceholderManagerName(employeeForm.value.manager)
    )
  })

  function handleDocumentClick(event) {
    const target = event.target

    if (!(target instanceof Element)) {
      options.closeFilterPopover?.()
      return
    }

    if (!target.closest('.picker-filter')) options.closeFilterPopover?.()
    if (!target.closest('.manager-picker')) closeManagerPicker()
    if (!target.closest('.department-picker')) closeDepartmentPicker()

    if (
      target.closest('.picker-filter') ||
      target.closest('.manager-picker') ||
      target.closest('.department-picker')
    ) {
      return
    }
  }

  function toggleDepartmentPicker() {
    departmentPickerOpen.value = !departmentPickerOpen.value
    if (!departmentPickerOpen.value) {
      departmentSearchKeyword.value = ''
    }
  }

  function closeDepartmentPicker() {
    departmentPickerOpen.value = false
    departmentSearchKeyword.value = ''
  }

  function selectDepartment(option) {
    if (!option) {
      return
    }

    employeeForm.value.organizationUnitCode = option.code
    employeeForm.value.department = option.name
    closeDepartmentPicker()
  }

  function resolveDepartmentSelectionFromKeyword() {
    const keyword = normalizeText(departmentSearchKeyword.value)
    if (!keyword || normalizeText(employeeForm.value.organizationUnitCode)) {
      return
    }

    const exactMatches = organizationUnitOptions.value.filter(
      (item) => item.code === keyword || item.name === keyword
    )

    if (exactMatches.length === 1) {
      selectDepartment(exactMatches[0])
    }
  }

  function toggleManagerPicker() {
    managerPickerOpen.value = !managerPickerOpen.value
    if (!managerPickerOpen.value) {
      managerSearchKeyword.value = ''
    }
  }

  function closeManagerPicker() {
    managerPickerOpen.value = false
    managerSearchKeyword.value = ''
  }

  function selectManager(option) {
    if (!option) {
      employeeForm.value.managerEmployeeNo = ''
      employeeForm.value.manager = ''
      closeManagerPicker()
      return
    }

    employeeForm.value.managerEmployeeNo = option.employeeNo
    employeeForm.value.manager = option.name
    closeManagerPicker()
  }

  function resolveManagerSelectionFromKeyword() {
    const keyword = normalizeText(managerSearchKeyword.value)
    if (!keyword || normalizeText(employeeForm.value.managerEmployeeNo)) {
      return
    }

    const exactMatches = managerOptions.value.filter(
      (item) => item.employeeNo === keyword || item.name === keyword
    )

    if (exactMatches.length === 1) {
      selectManager(exactMatches[0])
    }
  }

  return {
    managerPickerOpen,
    managerSearchKeyword,
    managerDisplayLabel,
    hasManagerAssignment,
    departmentPickerOpen,
    departmentSearchKeyword,
    departmentDisplayLabel,
    filteredDepartmentOptions,
    filteredManagerOptions,
    handleDocumentClick,
    toggleDepartmentPicker,
    closeDepartmentPicker,
    selectDepartment,
    resolveDepartmentSelectionFromKeyword,
    toggleManagerPicker,
    closeManagerPicker,
    selectManager,
    resolveManagerSelectionFromKeyword
  }
}
