import { computed, ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import type { Order, HandoffRecord } from '../api/orders'
import {
  fetchOrder,
  fetchHandoffRecords,
  cancelOrder,
  startOrderPayment,
  submitHandoff,
  confirmReceive,
} from '../api/orders'
import { createDispute } from '@/features/disputes/api/disputes'
import { uploadFile } from '@/shared/api/files'
import { fetchOrderChat } from '@/features/chats/api/chats'
import { useSessionStore } from '@/stores/session'
import { usePaymentPolling } from './usePaymentPolling'
import { useSettlement } from './useSettlement'

/**
 * 订单详情 Composable
 * 负责订单的核心流程：加载、取消、支付、交接、收货
 * 结算和支付轮询逻辑已拆分到独立 composables
 */
export function useOrderDetail() {
  const route = useRoute()
  const session = useSessionStore()

  // Loading states
  const loading = ref(false)
  const cancelling = ref(false)
  const startingPayment = ref(false)
  const handoffing = ref(false)
  const confirming = ref(false)
  const disputing = ref(false)
  const uploadingEvidence = ref(false)
  const openingChat = ref(false)

  // Data
  const order = ref<Order | null>(null)
  const handoffRecords = ref<HandoffRecord[]>([])
  const handoffContent = ref('')

  // Dispute form
  const disputeType = ref('cannot_login')
  const disputeDescription = ref('')
  const disputeEvidenceText = ref('')

  // 使用拆分的 composables
  const paymentPolling = usePaymentPolling()
  const settlement = useSettlement(order)

  // Computed
  const isOwner = computed(() => order.value?.owner_id === session.userId)
  const isRenter = computed(() => order.value?.renter_id === session.userId)
  const orderAmountLabel = computed(() => (isOwner.value ? '我的租金' : '订单金额'))

  const canOpenDispute = computed(() => {
    if (!order.value || (!isOwner.value && !isRenter.value)) return false
    return !['completed', 'cancelled', 'closed', 'disputing', 'checkout_disputing', 'abnormal'].includes(
      order.value.status
    )
  })

  const isCheckoutDisputeStage = computed(() => {
    return !!order.value && ['pending_checkout_confirm', 'pending_checkout_accept'].includes(order.value.status)
  })

  // Methods
  async function loadOrder() {
    loading.value = true
    try {
      order.value = await fetchOrder(String(route.params.id))
      handoffRecords.value = await fetchHandoffRecords(String(route.params.id))
      return order.value
    } finally {
      loading.value = false
    }
  }

  async function handleCancel() {
    if (!order.value) return false
    cancelling.value = true
    try {
      await cancelOrder(order.value.id)
      await loadOrder()
      return true
    } finally {
      cancelling.value = false
    }
  }

  async function handlePay() {
    if (!order.value) return null
    startingPayment.value = true
    try {
      const payment = await startOrderPayment(order.value.id)
      // 开始支付轮询，成功后重新加载订单
      paymentPolling.startPaymentPolling(payment, loadOrder)
      return payment
    } finally {
      startingPayment.value = false
    }
  }

  async function handleSubmitHandoff() {
    if (!order.value || !handoffContent.value.trim()) return false
    handoffing.value = true
    try {
      await submitHandoff(order.value.id, handoffContent.value.trim())
      handoffContent.value = ''
      await loadOrder()
      return true
    } finally {
      handoffing.value = false
    }
  }

  async function handleConfirmReceive() {
    if (!order.value) return false
    confirming.value = true
    try {
      await confirmReceive(order.value.id)
      await loadOrder()
      return true
    } finally {
      confirming.value = false
    }
  }

  async function handleCreateDispute() {
    if (!order.value) return false
    disputing.value = true
    try {
      await createDispute(order.value.id, {
        type: disputeType.value,
        description: disputeDescription.value.trim(),
        evidence_urls: linesToList(disputeEvidenceText.value),
      })
      await loadOrder()
      return true
    } finally {
      disputing.value = false
    }
  }

  async function handleUploadEvidence(file: File) {
    uploadingEvidence.value = true
    try {
      const result = await uploadFile(file, 'evidence')
      return result.url
    } finally {
      uploadingEvidence.value = false
    }
  }

  async function handleOpenChat() {
    if (!order.value) return null
    openingChat.value = true
    try {
      const chat = await fetchOrderChat(order.value.id)
      return chat
    } finally {
      openingChat.value = false
    }
  }

  function getOrderStep(status: string) {
    const stepMap: Record<string, number> = {
      pending_payment: 0,
      pending_handoff: 1,
      renting: 2,
      overdue: 2,
      pending_checkout_confirm: 3,
      pending_checkout_accept: 3,
      completed: 4,
      cancelled: 0,
      closed: 4,
    }
    return stepMap[status] ?? 0
  }

  function linesToList(value: string) {
    return value
      .split('\n')
      .map((line) => line.trim())
      .filter(Boolean)
  }

  onMounted(loadOrder)

  return {
    // States
    loading,
    cancelling,
    startingPayment,
    handoffing,
    confirming,
    disputing,
    uploadingEvidence,
    openingChat,

    // Data
    order,
    handoffRecords,
    handoffContent,

    // Dispute form
    disputeType,
    disputeDescription,
    disputeEvidenceText,

    // Computed
    isOwner,
    isRenter,
    orderAmountLabel,
    canOpenDispute,
    isCheckoutDisputeStage,

    // Methods
    loadOrder,
    handleCancel,
    handlePay,
    handleSubmitHandoff,
    handleConfirmReceive,
    handleCreateDispute,
    handleUploadEvidence,
    handleOpenChat,
    getOrderStep,

    // 从拆分的 composables 导出
    ...paymentPolling,
    ...settlement,
  }
}
