import { ref, type Ref } from 'vue'
import { submitCheckout, acceptCheckout, counterCheckout, confirmCheckout } from '../api/orders'
import type { Order } from '../api/orders'

export interface CheckoutForm {
  content: string
  consumable_amount: number
  coin_consumed_m: number
  other_amount: number
  evidenceText: string
}

export interface CounterForm {
  consumable_amount: number
  coin_consumed_m: number
  other_amount: number
  deposit_deduct_amount: number
  reason: string
  evidenceText: string
}

/**
 * 订单结算 Composable
 * 负责处理订单结算流程：提交结算、接受结算、反驳结算、确认结算
 */
export function useSettlement(order: Ref<Order | null>) {
  const returning = ref(false)
  const acceptingCheckout = ref(false)
  const countering = ref(false)
  const rejectingCheckout = ref(false)
  const completing = ref(false)

  const checkoutForm = ref<CheckoutForm>({
    content: '',
    consumable_amount: 0,
    coin_consumed_m: 0,
    other_amount: 0,
    evidenceText: '',
  })

  const counterForm = ref<CounterForm>({
    consumable_amount: 0,
    coin_consumed_m: 0,
    other_amount: 0,
    deposit_deduct_amount: 0,
    reason: '',
    evidenceText: '',
  })

  const resourceUsage = ref<Record<string, number>>({})

  /**
   * 提交结算单
   */
  async function handleSubmitCheckout(onSuccess?: () => void) {
    if (!order.value) return false
    returning.value = true
    try {
      await submitCheckout(order.value.id, {
        content: checkoutForm.value.content.trim(),
        consumable_amount: checkoutForm.value.consumable_amount,
        coin_consumed_m: checkoutForm.value.coin_consumed_m,
        other_amount: checkoutForm.value.other_amount,
        evidence_urls: linesToList(checkoutForm.value.evidenceText),
      })
      onSuccess?.()
      return true
    } finally {
      returning.value = false
    }
  }

  /**
   * 接受对方的结算
   */
  async function handleAcceptCheckout(onSuccess?: () => void) {
    if (!order.value) return false
    acceptingCheckout.value = true
    try {
      await acceptCheckout(order.value.id)
      onSuccess?.()
      return true
    } finally {
      acceptingCheckout.value = false
    }
  }

  /**
   * 反驳对方的结算
   */
  async function handleCounterCheckout(onSuccess?: () => void) {
    if (!order.value) return false
    countering.value = true
    try {
      await counterCheckout(order.value.id, {
        consumable_amount: counterForm.value.consumable_amount,
        coin_consumed_m: counterForm.value.coin_consumed_m,
        other_amount: counterForm.value.other_amount,
        deposit_deduct_amount: counterForm.value.deposit_deduct_amount,
        reason: counterForm.value.reason.trim(),
        evidence_urls: linesToList(counterForm.value.evidenceText),
      })
      onSuccess?.()
      return true
    } finally {
      countering.value = false
    }
  }

  /**
   * 拒绝对方的结算（简化版反驳）
   */
  async function handleRejectCheckout(reason: string, onSuccess?: () => void) {
    if (!order.value) return false
    rejectingCheckout.value = true
    try {
      await counterCheckout(order.value.id, {
        consumable_amount: 0,
        coin_consumed_m: 0,
        other_amount: 0,
        deposit_deduct_amount: 0,
        reason: reason.trim(),
        evidence_urls: [],
      })
      onSuccess?.()
      return true
    } finally {
      rejectingCheckout.value = false
    }
  }

  /**
   * 确认最终结算
   */
  async function handleConfirmCheckout(onSuccess?: () => void) {
    if (!order.value) return false
    completing.value = true
    try {
      await confirmCheckout(order.value.id)
      onSuccess?.()
      return true
    } finally {
      completing.value = false
    }
  }

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

  return {
    // Loading states
    returning,
    acceptingCheckout,
    countering,
    rejectingCheckout,
    completing,

    // Forms
    checkoutForm,
    counterForm,
    resourceUsage,

    // Methods
    handleSubmitCheckout,
    handleAcceptCheckout,
    handleCounterCheckout,
    handleRejectCheckout,
    handleConfirmCheckout,
  }
}
