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

import {
  DEFAULT_STATUS_TABS,
  buildEmployeeEmptyState,
  buildEmployeeSummary,
  buildStatusTabs,
  mapSimpleFilterOptions,
  matchKeyword,
  uniqueSorted
} from './employeeManagementModel.js'

export function useEmployeeManagementFilters(options = {}) {
  const employees = options.employees
  const roleOptions = options.roleOptions
  const activeTab = ref(DEFAULT_STATUS_TABS[0])
  const searchKeyword = ref('')
  const selectedDepartment = ref('')
  const selectedGrade = ref('')
  const selectedRole = ref('')
  const activeFilterPopover = ref('')
  const currentPage = ref(1)
  const pageSize = ref(10)
  const pageSizes = [10, 20, 50]
  const pageSizeOptions = pageSizes.map((size) => ({ label: `${size} 条/页`, value: size }))

  const tabs = computed(() => buildStatusTabs(employees.value))
  const employeeSummary = computed(() => buildEmployeeSummary(employees.value))
  const departmentOptions = computed(() =>
    uniqueSorted(employees.value.map((item) => item.department))
  )
  const gradeOptions = computed(() => uniqueSorted(employees.value.map((item) => item.grade)))
  const roleFilterOptions = computed(() =>
    uniqueSorted(
      roleOptions.value.map((item) => item.label).concat(
        employees.value.flatMap((item) => item.roles || [])
      )
    )
  )
  const departmentFilterOptions = computed(() => mapSimpleFilterOptions(departmentOptions.value, '全部部门'))
  const gradeFilterOptions = computed(() => mapSimpleFilterOptions(gradeOptions.value, '全部职级'))
  const roleDropdownOptions = computed(() => mapSimpleFilterOptions(roleFilterOptions.value, '全部角色'))
  const departmentFilterLabel = computed(() => selectedDepartment.value || '组织部门')
  const gradeFilterLabel = computed(() => selectedGrade.value || '职级')
  const roleFilterLabel = computed(() => selectedRole.value || '系统角色')

  const filteredEmployees = computed(() => {
    const keyword = searchKeyword.value.trim().toLowerCase()

    return employees.value.filter((item) => {
      const matchesStatus =
        activeTab.value === DEFAULT_STATUS_TABS[0] ? true : item.status === activeTab.value
      const matchesDepartment = selectedDepartment.value
        ? item.department === selectedDepartment.value
        : true
      const matchesGrade = selectedGrade.value ? item.grade === selectedGrade.value : true
      const matchesRole = selectedRole.value ? (item.roles || []).includes(selectedRole.value) : true

      return (
        matchesStatus &&
        matchesDepartment &&
        matchesGrade &&
        matchesRole &&
        matchKeyword(item, keyword)
      )
    })
  })

  const totalCount = computed(() => filteredEmployees.value.length)
  const totalPages = computed(() => Math.max(1, Math.ceil(totalCount.value / pageSize.value)))
  const pageSummary = computed(() => `共 ${totalCount.value} 条，目前第 ${currentPage.value} / ${totalPages.value} 页`)
  const visibleEmployees = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    return filteredEmployees.value.slice(start, start + pageSize.value)
  })
  const activeFilterTokens = computed(() => {
    const tokens = []
    if (selectedDepartment.value) tokens.push(`部门：${selectedDepartment.value}`)
    if (selectedGrade.value) tokens.push(`职级：${selectedGrade.value}`)
    if (selectedRole.value) tokens.push(`角色：${selectedRole.value}`)
    if (searchKeyword.value.trim()) tokens.push(`搜索：${searchKeyword.value.trim()}`)
    return tokens
  })
  const hasActiveFilters = computed(() => activeFilterTokens.value.length > 0)
  const hasEmployeeFilters = computed(() => {
    return activeTab.value !== DEFAULT_STATUS_TABS[0] || hasActiveFilters.value
  })
  const employeeEmptyState = computed(() => buildEmployeeEmptyState({
    activeTab: activeTab.value,
    employeeCount: employees.value.length,
    hasEmployeeFilters: hasEmployeeFilters.value
  }))

  watch(
    employeeSummary,
    (summary) => {
      options.emit?.('overview-change', summary)
    },
    { immediate: true }
  )

  watch(filteredEmployees, () => {
    currentPage.value = 1
  })

  function resetFilters() {
    searchKeyword.value = ''
    selectedDepartment.value = ''
    selectedGrade.value = ''
    selectedRole.value = ''
    activeTab.value = DEFAULT_STATUS_TABS[0]
    activeFilterPopover.value = ''
  }

  function handleEmployeeEmptyAction() {
    if (!employees.value.length) {
      options.loadEmployees?.().catch(() => {})
      return
    }

    resetFilters()
  }

  function changePageSize(size) {
    pageSize.value = size
    currentPage.value = 1
  }

  function toggleFilterPopover(name) {
    activeFilterPopover.value = activeFilterPopover.value === name ? '' : name
  }

  function closeFilterPopover() {
    activeFilterPopover.value = ''
  }

  function selectFilter(name, value) {
    if (name === 'department') selectedDepartment.value = value
    if (name === 'grade') selectedGrade.value = value
    if (name === 'role') selectedRole.value = value
    closeFilterPopover()
  }

  return {
    activeTab,
    searchKeyword,
    selectedDepartment,
    selectedGrade,
    selectedRole,
    activeFilterPopover,
    currentPage,
    pageSize,
    pageSizes,
    pageSizeOptions,
    tabs,
    employeeSummary,
    departmentOptions,
    gradeOptions,
    roleFilterOptions,
    departmentFilterOptions,
    gradeFilterOptions,
    roleDropdownOptions,
    departmentFilterLabel,
    gradeFilterLabel,
    roleFilterLabel,
    filteredEmployees,
    totalCount,
    totalPages,
    pageSummary,
    visibleEmployees,
    activeFilterTokens,
    hasActiveFilters,
    hasEmployeeFilters,
    employeeEmptyState,
    resetFilters,
    handleEmployeeEmptyAction,
    changePageSize,
    toggleFilterPopover,
    closeFilterPopover,
    selectFilter
  }
}
