/**
 * 发票管理页面
 */
import { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Button, Tabs, Tag, Loading, Dialog } from '@nutui/nutui-react-taro'
import { pageInvoice, listInvoiceTitles, applyInvoice, cancelInvoice, getInvoiceableAmount } from '@/api/invoice'
import type { Invoice, InvoiceTitle, InvoiceStatus } from '@/types/invoice'
import './invoice.scss'

// 状态映射
const STATUS_MAP: Record<InvoiceStatus, { text: string; color: string }> = {
  pending: { text: '待审核', color: '#FFC107' },
  approved: { text: '已通过', color: '#2196F3' },
  rejected: { text: '已拒绝', color: '#F44336' },
  issued: { text: '已开票', color: '#4CAF50' },
  cancelled: { text: '已取消', color: '#9E9E9E' },
}

// Tab 配置
const TABS = [
  { key: 'all', title: '全部' },
  { key: 'pending', title: '待审核' },
  { key: 'approved', title: '已通过' },
  { key: 'issued', title: '已开票' }
]

const InvoicePage: React.FC = () => {
  const [loading, setLoading] = useState(true)
  const [tabIndex, setTabIndex] = useState(0)
  const [invoices, setInvoices] = useState<Invoice[]>([])
  const [invoiceableAmount, setInvoiceableAmount] = useState(0)
  const [showApplyModal, setShowApplyModal] = useState(false)

  useEffect(() => {
    loadData()
  }, [tabIndex])

  const loadData = async () => {
    setLoading(true)
    try {
      const [invoiceData, amountData] = await Promise.all([
        pageInvoice({ status: tabIndex > 0 ? TABS[tabIndex].key as InvoiceStatus : undefined }),
        getInvoiceableAmount()
      ])
      setInvoices(invoiceData.list)
      setInvoiceableAmount(amountData.amount)
    } catch (e) {
      console.error('加载失败', e)
    } finally {
      setLoading(false)
    }
  }

  const handleCancel = async (id: string) => {
    Dialog.confirm({
      title: '确认取消',
      content: '确定要取消这个发票申请吗？',
      onConfirm: async () => {
        await cancelInvoice(id)
        Taro.showToast({ title: '已取消', icon: 'success' })
        loadData()
      }
    })
  }

  return (
    <View className="invoice-page">
      {/* 可开票金额 */}
      <View className="amount-card">
        <Text className="amount-label">可开票金额</Text>
        <Text className="amount-value">¥{invoiceableAmount.toLocaleString()}</Text>
        <Button className="apply-btn" onClick={() => setShowApplyModal(true)}>
          申请开票
        </Button>
      </View>

      {/* 发票列表 */}
      <Tabs value={tabIndex} onChange={(val) => setTabIndex(Number(val))}>
        {TABS.map(tab => (
          <Tabs.TabPane key={tab.key} title={tab.title} value={TABS.indexOf(tab)}>
            {loading ? (
              <Loading className="loading">加载中...</Loading>
            ) : invoices.length === 0 ? (
              <View className="empty">
                <Text>暂无发票记录</Text>
              </View>
            ) : (
              <ScrollView className="invoice-list" scrollY>
                {invoices.map(invoice => (
                  <View key={invoice.id} className="invoice-card">
                    <View className="invoice-header">
                      <Text className="invoice-title">{invoice.title}</Text>
                      <Tag color={STATUS_MAP[invoice.status]?.color}>{STATUS_MAP[invoice.status]?.text}</Tag>
                    </View>
                    <View className="invoice-info">
                      <Text className="info-item">金额: ¥{invoice.amount.toLocaleString()}</Text>
                      <Text className="info-item">类型: {invoice.type === 'normal' ? '普通发票' : '增值税专用发票'}</Text>
                    </View>
                    <View className="invoice-footer">
                      <Text className="create-time">{invoice.createTime.slice(0, 10)}</Text>
                      {invoice.status === 'pending' && (
                        <Button size="small" onClick={() => handleCancel(invoice.id)}>
                          取消申请
                        </Button>
                      )}
                    </View>
                  </View>
                ))}
              </ScrollView>
            )}
          </Tabs.TabPane>
        ))}
      </Tabs>
    </View>
  )
}

export default InvoicePage
