'use client'

import { useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { Download, RefreshCw } from 'lucide-react'
import { AccountAuthPrompt } from '@/components/account/AccountAuthPrompt'
import { AccountEmptyState } from '@/components/account/AccountEmptyState'
import { formatAccountDateTime } from '@/components/account/account-utils'
import { useApp } from '@/components/providers/AppProvider'
import { backend, type BackendInvoiceApplication, yuan } from '@/lib/backend'

const statusGroups = [
  { label: '待开票', values: ['pending'] },
  { label: '开票中', values: ['processing'] },
  { label: '已开票', values: ['issued'] },
  { label: '异常处理', values: ['rejected', 'failed'] },
]

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

function statusTone(status: string) {
  if (status === 'issued') return 'bg-brand/10 text-brand'
  if (status === 'processing') return 'bg-amber-50 text-amber-700'
  if (status === 'rejected' || status === 'failed') return 'bg-red-50 text-red-700'
  return 'bg-bg text-muted'
}

export default function AccountInvoicesPage() {
  const { token, user } = useApp()
  const [items, setItems] = useState<BackendInvoiceApplication[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const groupedInvoices = useMemo(() => statusGroups
    .map((group) => ({
      ...group,
      items: items.filter((item) => group.values.includes(item.status)),
    }))
    .filter((group) => group.items.length > 0), [items])

  async function reload() {
    if (!token) return
    setLoading(true)
    try {
      const result = await backend.accountInvoiceApplications(token)
      setItems(result.items || [])
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '发票列表加载失败')
    } finally {
      setLoading(false)
    }
  }

  async function downloadInvoiceFile(invoiceNo: string) {
    if (!token) return
    try {
      const blob = await backend.downloadAccountInvoiceFile(token, invoiceNo)
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `${invoiceNo}.pdf`
      link.click()
      URL.revokeObjectURL(url)
    } catch (err) {
      setError(err instanceof Error ? err.message : '发票文件下载失败')
    }
  }

  useEffect(() => {
    void reload()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token])

  if (!user) return <AccountAuthPrompt message="登录后可查看发票申请和下载电子发票。" />

  return (
    <div>
      <div className="mb-4 flex items-center justify-between gap-3">
        <div className="text-sm font-extrabold text-muted">普通电子发票</div>
        <button
          type="button"
          onClick={() => void reload()}
          className="inline-flex h-9 items-center gap-2 rounded-[4px] border border-line bg-white px-3 text-sm font-bold text-muted hover:border-brand hover:text-brand"
        >
          <RefreshCw className="h-4 w-4" />
          刷新
        </button>
      </div>

      {error && <div className="mb-4 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}
      {loading && <div className="rounded-[4px] border border-line bg-white px-4 py-8 text-sm font-bold text-muted">正在加载发票...</div>}

      {!loading && items.length === 0 ? (
        <AccountEmptyState title="还没有发票申请" description="已支付订单可在订单详情中提交普通电子发票申请。" actionLabel="查看订单" actionHref="/account/orders" />
      ) : (
        <div className="space-y-6">
          {groupedInvoices.map((group) => (
            <section key={group.label}>
              <div className="mb-2 text-sm font-extrabold text-muted">{group.label}</div>
              <div className="overflow-hidden rounded-[4px] border border-line bg-white">
                {group.items.map((item) => (
                  <div
                    key={item.id}
                    className="grid border-b border-line transition last:border-b-0 hover:bg-[#f8fbff] md:grid-cols-[1fr_104px]"
                  >
                    <div className="px-4 py-3">
                      <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                        <div className="min-w-0">
                          <div className="truncate text-[15px] font-extrabold leading-6 text-ink">{item.title}</div>
                          <div className="mt-0.5 text-sm text-muted">{item.invoiceTypeLabel || '普通电子发票'} · {item.email}</div>
                        </div>
                        <div className="shrink-0 text-base font-extrabold text-brand">¥{yuan(item.amount).toLocaleString()}</div>
                      </div>

                      <div className="mt-3 grid gap-x-5 gap-y-1.5 text-sm md:grid-cols-3 xl:grid-cols-5">
                        <div>
                          <div className="text-xs font-bold text-soft">申请单号</div>
                          <div className="mt-0.5 break-all font-extrabold text-ink">{item.invoiceNo}</div>
                        </div>
                        <div>
                          <div className="text-xs font-bold text-soft">订单号</div>
                          <div className="mt-0.5 break-all font-extrabold text-ink">{item.orderNo}</div>
                        </div>
                        <div>
                          <div className="text-xs font-bold text-soft">税号</div>
                          <div className="mt-0.5 break-all font-extrabold text-ink">{item.taxNumber || '-'}</div>
                        </div>
                        <div>
                          <div className="text-xs font-bold text-soft">申请时间</div>
                          <div className="mt-0.5 font-extrabold text-ink">{formatAccountDateTime(item.createdAt)}</div>
                        </div>
                        <div>
                          <div className="text-xs font-bold text-soft">开票时间</div>
                          <div className="mt-0.5 font-extrabold text-ink">{item.issuedAt ? formatAccountDateTime(item.issuedAt) : '-'}</div>
                        </div>
                      </div>

                      {(item.failureReason || item.adminNote) && (
                        <div className="mt-3 rounded-[4px] bg-red-50 px-3 py-2 text-xs font-bold text-red-700">
                          {item.failureReason || item.adminNote}
                        </div>
                      )}

                      <div className="mt-3 flex flex-wrap gap-2">
                        <Link href={`/account/orders/${encodeURIComponent(item.orderNo)}`} className="inline-flex h-9 items-center rounded-[4px] border border-line px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">
                          查看订单
                        </Link>
                        {item.status === 'issued' && item.pdfFileId && (
                          <button
                            type="button"
                            onClick={() => void downloadInvoiceFile(item.invoiceNo)}
                            className="inline-flex h-9 items-center gap-2 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white"
                          >
                            <Download className="h-3.5 w-3.5" />
                            下载电子发票
                          </button>
                        )}
                      </div>
                    </div>

                    <div className={`grid min-h-[44px] place-items-center border-t border-line px-3 text-center text-sm font-extrabold md:min-h-full md:border-l md:border-t-0 ${statusTone(item.status)}`}>
                      {statusLabel[item.status] || item.status}
                    </div>
                  </div>
                ))}
              </div>
            </section>
          ))}
        </div>
      )}
    </div>
  )
}
