import { Checkbox, Input, Text, View } from '@tarojs/components'
import Taro, { useDidShow, useLoad } from '@tarojs/taro'
import { useEffect, useState } from 'react'
import { backend, yuan, type BackendCheckoutPreview } from '@/api/backend'
import { AgreementModal, EmptyState, MetaRow, Page } from '@/components/ui'
import { createBackendOrders, ensureLoggedIn, getCart, getToken, getUser } from '@/stores/storage'
import type { CartItem } from '@/types'
import { toast } from '@/utils/nav'
import { tapLight, tapMedium } from '@/utils/feedback'

export default function CheckoutPage() {
  const [items, setItems] = useState<CartItem[]>([])
  const [expertBookingId, setExpertBookingId] = useState('')
  const [dataServiceRequestId, setDataServiceRequestId] = useState('')
  const [consultingRequestId, setConsultingRequestId] = useState('')
  const [accepted, setAccepted] = useState(false)
  const [showTerms, setShowTerms] = useState(false)
  const [preview, setPreview] = useState<BackendCheckoutPreview | null>(null)
  const [previewError, setPreviewError] = useState('')
  const [needInvoice, setNeedInvoice] = useState(false)
  const [invoiceTitle, setInvoiceTitle] = useState('')
  const [taxNumber, setTaxNumber] = useState('')
  const [invoiceEmail, setInvoiceEmail] = useState('')

  useLoad((query) => {
    const bookingId = String(query.expertBookingId || query.bookingId || '')
    const requestId = String(query.dataServiceRequestId || '')
    const consultingId = String(query.consultingRequestId || '')
    setExpertBookingId(bookingId)
    setDataServiceRequestId(requestId)
    setConsultingRequestId(consultingId)
    if (!bookingId && !requestId && !consultingId) return
    const redirect = bookingId
      ? `/pages/checkout/index?expertBookingId=${encodeURIComponent(bookingId)}`
      : requestId
      ? `/pages/checkout/index?dataServiceRequestId=${encodeURIComponent(requestId)}`
      : `/pages/checkout/index?consultingRequestId=${encodeURIComponent(consultingId)}`
    const user = ensureLoggedIn(redirect)
    const token = getToken()
    if (!user || !token) return
    if (bookingId) {
      backend.accountExpertBookings(token)
        .then((result) => {
          const booking = result.items.find((item) => item.id === bookingId || item.bookingNo === bookingId)
          if (!booking || booking.status !== 'pending_payment') {
            toast('当前专家预约暂不能付款')
            return
          }
          setItems([{
            id: 'expert-city-consulting',
            type: 'expert',
            title: `${booking.expert?.name || '专家'}咨询 1 小时`,
            subtitle: `${booking.bookingNo} · ${booking.expert?.title || '专家咨询'} · ${booking.expert?.organization || '大连市大数据研究院'}`,
            price: yuan(booking.expert?.priceAmount || 0),
            cover: booking.expert?.photoUrl || 'expert',
            expertBookingId: booking.id
          }])
        })
        .catch((error) => toast(error instanceof Error ? error.message : '专家预约加载失败'))
      return
    }
    if (consultingId) {
      backend.accountConsultingRequests(token)
        .then((result) => {
          const request = result.items.find((item) => item.id === consultingId || item.requestNo === consultingId)
          if (!request || (request.status !== 'proposal_ready' && request.status !== 'pending_payment')) {
            toast('当前规划咨询暂不能付款')
            return
          }
          setItems([{
            id: 'consulting-service-custom',
            type: 'consulting',
            title: request.quotedTitle || request.direction || '规划咨询服务',
            subtitle: `${request.requestNo} · 规划咨询报价`,
            price: yuan(request.quotedAmount || 0),
            cover: 'consulting',
            consultingRequestId: request.id
          }])
        })
        .catch((error) => toast(error instanceof Error ? error.message : '咨询报价加载失败'))
      return
    }
    backend.accountDataServiceRequest(token, requestId)
      .then((request) => {
        if (request.status !== 'quoted' && request.status !== 'pending_payment') {
          toast('当前数据服务申请暂不能付款')
          return
        }
        setItems([{
          id: 'data-service-custom',
          type: 'data',
          title: request.quotedTitle || request.dataTopic || '数据服务定制',
          subtitle: `${request.requestNo} · 数据服务报价`,
          price: yuan(request.quotedAmount || 0),
          cover: 'data',
          dataServiceRequestId: request.id
        }])
      })
      .catch((error) => toast(error instanceof Error ? error.message : '报价单加载失败'))
  })

  useDidShow(() => {
    const redirect = expertBookingId
      ? `/pages/checkout/index?expertBookingId=${encodeURIComponent(expertBookingId)}`
      : dataServiceRequestId
      ? `/pages/checkout/index?dataServiceRequestId=${encodeURIComponent(dataServiceRequestId)}`
      : consultingRequestId
      ? `/pages/checkout/index?consultingRequestId=${encodeURIComponent(consultingRequestId)}`
      : '/pages/checkout/index'
    const user = ensureLoggedIn(redirect)
    if (!user) return
    if (!expertBookingId && !dataServiceRequestId && !consultingRequestId) setItems(getCart())
  })

  const user = getUser()
  const serviceCheckout = Boolean(expertBookingId || dataServiceRequestId || consultingRequestId)
  const previewSubtotal = preview ? yuan(preview.items.reduce((sum, item) => sum + (item.listPriceAmount ?? item.unitPriceAmount) * item.quantity, 0)) : 0
  const previewPaid = preview ? yuan(preview.totalAmount) : 0
  const fallbackSubtotal = items.reduce((sum, item) => sum + item.price, 0)
  const subtotal = preview ? previewSubtotal : fallbackSubtotal
  const paid = preview ? previewPaid : fallbackSubtotal
  const discount = Math.max(subtotal - paid, 0)
  const defaultInvoiceTitle = user?.invoiceTitle || user?.organization || user?.name || ''
  const defaultTaxNumber = user?.taxNumber || ''
  const defaultInvoiceEmail = user?.invoiceEmail || user?.email || ''

  useEffect(() => {
    const token = getToken()
    if (!token || items.length === 0) {
      setPreview(null)
      setPreviewError('')
      return
    }
    let cancelled = false
    backend.previewCheckout(token, items)
      .then((result) => {
        if (cancelled) return
        setPreview(result)
        setPreviewError('')
      })
      .catch((error) => {
        if (cancelled) return
        setPreview(null)
        setPreviewError(error instanceof Error ? error.message : '订单试算失败')
      })
    return () => {
      cancelled = true
    }
  }, [items])

  function pay() {
    const current = ensureLoggedIn('/pages/checkout/index')
    if (!current) return
    if (items.length === 0) {
      toast('暂无可结算商品')
      return
    }
    if (!accepted) {
      tapMedium()
      toast('请先同意线上购买条款')
      return
    }
    const effectiveInvoiceTitle = invoiceTitle.trim() || defaultInvoiceTitle
    const effectiveTaxNumber = taxNumber.trim() || defaultTaxNumber
    const effectiveInvoiceEmail = invoiceEmail.trim() || defaultInvoiceEmail
    if (needInvoice) {
      if (!effectiveInvoiceTitle || !effectiveInvoiceEmail) {
        toast('请填写发票抬头和接收邮箱')
        return
      }
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(effectiveInvoiceEmail)) {
        toast('请填写有效邮箱')
        return
      }
      if (effectiveTaxNumber && !/^[0-9A-Z]{15,20}$/.test(effectiveTaxNumber)) {
        toast('税号需为 15-20 位字母或数字')
        return
      }
    }
    createBackendOrders(items, {
      clearCart: !serviceCheckout,
      invoiceRequest: needInvoice ? {
        requested: true,
        title: effectiveInvoiceTitle,
        taxNumber: effectiveTaxNumber,
        email: effectiveInvoiceEmail,
        remark: '结算页勾选自动申请发票'
      } : undefined
    })
      .then(() => {
        tapMedium()
        const suffix = dataServiceRequestId
          ? `?dataServiceRequestId=${encodeURIComponent(dataServiceRequestId)}`
          : consultingRequestId
          ? `?consultingRequestId=${encodeURIComponent(consultingRequestId)}`
          : expertBookingId
          ? `?expertBookingId=${encodeURIComponent(expertBookingId)}`
          : ''
        Taro.redirectTo({ url: `/pages/checkout/success/index${suffix}` })
      })
      .catch((error) => toast(error instanceof Error ? error.message : '购买失败，请稍后重试'))
  }

  return (
    <Page title="确认订单" subtle={items.length ? `共 ${items.length} 项服务` : undefined}>
      {items.length === 0 ? (
        <EmptyState title="暂无可结算商品" text="请先选择课程、活动、数据服务或智能体服务。" />
      ) : (
        <>
          <View className="checkout-section">
            <Text className="checkout-section-title">订单内容</Text>
            <View className="commerce-list">
              {items.map((item, index) => {
                const previewItem = preview?.items[index]
                const linePrice = previewItem ? yuan(previewItem.unitPriceAmount) : item.price
                return (
                  <View key={item.id} className="commerce-row">
                    <View className="commerce-main">
                      <Text className="commerce-title">{item.title}</Text>
                      <Text className="commerce-sub">{item.subtitle}</Text>
                      {previewItem?.pricingSource && previewItem.pricingSource !== 'list_price' && (
                        <Text className="commerce-note">{previewItem.membershipDiscountNote || '已按服务端报价规则试算'}</Text>
                      )}
                    </View>
                    <Text className="commerce-price side">¥{linePrice.toLocaleString()}</Text>
                  </View>
                )
              })}
            </View>
          </View>

          <View className="checkout-section">
            <Text className="checkout-section-title">支付信息</Text>
            <View className="checkout-summary-list">
              <MetaRow label="联系电话" value={user?.contactPhone} />
              <MetaRow label="发票" value={needInvoice ? '支付后自动申请' : '暂不开票'} />
              <MetaRow label="金额" value={`¥${subtotal.toLocaleString()}`} />
              <MetaRow label="会员折扣" value={`¥${discount.toLocaleString()}`} />
              {preview?.membershipChange?.type === 'upgrade' && <MetaRow label="升级抵扣" value={`已抵扣 ¥${yuan(preview.membershipChange.upgradeCreditAmount).toLocaleString()}`} />}
              {previewError && <MetaRow label="试算状态" value={previewError} />}
              <MetaRow label="实付金额" value={`¥${paid.toLocaleString()}`} />
            </View>
            <View className="checkout-invoice-toggle" onClick={() => { tapLight(); setNeedInvoice(!needInvoice) }}>
              <Checkbox checked={needInvoice} value="invoice" />
              <Text className="checkout-agreement-text">我需要发票</Text>
            </View>
            {needInvoice && (
              <View className="invoice-form checkout-invoice-form">
                <Input className="form-input" value={invoiceTitle} onInput={(event) => setInvoiceTitle(String(event.detail.value))} placeholder={defaultInvoiceTitle || '发票抬头'} />
                <Input className="form-input" value={taxNumber} onInput={(event) => setTaxNumber(String(event.detail.value).toUpperCase())} placeholder={defaultTaxNumber || '税号（选填）'} />
                <Input className="form-input" value={invoiceEmail} onInput={(event) => setInvoiceEmail(String(event.detail.value))} placeholder={defaultInvoiceEmail || '电子发票接收邮箱'} />
                <Text className="invoice-note">支付完成后会自动提交普通电子发票申请，也可后续在订单详情补申请。</Text>
              </View>
            )}
          </View>

          <View className="checkout-agreement" onClick={() => { tapLight(); setAccepted(!accepted) }}>
            <Checkbox checked={accepted} value="terms" />
            <Text className="checkout-agreement-text">我同意</Text>
            <Text className="checkout-terms-link" onClick={(event) => { event.stopPropagation(); setShowTerms(true) }}>《大连市大数据研究院线上购买条款》</Text>
          </View>

          <View className="detail-spacer" />
          <View className="checkout-fixed-bar">
            <View className="checkout-total-copy">
              <Text className="checkout-total-label">实付</Text>
              <Text className="checkout-total-price">¥{paid.toLocaleString()}</Text>
            </View>
            <View className="primary-btn checkout-submit" onClick={pay}>提交购买</View>
          </View>
        </>
      )}

      {showTerms && <AgreementModal title="线上购买条款" onClose={() => setShowTerms(false)} />}
    </Page>
  )
}
