import { onMounted, ref } from 'vue'

import {
  isFeedbackDismissed,
  showConfirm,
  showError,
  showPrompt,
  showSuccess,
} from '@/lib/feedback'
import {
  createAdminUser,
  fetchAdminUsers,
  resetAdminUserPassword,
  updateAdminUserInventoryGroups,
  updateAdminUserRole,
  updateAdminUserStatus,
} from '@/services/admin'
import type { AdminPagination, AdminRole, AdminUserListItem } from '@/types/admin'
import { getAdminUserId, hasAdminRole } from '@/utils/admin-auth'
import { adminUserRoleOptions, adminUserStatusOptions } from '@/utils/admin-options'
import { formatAdminDateTime } from '@/utils/admin-time'

export function useAdminUsers() {
  const loading = ref(true)
  const creating = ref(false)
  const actionLoadingId = ref<number | null>(null)
  const errorMessage = ref('')
  const username = ref('')
  const role = ref('')
  const status = ref('')
  const createUsername = ref('')
  const createPassword = ref('')
  const createRole = ref<AdminRole>('operator')
  const items = ref<AdminUserListItem[]>([])
  const pagination = ref<AdminPagination>({ page: 1, pageSize: 20, total: 0 })

  function isCurrentUser(userId: number) {
    return getAdminUserId() === userId
  }

  function formatRoleLabel(role: AdminRole) {
    if (role === 'admin') return '管理员'
    if (role === 'support') return '客服'
    return '普通运营'
  }

  function formatInventoryGroups(item: AdminUserListItem) {
    if (item.role !== 'support') return ['不限库存组']
    if (item.inventoryGroupCodes.length === 0) return ['未绑定']
    return item.inventoryGroupCodes
  }

  async function loadUsers(page = pagination.value.page) {
    if (!hasAdminRole('admin')) {
      loading.value = false
      return
    }
    loading.value = true
    errorMessage.value = ''
    try {
      const response = await fetchAdminUsers({
        page,
        pageSize: pagination.value.pageSize,
        username: username.value.trim(),
        role: role.value.trim(),
        status: status.value.trim(),
      })
      items.value = response.data.items
      pagination.value = response.data.pagination
    } catch (error) {
      errorMessage.value = error instanceof Error ? error.message : '读取后台用户失败'
    } finally {
      loading.value = false
    }
  }

  async function submitCreate() {
    if (!createUsername.value.trim() || !createPassword.value.trim()) {
      showError('请填写账号和密码')
      return
    }
    creating.value = true
    try {
      await createAdminUser({
        username: createUsername.value.trim(),
        password: createPassword.value.trim(),
        role: createRole.value,
        status: 'active',
      })
      showSuccess('后台用户已创建')
      createUsername.value = ''
      createPassword.value = ''
      createRole.value = 'operator'
      await loadUsers(1)
    } catch (error) {
      showError(error instanceof Error ? error.message : '创建后台用户失败')
    } finally {
      creating.value = false
    }
  }

  async function updateRole(item: AdminUserListItem, nextRole: AdminRole) {
    if (item.role === nextRole) return
    try {
      await showConfirm(
        `确认将 ${item.username} 调整为${formatRoleLabel(nextRole)}吗？`,
        '确认操作',
        { type: 'warning', confirmButtonText: '继续执行', cancelButtonText: '取消' },
      )
    } catch {
      return
    }
    actionLoadingId.value = item.userId
    try {
      await updateAdminUserRole(item.userId, { role: nextRole })
      showSuccess('用户角色已更新')
      await loadUsers()
    } catch (error) {
      showError(error instanceof Error ? error.message : '更新用户角色失败')
    } finally {
      actionLoadingId.value = null
    }
  }

  async function toggleStatus(item: AdminUserListItem) {
    const nextStatus = item.status === 'active' ? 'disabled' : 'active'
    try {
      await showConfirm(
        `确认将 ${item.username}${nextStatus === 'active' ? '启用' : '停用'}吗？`,
        '确认操作',
        {
          type: nextStatus === 'active' ? 'info' : 'warning',
          confirmButtonText: '继续执行',
          cancelButtonText: '取消',
        },
      )
    } catch {
      return
    }
    actionLoadingId.value = item.userId
    try {
      await updateAdminUserStatus(item.userId, { status: nextStatus })
      showSuccess('用户状态已更新')
      await loadUsers()
    } catch (error) {
      showError(error instanceof Error ? error.message : '更新用户状态失败')
    } finally {
      actionLoadingId.value = null
    }
  }

  async function promptResetPassword(item: AdminUserListItem) {
    try {
      const result = await showPrompt(`请输入 ${item.username} 的新密码`, '重置密码', {
        inputType: 'password',
        inputPlaceholder: '至少 8 位',
        confirmButtonText: '提交',
        cancelButtonText: '取消',
        inputValidator: (value) => value.trim().length >= 8 || '密码至少 8 位',
      })
      actionLoadingId.value = item.userId
      await resetAdminUserPassword(item.userId, { password: result.value.trim() })
      showSuccess('用户密码已重置')
      await loadUsers()
    } catch (error) {
      if (isFeedbackDismissed(error)) return
      showError(error instanceof Error ? error.message : '重置密码失败')
    } finally {
      actionLoadingId.value = null
    }
  }

  async function promptUpdateInventoryGroups(item: AdminUserListItem) {
    if (item.role !== 'support') {
      showError('仅客服账号需要绑定库存组')
      return
    }
    try {
      const result = await showPrompt(
        `请输入 ${item.username} 可用的库存组，多个组用英文逗号分隔`,
        '配置库存组',
        {
          inputType: 'text',
          inputValue: item.inventoryGroupCodes.join(','),
          inputPlaceholder: '例如 A组,B组,售后组',
          confirmButtonText: '保存',
          cancelButtonText: '取消',
        },
      )
      const inventoryGroupCodes = String(result.value || '')
        .split(',')
        .map((v) => v.trim())
        .filter(Boolean)
      actionLoadingId.value = item.userId
      await updateAdminUserInventoryGroups(item.userId, { inventoryGroupCodes })
      showSuccess('用户库存组已更新')
      await loadUsers()
    } catch (error) {
      if (isFeedbackDismissed(error)) return
      showError(error instanceof Error ? error.message : '更新库存组失败')
    } finally {
      actionLoadingId.value = null
    }
  }

  onMounted(loadUsers)

  return {
    // state
    loading,
    creating,
    actionLoadingId,
    errorMessage,
    items,
    pagination,
    // filter
    username,
    role,
    status,
    // create
    createUsername,
    createPassword,
    createRole,
    // actions
    loadUsers,
    submitCreate,
    updateRole,
    toggleStatus,
    promptResetPassword,
    promptUpdateInventoryGroups,
    // formatters
    isCurrentUser,
    formatRoleLabel,
    formatInventoryGroups,
    // utils
    hasAdminRole,
    formatAdminDateTime,
    adminUserRoleOptions,
    adminUserStatusOptions,
  }
}
