'use client'

import Link from 'next/link'
import { useParams } from 'next/navigation'
import { useEffect, useState } from 'react'
import type { FormEvent } from 'react'
import { ArrowRight, ChevronRight, Download, FileText, Send } from 'lucide-react'
import {
  formatAccountDateTime,
  parseOrderNote,
  serviceActionLabel,
  serviceEntryHref,
  serviceTypeLabel,
} from '@/components/account/account-utils'
import { useApp } from '@/components/providers/AppProvider'
import type { OrderRecord } from '@/components/providers/AppProvider'
import { backend, mapBackendOrder } from '@/lib/backend'

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

export default function AccountOrderDetailPage() {
  const params = useParams<{ id: string }>()
  const { user, token } = useApp()
  const [order, setOrder] = useState<OrderRecord | null>(null)
  const [loading, setLoading] = useState(true)
  const [loadError, setLoadError] = useState('')
  const [invoiceDraft, setInvoiceDraft] = useState({ title: '', taxNumber: '', email: '', remark: '' })
  const [submittingInvoice, setSubmittingInvoice] = useState(false)
  const [invoiceError, setInvoiceError] = useState('')
  const [invoiceMessage, setInvoiceMessage] = useState('')

  useEffect(() => {
    if (!token || !params.id) return
    let mounted = true
    setLoading(true)
    backend.accountOrder(token, params.id)
      .then((item) => {
        if (!mounted) return
        setOrder(mapBackendOrder(item))
        setLoadError('')
      })
      .catch((err) => {
        if (mounted) setLoadError(err instanceof Error ? err.message : '订单加载失败')
      })
      .finally(() => {
        if (mounted) setLoading(false)
      })
    return () => {
      mounted = false
    }
  }, [params.id, token])

  if (!user) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center">
          <h1 className="text-2xl font-extrabold text-ink">尚未登录</h1>
          <Link href="/login?redirect=%2Faccount" className="mt-7 inline-flex rounded-[4px] bg-brand px-6 py-3 text-sm font-extrabold text-white">去登录</Link>
        </div>
      </section>
    )
  }

  if (loading) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center text-sm font-bold text-muted">
          正在加载订单详情...
        </div>
      </section>
    )
  }

  if (!order) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center">
          <h1 className="text-2xl font-extrabold text-ink">订单不存在</h1>
          {loadError && <p className="mt-3 text-sm font-bold text-muted">{loadError}</p>}
          <Link href="/account/orders" className="mt-7 inline-flex rounded-[4px] bg-brand px-6 py-3 text-sm font-extrabold text-white">返回我的订单</Link>
        </div>
      </section>
    )
  }

  const currentOrder = order
  const invoice = currentOrder.invoiceApplication
  const canApplyInvoice = currentOrder.status === '已支付' && currentOrder.total > 0 && !invoice
  const invoiceTitle = invoiceDraft.title || user.invoiceTitle || user.organization || user.name || ''
  const invoiceTaxNumber = invoiceDraft.taxNumber || user.taxNumber || ''
  const invoiceEmail = invoiceDraft.email || user.invoiceEmail || user.email || ''
  const noteItems = parseOrderNote(currentOrder.note)
    .filter((item) => !['联系人', '联系电话', '预约电话', '预约联系人'].includes(item.label))

  async function submitInvoiceApplication(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!token) return
    setSubmittingInvoice(true)
    setInvoiceError('')
    setInvoiceMessage('')
    try {
      await backend.createAccountInvoiceApplication(token, currentOrder.id, {
        title: invoiceTitle,
        taxNumber: invoiceTaxNumber,
        email: invoiceEmail,
        remark: invoiceDraft.remark,
      })
      const refreshed = await backend.accountOrder(token, currentOrder.id)
      setOrder(mapBackendOrder(refreshed))
      setInvoiceMessage('发票申请已提交，财务将在 3-5 个工作日内处理。')
    } catch (err) {
      setInvoiceError(err instanceof Error ? err.message : '发票申请提交失败')
    } finally {
      setSubmittingInvoice(false)
    }
  }

  async function downloadInvoiceFile(invoiceNo: string) {
    if (!token) return
    setInvoiceError('')
    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) {
      setInvoiceError(err instanceof Error ? err.message : '发票文件下载失败')
    }
  }

  return (
    <section className="bg-bg py-8">
      <div className="mx-auto max-w-[1040px] px-6">
        <nav className="mb-5 flex flex-wrap items-center gap-2 text-sm text-muted">
          <Link href="/account" className="hover:text-brand">个人中心</Link>
          <ChevronRight className="h-4 w-4 text-soft" />
          <Link href="/account/orders" className="hover:text-brand">我的订单</Link>
          <ChevronRight className="h-4 w-4 text-soft" />
          <span className="font-bold text-ink">{currentOrder.id}</span>
        </nav>
        <div className="rounded-[4px] border border-line bg-white">
          <div className="flex flex-col gap-4 border-b border-line px-6 py-5 md:flex-row md:items-center md:justify-between">
            <div>
              <h1 className="text-2xl font-extrabold text-ink">订单详情</h1>
              <div className="mt-1 text-sm text-muted">{currentOrder.id} · {formatAccountDateTime(currentOrder.createdAt)} · {currentOrder.status}</div>
            </div>
            <div className="text-3xl font-extrabold text-brand">¥{currentOrder.total.toLocaleString()}</div>
          </div>

          <div className="grid gap-8 p-6 lg:grid-cols-[1fr_300px]">
            <div>
              <div className="text-lg font-extrabold text-ink">服务明细</div>
              <div className="mt-4 divide-y divide-line rounded-[4px] border border-line">
                {currentOrder.items.map((item) => (
                  <div key={`${item.type}-${item.id}`} className="grid gap-3 px-4 py-4 md:grid-cols-[1fr_auto] md:items-center">
                    <div>
                      <div className="flex flex-wrap items-center gap-2">
                        <span className="rounded-[4px] bg-brand-light px-2 py-1 text-xs font-extrabold text-brand">{serviceTypeLabel(item.type)}</span>
                        <Link href={item.href} className="font-bold text-ink hover:text-brand">{item.title}</Link>
                      </div>
                      {item.meta && <div className="mt-2 text-sm text-muted">{item.meta}</div>}
                      <div className="mt-2 text-xs text-muted">数量 x{item.quantity}</div>
                    </div>
                    <Link href={serviceEntryHref(item.type, item.id, item.serviceEntryHref)} className="inline-flex w-fit items-center gap-2 rounded-[4px] bg-brand px-4 py-2 text-sm font-extrabold text-white">
                      {serviceActionLabel(item.type)}
                      <ArrowRight className="h-4 w-4" />
                    </Link>
                  </div>
                ))}
              </div>

              <div className="mt-8 text-lg font-extrabold text-ink">其他信息</div>
              {noteItems.length === 0 ? (
                <div className="mt-3 rounded-[4px] bg-bg p-4 text-sm leading-7 text-muted">暂无备注</div>
              ) : (
                <div className="mt-3 divide-y divide-line rounded-[4px] border border-line">
                  {noteItems.map((item) => (
                    <div key={`${item.label}-${item.value}`} className="grid gap-2 px-4 py-3 text-sm md:grid-cols-[110px_1fr]">
                      <div className="font-bold text-muted">{item.label}</div>
                      <div className="font-bold leading-6 text-ink">{item.value}</div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            <aside className="h-fit rounded-[4px] border border-line p-5">
              <div className="space-y-3 text-sm">
                <div className="flex justify-between"><span className="text-muted">商品小计</span><span className="font-bold text-ink">¥{currentOrder.subtotal.toLocaleString()}</span></div>
                <div className="flex justify-between"><span className="text-muted">会员折扣</span><span className="font-bold text-ink">- ¥{currentOrder.discount.toLocaleString()}</span></div>
                <div className="flex justify-between border-t border-line pt-3"><span className="text-muted">实付</span><span className="font-extrabold text-brand">¥{currentOrder.total.toLocaleString()}</span></div>
              </div>
              <div className="mt-6 border-t border-line pt-5">
                <div className="flex items-center gap-2 text-base font-extrabold text-ink">
                  <FileText className="h-4 w-4 text-brand" />
                  发票信息
                </div>
                {invoiceMessage && <div className="mt-3 rounded-[4px] bg-brand-light px-3 py-2 text-xs font-bold text-brand">{invoiceMessage}</div>}
                {invoiceError && <div className="mt-3 rounded-[4px] bg-red-50 px-3 py-2 text-xs font-bold text-red-700">{invoiceError}</div>}
                {invoice ? (
                  <div className="mt-4 space-y-3 text-sm">
                    <div className="flex justify-between gap-3"><span className="text-muted">状态</span><span className="font-extrabold text-brand">{invoiceStatusLabel[invoice.status] || invoice.status}</span></div>
                    <div className="flex justify-between gap-3"><span className="text-muted">申请单号</span><span className="font-bold text-ink">{invoice.invoiceNo}</span></div>
                    <div className="flex justify-between gap-3"><span className="text-muted">发票抬头</span><span className="text-right font-bold text-ink">{invoice.title}</span></div>
                    {invoice.providerInvoiceId && <div className="flex justify-between gap-3"><span className="text-muted">发票号码</span><span className="text-right font-bold text-ink">{invoice.providerInvoiceId}</span></div>}
                    {invoice.issuedAt && <div className="flex justify-between gap-3"><span className="text-muted">开票时间</span><span className="text-right font-bold text-ink">{formatAccountDateTime(invoice.issuedAt)}</span></div>}
                    {(invoice.status === 'pending' || invoice.status === 'processing') && (
                      <div className="rounded-[4px] bg-bg p-3 text-xs font-bold leading-6 text-muted">财务将在 3-5 个工作日内处理，请留意接收邮箱。</div>
                    )}
                    {(invoice.status === 'rejected' || invoice.status === 'failed') && (
                      <div className="rounded-[4px] bg-red-50 p-3 text-xs font-bold leading-6 text-red-700">{invoice.failureReason || invoice.adminNote || '请联系工作人员核对发票信息。'}</div>
                    )}
                    {invoice.status === 'issued' && invoice.pdfFileId && (
                      <button type="button" onClick={() => void downloadInvoiceFile(invoice.invoiceNo)} className="flex w-full items-center justify-center gap-2 rounded-[4px] bg-ink py-3 text-sm font-extrabold text-white">
                        <Download className="h-4 w-4" />
                        下载电子发票
                      </button>
                    )}
                  </div>
                ) : canApplyInvoice ? (
                  <form className="mt-4 space-y-3" onSubmit={submitInvoiceApplication}>
                    <label className="block text-xs font-extrabold text-muted">
                      发票抬头
                      <input value={invoiceTitle} onChange={(event) => setInvoiceDraft((current) => ({ ...current, title: event.target.value }))} className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm font-bold text-ink outline-none focus:border-brand" />
                    </label>
                    <label className="block text-xs font-extrabold text-muted">
                      税号
                      <input value={invoiceTaxNumber} onChange={(event) => setInvoiceDraft((current) => ({ ...current, taxNumber: event.target.value }))} className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm font-bold text-ink outline-none focus:border-brand" />
                    </label>
                    <label className="block text-xs font-extrabold text-muted">
                      接收邮箱
                      <input value={invoiceEmail} onChange={(event) => setInvoiceDraft((current) => ({ ...current, email: event.target.value }))} className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm font-bold text-ink outline-none focus:border-brand" />
                    </label>
                    <label className="block text-xs font-extrabold text-muted">
                      备注
                      <textarea value={invoiceDraft.remark} onChange={(event) => setInvoiceDraft((current) => ({ ...current, remark: event.target.value }))} rows={3} className="mt-1 w-full resize-none rounded-[4px] border border-line px-3 py-2 text-sm font-bold text-ink outline-none focus:border-brand" />
                    </label>
                    <button disabled={submittingInvoice} className="flex w-full items-center justify-center gap-2 rounded-[4px] bg-brand py-3 text-sm font-extrabold text-white disabled:opacity-60">
                      <Send className="h-4 w-4" />
                      {submittingInvoice ? '提交中' : '提交发票申请'}
                    </button>
                  </form>
                ) : (
                  <div className="mt-3 rounded-[4px] bg-bg p-3 text-xs font-bold leading-6 text-muted">
                    {currentOrder.total <= 0 ? '0 元订单不可申请发票。' : '订单支付完成后可申请普通电子发票。'}
                  </div>
                )}
              </div>
            </aside>
          </div>
        </div>
      </div>
    </section>
  )
}
