import { Input, Text, Textarea, View } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { accountInvoiceFileUrl, backend, type BackendInvoiceApplication, type BackendOrder, yuan } from '@/api/backend'
import { EmptyState, MetaRow, Page, StatusSide } from '@/components/ui'
import { getToken, getUser, payBackendOrder } from '@/stores/storage'

const invoiceStatusText: Record<string, string> = {
  pending: '待开票',
  processing: '开票中',
  issued: '已开票',
  rejected: '已驳回',
  failed: '开票失败'
}

function orderStatusText(status: BackendOrder['status']) {
  if (status === 'pending_payment') return '待支付'
  if (status === 'closed') return '已关闭'
  if (status === 'completed') return '已完成'
  return '已支付'
}

function productTypeText(type: string) {
  if (type === 'course') return '课程'
  if (type === 'event') return '活动'
  if (type === 'data') return '数据服务'
  if (type === 'agent') return '智能体'
  if (type === 'expert') return '专家预约'
  if (type === 'consulting') return '规划咨询'
  if (type === 'membership') return '会员'
  return '服务'
}

function formatDateTime(value?: string) {
  if (!value) return '-'
  const date = new Date(value)
  return Number.isNaN(date.getTime()) ? '-' : date.toLocaleString('zh-CN')
}

function invoiceFileReady(invoice?: BackendInvoiceApplication | null) {
  return invoice?.status === 'issued' && Boolean(invoice.fileUrl || invoice.pdfFileId)
}

function serviceUrl(type: string) {
  if (type === 'course') return '/pages/account/courses/index'
  if (type === 'event') return '/pages/account/events/index'
  if (type === 'data') return '/pages/account/reports/index'
  if (type === 'agent') return '/pages/account/agents/index'
  if (type === 'expert') return '/pages/account/expert-bookings/index'
  if (type === 'consulting') return '/pages/account/consulting/index'
  if (type === 'membership') return '/pages/account/membership/index'
  return '/pages/services/index'
}

export default function OrderDetailPage() {
  const [orderNo, setOrderNo] = useState('')
  const [order, setOrder] = useState<BackendOrder | null>(null)
  const [loading, setLoading] = useState(false)
  const [paying, setPaying] = useState(false)
  const [title, setTitle] = useState('')
  const [taxNumber, setTaxNumber] = useState('')
  const [email, setEmail] = useState('')
  const [remark, setRemark] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const user = getUser()

  async function loadOrder(nextOrderNo = orderNo) {
    const token = getToken()
    if (!token || !nextOrderNo) return
    setLoading(true)
    try {
      setOrder(await backend.accountOrder(token, nextOrderNo))
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '订单加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  useLoad((query) => {
    const nextOrderNo = String(query.id || query.orderNo || '')
    setOrderNo(nextOrderNo)
    void loadOrder(nextOrderNo)
  })

  async function continuePay() {
    if (!order || paying) return
    setPaying(true)
    try {
      const paidOrder = await payBackendOrder(order.orderNo)
      setOrder(paidOrder)
      Taro.showToast({ title: '支付完成', icon: 'success' })
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '支付失败', icon: 'none' })
    } finally {
      setPaying(false)
    }
  }

  async function submitInvoice() {
    if (!order || submitting) return
    const token = getToken()
    if (!token) {
      Taro.showToast({ title: '请先登录', icon: 'none' })
      return
    }
    const invoiceTitle = title.trim() || user?.invoiceTitle || user?.organization || user?.name || ''
    const invoiceEmail = email.trim() || user?.invoiceEmail || user?.email || ''
    if (!invoiceTitle || !invoiceEmail) {
      Taro.showToast({ title: '请填写发票抬头和接收邮箱', icon: 'none' })
      return
    }
    setSubmitting(true)
    try {
      await backend.createAccountInvoiceApplication(token, order.orderNo, {
        title: invoiceTitle,
        taxNumber: taxNumber.trim() || user?.taxNumber || '',
        email: invoiceEmail,
        remark: remark.trim()
      })
      setOrder(await backend.accountOrder(token, order.orderNo))
      Taro.showToast({ title: '发票申请已提交', icon: 'success' })
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '提交失败', icon: 'none' })
    } finally {
      setSubmitting(false)
    }
  }

  async function openInvoiceFile(invoice: BackendInvoiceApplication) {
    const token = getToken()
    const url = accountInvoiceFileUrl(invoice.invoiceNo)
    try {
      const downloaded = await Taro.downloadFile({
        url,
        header: token ? { Authorization: `Bearer ${token}` } : {}
      })
      await Taro.openDocument({ filePath: downloaded.tempFilePath, showMenu: true })
    } catch {
      await Taro.setClipboardData({ data: url })
      Taro.showToast({ title: '已复制发票链接', icon: 'none' })
    }
  }

  if (!order && !loading) {
    return (
      <Page title="订单详情" subtle={orderNo ? `订单号 ${orderNo}` : ''}>
        <EmptyState title="未找到订单" text="订单可能还在同步，请稍后从订单列表重新进入。" />
      </Page>
    )
  }

  if (!order) return <Page title="订单详情" subtle="正在同步订单" />

  const invoice = order.invoiceApplication
  const canApplyInvoice = order.status !== 'pending_payment' && order.status !== 'closed' && order.paidAmount > 0 && !invoice
  const invoiceTitle = title || user?.invoiceTitle || user?.organization || user?.name || ''
  const invoiceTaxNumber = taxNumber || user?.taxNumber || ''
  const invoiceEmail = email || user?.invoiceEmail || user?.email || ''

  return (
    <Page title="订单详情" subtle={`订单号 ${order.orderNo}`}>
      <View className="order-detail-hero">
        <View>
          <Text className="order-detail-title">{order.items[0]?.titleSnapshot || '服务订单'}</Text>
          <Text className="order-detail-sub">创建于 {formatDateTime(order.createdAt)}</Text>
        </View>
        <StatusSide value={orderStatusText(order.status)} orange={order.status === 'pending_payment'} />
      </View>

      <View className="meta-grid order-amount-grid">
        <View><Text className="meta-label">商品小计</Text><Text className="meta-value">¥{yuan(order.subtotalAmount).toLocaleString()}</Text></View>
        <View><Text className="meta-label">会员优惠</Text><Text className="meta-value">¥{yuan(order.memberDiscountAmount || 0).toLocaleString()}</Text></View>
        <View><Text className="meta-label">优惠码</Text><Text className="meta-value">¥{yuan(order.couponDiscountAmount || 0).toLocaleString()}</Text></View>
        <View><Text className="meta-label">应付</Text><Text className="meta-value strong">¥{yuan(order.totalAmount).toLocaleString()}</Text></View>
      </View>

      {order.status === 'pending_payment' && (
        <View className="primary-btn order-pay-btn" onClick={continuePay}>{paying ? '支付中...' : '继续支付'}</View>
      )}

      <View className="section-lite">
        <Text className="section-lite-title">订单内容</Text>
        <View className="list-shell flat-list">
          {order.items.map((item) => (
            <View key={`${item.productId}-${item.productType}`} className="list-line compact-line">
              <View className="list-main">
                <Text className="row-title">{item.titleSnapshot}</Text>
                <Text className="row-sub">{productTypeText(item.productType)} · 数量 {item.quantity}</Text>
              </View>
              <View className="list-side-action" onClick={() => Taro.navigateTo({ url: serviceUrl(item.productType) })}>
                <Text>查看</Text>
              </View>
            </View>
          ))}
        </View>
      </View>

      <View className="section-lite">
        <Text className="section-lite-title">发票申请</Text>
        {invoice ? (
          <View className="invoice-summary">
            <MetaRow label="申请单号" value={invoice.invoiceNo} />
            <MetaRow label="状态" value={invoiceStatusText[invoice.status] || invoice.status} />
            <MetaRow label="发票抬头" value={invoice.title} />
            <MetaRow label="税号" value={invoice.taxNumber || '未填写'} />
            <MetaRow label="接收邮箱" value={invoice.email} />
            <MetaRow label="发票金额" value={`¥${yuan(invoice.amount).toLocaleString()}`} />
            {invoice.providerInvoiceId && <MetaRow label="发票号码" value={invoice.providerInvoiceId} />}
            {(invoice.failureReason || invoice.adminNote) && <MetaRow label="处理说明" value={invoice.failureReason || invoice.adminNote} />}
            {invoiceFileReady(invoice) && (
              <View className="primary-btn ghost-primary" onClick={() => void openInvoiceFile(invoice)}>打开电子发票</View>
            )}
          </View>
        ) : canApplyInvoice ? (
          <View className="invoice-form">
            <Input className="form-input" value={invoiceTitle} onInput={(event) => setTitle(String(event.detail.value))} placeholder="发票抬头" />
            <Input className="form-input" value={invoiceTaxNumber} onInput={(event) => setTaxNumber(String(event.detail.value))} placeholder="税号（选填）" />
            <Input className="form-input" value={invoiceEmail} onInput={(event) => setEmail(String(event.detail.value))} placeholder="接收邮箱" />
            <Textarea className="form-textarea" value={remark} onInput={(event) => setRemark(String(event.detail.value))} placeholder="备注（选填）" />
            <View className="primary-btn" onClick={submitInvoice}>{submitting ? '提交中...' : '提交发票申请'}</View>
          </View>
        ) : (
          <EmptyState title={order.status === 'pending_payment' ? '支付完成后可申请发票' : '暂无可申请发票'} compact />
        )}
      </View>
    </Page>
  )
}
