import { computed, onBeforeUnmount, ref } from 'vue'
import { useRoute } from 'vue-router'

import { showConfirm, showError, showSuccess } from '@/lib/feedback'
import {
  completeAdminTaskManualDispatch,
  fetchAdminTaskScreenshot,
  fetchAdminTaskDetail,
} from '@/services/admin'
import type { AdminTaskActionResponse, AdminTaskDetail } from '@/types/admin'
import { hasAdminRole } from '@/utils/admin-auth'

import type { ManualDispatchForm } from './types'

export function useAdminTaskDetail() {
  const route = useRoute()
  const loading = ref(true)
  const actionLoading = ref(false)
  const errorMessage = ref('')
  const detail = ref<AdminTaskDetail | null>(null)
  const lastClaimUrl = ref('')
  const screenshotPreviewUrl = ref('')
  const manualDispatchForm = ref<ManualDispatchForm>({
    deliveryReference: '',
    deliveredCredential: '',
    resultMessage: '',
  })

  const canManageTaskLifecycle = computed(() => hasAdminRole('operator'))
  const canCloseTasks = computed(() => hasAdminRole('support'))
  const canViewSensitiveTaskData = computed(() =>
    Boolean(detail.value?.operations.canViewSensitiveTaskData),
  )

  const claimUrl = computed(() => {
    const tokenStatus = String(detail.value?.claimToken?.status || '').trim()
    const taskStatus = String(detail.value?.task.status || '').trim()

    if (tokenStatus !== 'active' || ['closed', 'expired'].includes(taskStatus)) {
      return ''
    }

    return lastClaimUrl.value || detail.value?.claimToken?.claimUrl || ''
  })

  const claimLinkInvalid = computed(() => {
    const tokenStatus = String(detail.value?.claimToken?.status || '').trim()
    return Boolean(
      detail.value?.claimToken?.claimUrl &&
        tokenStatus &&
        tokenStatus !== 'active',
    )
  })

  const screenshotSectionTitle = computed(() => {
    if (detail.value?.task.status === 'redeemed') {
      return '结果截图'
    }

    return detail.value?.review.required ? '客服复核截图' : '结果截图'
  })

  async function loadDetail() {
    loading.value = true
    errorMessage.value = ''

    try {
      const response = await fetchAdminTaskDetail(String(route.params.taskId || ''))
      detail.value = response.data
      syncManualDispatchForm(response.data)
      await loadScreenshotPreview(response.data)
    } catch (error) {
      errorMessage.value = error instanceof Error ? error.message : '读取任务详情失败'
    } finally {
      loading.value = false
    }
  }

  async function runAction(
    action: () => Promise<{ data: AdminTaskActionResponse }>,
    successMessage: string,
    confirmText: string,
  ) {
    try {
      await showConfirm(confirmText, '确认操作', {
        type: 'warning',
        confirmButtonText: '继续执行',
        cancelButtonText: '取消',
      })
    } catch {
      return
    }

    actionLoading.value = true

    try {
      const response = await action()
      if (response.data.claimUrl) {
        lastClaimUrl.value = response.data.claimUrl
      }
      showSuccess(successMessage)
      await loadDetail()
    } catch (error) {
      showError(error instanceof Error ? error.message : '操作失败')
    } finally {
      actionLoading.value = false
    }
  }

  async function loadScreenshotPreview(taskDetail: AdminTaskDetail) {
    clearScreenshotPreview()

    if (!taskDetail.screenshotUrl) {
      return
    }

    try {
      const blob = await fetchAdminTaskScreenshot(taskDetail.task.taskId)
      screenshotPreviewUrl.value = URL.createObjectURL(blob)
    } catch {
      screenshotPreviewUrl.value = ''
    }
  }

  function clearScreenshotPreview() {
    if (screenshotPreviewUrl.value) {
      URL.revokeObjectURL(screenshotPreviewUrl.value)
      screenshotPreviewUrl.value = ''
    }
  }

  function syncManualDispatchForm(taskDetail: AdminTaskDetail) {
    manualDispatchForm.value = {
      deliveryReference: taskDetail.manualDispatch?.deliveryReference || '',
      deliveredCredential: taskDetail.manualDispatch?.deliveredCredential || '',
      resultMessage:
        taskDetail.manualDispatch?.resultMessage || taskDetail.task.resultMessage || '',
    }
  }

  async function submitManualDispatch(outcome: 'delivered' | 'failed') {
    if (!detail.value) {
      return
    }

    const actionLabel = outcome === 'failed' ? '标记履约失败' : '标记已完成履约'
    const confirmText =
      outcome === 'failed'
        ? `确认把任务 ${detail.value.task.taskNo} 回写为人工履约失败吗？这会把任务直接收口并保留失败原因。`
        : `确认把任务 ${detail.value.task.taskNo} 回写为人工履约完成吗？这会把任务直接标记为已发放。`

    await runAction(
      () =>
        completeAdminTaskManualDispatch(detail.value!.task.taskId, {
          outcome,
          resultMessage: manualDispatchForm.value.resultMessage,
          deliveryReference: manualDispatchForm.value.deliveryReference,
          deliveredCredential: manualDispatchForm.value.deliveredCredential,
        }),
      actionLabel,
      confirmText,
    )
  }

  async function copyText(value: string, successMessage: string) {
    const text = String(value || '').trim()
    if (!text) {
      showError('当前没有可复制的内容')
      return
    }

    try {
      await navigator.clipboard.writeText(text)
      showSuccess(successMessage)
    } catch {
      showError('复制失败，请手动复制')
    }
  }

  function openExternalLink(value: string) {
    const text = String(value || '').trim()
    if (!text) {
      return
    }

    window.open(text, '_blank', 'noopener,noreferrer')
  }

  function resolveTaskAutoDeliveryStatus(taskDetail: AdminTaskDetail) {
    if (taskDetail.task.agisoAutoDelivery?.status) {
      return taskDetail.task.agisoAutoDelivery.status
    }

    return taskDetail.task.deliveryStatus === 'delivered' ? 'pending' : 'waiting'
  }

  function resolveTaskAutoDeliverySummary(taskDetail: AdminTaskDetail) {
    const autoDelivery = taskDetail.task.agisoAutoDelivery

    if (autoDelivery?.errorMessage) {
      return autoDelivery.errorMessage
    }

    if (autoDelivery?.reason) {
      return autoDelivery.reason
    }

    return taskDetail.task.deliveryStatus === 'delivered'
      ? '当前任务已交付，等待订单下其他任务完成后统一自动发货'
      : '当前任务尚未完成交付，暂不会触发自动发货'
  }

  onBeforeUnmount(clearScreenshotPreview)

  return {
    loading,
    actionLoading,
    errorMessage,
    detail,
    screenshotPreviewUrl,
    manualDispatchForm,
    canManageTaskLifecycle,
    canCloseTasks,
    canViewSensitiveTaskData,
    claimUrl,
    claimLinkInvalid,
    screenshotSectionTitle,
    loadDetail,
    runAction,
    submitManualDispatch,
    copyText,
    openExternalLink,
    resolveTaskAutoDeliveryStatus,
    resolveTaskAutoDeliverySummary,
  }
}
