import { ScrollView, Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useMemo, useState } from 'react'
import { accountInvoiceFileUrl, backend, type BackendInvoiceApplication, type BackendInvoiceStatus, yuan } from '@/api/backend'
import { EmptyState, Page } from '@/components/ui'
import { ensureLoggedIn, getToken } from '@/stores/storage'
import { tapLight } from '@/utils/feedback'

type InvoiceFilter = 'all' | BackendInvoiceStatus

const filters: Array<{ key: InvoiceFilter; label: string }> = [
  { key: 'all', label: '全部' },
  { key: 'pending', label: '待开票' },
  { key: 'processing', label: '开票中' },
  { key: 'issued', label: '已开票' },
  { key: 'rejected', label: '已驳回' },
  { key: 'failed', label: '异常' }
]

const statusText: Record<BackendInvoiceStatus, string> = {
  pending: '待开票',
  processing: '开票中',
  issued: '已开票',
  rejected: '已驳回',
  failed: '开票异常'
}

function formatDate(value?: string | null) {
  if (!value) return '-'
  return new Date(value).toLocaleDateString('zh-CN')
}

function statusClass(status: BackendInvoiceStatus) {
  if (status === 'issued') return 'invoice-status success'
  if (status === 'rejected' || status === 'failed') return 'invoice-status warning'
  if (status === 'processing') return 'invoice-status brand'
  return 'invoice-status'
}

export default function AccountInvoicesPage() {
  const [items, setItems] = useState<BackendInvoiceApplication[]>([])
  const [filter, setFilter] = useState<InvoiceFilter>('all')
  const [loading, setLoading] = useState(false)
  const [message, setMessage] = useState('')

  async function load() {
    const user = ensureLoggedIn('/pages/account/invoices/index')
    const token = getToken()
    if (!user || !token) return
    setLoading(true)
    setMessage('')
    try {
      const result = await backend.accountInvoiceApplications(token)
      setItems(result.items || [])
    } catch (error) {
      setMessage(error instanceof Error ? error.message : '发票信息暂时加载失败')
    } finally {
      setLoading(false)
    }
  }

  useDidShow(() => {
    void load()
  })

  const visibleItems = useMemo(() => {
    if (filter === 'all') return items
    return items.filter((item) => item.status === filter)
  }, [filter, items])

  function openOrder(item: BackendInvoiceApplication) {
    tapLight()
    Taro.navigateTo({ url: `/pages/account/orders/detail/index?id=${encodeURIComponent(item.orderNo)}` })
  }

  async function openInvoice(item: BackendInvoiceApplication) {
    const token = getToken()
    if (!token) return
    tapLight()
    try {
      const url = item.fileUrl || accountInvoiceFileUrl(item.invoiceNo)
      const downloaded = await Taro.downloadFile({
        url,
        header: { Authorization: `Bearer ${token}` }
      })
      if (downloaded.statusCode && downloaded.statusCode >= 400) throw new Error('发票文件暂时无法下载')
      await Taro.openDocument({ filePath: downloaded.tempFilePath, showMenu: true })
    } catch (error) {
      const url = item.fileUrl || accountInvoiceFileUrl(item.invoiceNo)
      await Taro.setClipboardData({ data: url })
      Taro.showToast({
        title: error instanceof Error ? '已复制发票链接' : '已复制发票链接',
        icon: 'none'
      })
    }
  }

  return (
    <Page title="我的发票" subtle="订单开票、处理进度与电子发票下载">
      <ScrollView scrollX className="account-tab-scroll" showScrollbar={false}>
        {filters.map((item) => (
          <View key={item.key} className={filter === item.key ? 'account-filter active' : 'account-filter'} onClick={() => setFilter(item.key)}>
            <Text>{item.label}</Text>
          </View>
        ))}
      </ScrollView>

      {message ? <Text className="form-error">{message}</Text> : null}
      {loading ? <EmptyState title="正在加载发票" compact /> : null}
      {!loading && visibleItems.length === 0 ? (
        <EmptyState
          title="暂无发票记录"
          text={filter === 'all' ? '付款后的订单可在订单详情里提交开票申请。' : '当前状态下还没有发票记录。'}
          compact
          action={<View className="ghost-btn small" onClick={() => Taro.navigateTo({ url: '/pages/account/orders/index' })}>查看订单</View>}
        />
      ) : null}

      <View className="invoice-list">
        {visibleItems.map((item) => (
          <View key={item.id} className="invoice-row">
            <View className="invoice-row-head">
              <View style={{ flex: 1, minWidth: 0 }}>
                <Text className="row-title">{item.title}</Text>
                <Text className="row-sub">{item.invoiceNo} · {formatDate(item.createdAt)}</Text>
              </View>
              <Text className={statusClass(item.status)}>{statusText[item.status]}</Text>
            </View>
            <View className="invoice-meta">
              <Text>订单 {item.orderNo}</Text>
              <Text>¥{yuan(item.amount).toLocaleString()}</Text>
            </View>
            <View className="invoice-meta">
              <Text>{item.invoiceTypeLabel || item.invoiceType || '电子发票'}</Text>
              <Text>{item.email || '-'}</Text>
            </View>
            {item.failureReason || item.adminNote ? (
              <Text className="invoice-note">{item.failureReason || item.adminNote}</Text>
            ) : null}
            <View className="invoice-actions">
              <View className="mini-link" onClick={() => openOrder(item)}>查看订单</View>
              {item.status === 'issued' ? <View className="inline-action" onClick={() => openInvoice(item)}>打开发票</View> : null}
            </View>
          </View>
        ))}
      </View>
    </Page>
  )
}
