'use client'

import { useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { useParams } from 'next/navigation'
import { ArrowLeft, Download, ExternalLink, FileUp, RefreshCw, Save } from 'lucide-react'
import { AdminShell, hasAdminPermission } from '@/components/admin/AdminShell'
import { backend, type BackendInvoiceApplication, type StaffAccount, yuan } from '@/lib/backend'

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

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

function datetimeLocalValue(value?: string | null) {
  if (!value) return ''
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return ''
  const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
  return local.toISOString().slice(0, 16)
}

export default function AdminInvoiceDetailPage() {
  const params = useParams<{ id: string }>()
  const invoiceKey = useMemo(() => decodeURIComponent(String(params.id || '')), [params.id])
  const [account, setAccount] = useState<StaffAccount | null>(null)
  const [invoice, setInvoice] = useState<BackendInvoiceApplication | null>(null)
  const [providerInvoiceId, setProviderInvoiceId] = useState('')
  const [issuedAt, setIssuedAt] = useState('')
  const [issuedBy, setIssuedBy] = useState('')
  const [failureReason, setFailureReason] = useState('')
  const [adminNote, setAdminNote] = useState('')
  const [file, setFile] = useState<File | null>(null)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [error, setError] = useState('')
  const [message, setMessage] = useState('')
  const canWriteInvoice = hasAdminPermission(account, 'invoice:write')

  function hydrateDraft(item: BackendInvoiceApplication) {
    setProviderInvoiceId(item.providerInvoiceId || '')
    setIssuedAt(datetimeLocalValue(item.issuedAt))
    setIssuedBy(item.issuedBy || '')
    setFailureReason(item.failureReason || '')
    setAdminNote(item.adminNote || '')
  }

  async function reload() {
    setLoading(true)
    try {
      const [currentAccount, item] = await Promise.all([
        account ? Promise.resolve(account) : backend.staffMe(),
        backend.adminInvoiceApplication(invoiceKey),
      ])
      setAccount(currentAccount)
      setInvoice(item)
      hydrateDraft(item)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '发票申请加载失败')
    } finally {
      setLoading(false)
    }
  }

  async function uploadFile() {
    if (!invoice || !file) return
    if (!canWriteInvoice) {
      setError('当前账号没有发票处理权限')
      return
    }
    if (!window.confirm('确认上传并关联这份发票文件？')) return
    setUploading(true)
    setError('')
    setMessage('')
    try {
      const result = await backend.uploadAdminInvoiceFile(invoice.invoiceNo, file)
      setInvoice(result.invoice)
      hydrateDraft(result.invoice)
      setFile(null)
      setMessage('发票文件已上传。')
    } catch (err) {
      setError(err instanceof Error ? err.message : '发票文件上传失败')
    } finally {
      setUploading(false)
    }
  }

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


  async function updateStatus(status: BackendInvoiceApplication['status']) {
    if (!invoice) return
    if (!canWriteInvoice) {
      setError('当前账号没有发票处理权限')
      return
    }
    if (['rejected', 'failed'].includes(status) && !failureReason.trim()) {
      setError('驳回或失败前请填写原因')
      return
    }
    const actionLabel = statusLabel[status] || status
    if (!window.confirm(`确认将发票状态更新为“${actionLabel}”？`)) return
    setSaving(true)
    setError('')
    setMessage('')
    try {
      const updated = await backend.updateAdminInvoiceApplication(invoice.invoiceNo, {
        status,
        providerInvoiceId,
        issuedAt: issuedAt ? new Date(issuedAt).toISOString() : '',
        issuedBy,
        failureReason,
        adminNote,
      })
      setInvoice(updated)
      hydrateDraft(updated)
      setMessage('发票状态已更新。')
    } catch (err) {
      setError(err instanceof Error ? err.message : '发票状态更新失败')
    } finally {
      setSaving(false)
    }
  }

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

  return (
    <AdminShell title="发票详情" description="处理手动开票、上传电子发票文件并保留财务操作痕迹。">
      <div className="mb-3 flex flex-wrap justify-between gap-2">
        <Link href="/admin/invoices" className="inline-flex h-8 items-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">
          <ArrowLeft className="h-4 w-4" />
          返回发票中心
        </Link>
        <button type="button" onClick={() => void reload()} className="inline-flex h-8 items-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">
          <RefreshCw className="h-4 w-4" />
          刷新
        </button>
      </div>

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

      {!loading && invoice && (
        <div className="grid h-[calc(100vh-145px)] min-h-[560px] gap-3 overflow-hidden xl:grid-cols-[1fr_340px]">
          <section className="min-h-0 overflow-y-auto border border-line bg-white">
            <div className="border-b border-line px-4 py-3">
              <h2 className="text-lg font-extrabold text-ink">{invoice.invoiceNo}</h2>
              <div className="mt-1 text-xs font-bold text-muted">订单 {invoice.orderNo} · 用户 {invoice.userPhone || '-'} · {formatDate(invoice.createdAt)}</div>
            </div>

            <div className="grid gap-4 p-4 lg:grid-cols-2">
              <div>
                <div className="text-sm font-extrabold text-ink">申请信息</div>
                <div className="mt-3 divide-y divide-line border border-line text-xs">
                  {[
                    ['发票类型', invoice.invoiceTypeLabel || '普通电子发票'],
                    ['发票抬头', invoice.title],
                    ['税号', invoice.taxNumber || '-'],
                    ['接收邮箱', invoice.email],
                    ['申请金额', `¥${yuan(invoice.amount).toLocaleString()}`],
                    ['用户备注', invoice.remark || '-'],
                  ].map(([label, value]) => (
                    <div key={label} className="grid gap-2 px-3 py-2 md:grid-cols-[82px_1fr]">
                      <span className="font-bold text-muted">{label}</span>
                      <span className="font-bold text-ink">{value}</span>
                    </div>
                  ))}
                </div>
              </div>

              <div>
                <div className="text-sm font-extrabold text-ink">订单信息</div>
                <div className="mt-3 divide-y divide-line border border-line text-xs">
                  {[
                    ['订单号', invoice.orderNo],
                    ['结算编号', invoice.settlementNo || '-'],
                    ['当前状态', statusLabel[invoice.status] || invoice.status],
                    ['发票号码', invoice.providerInvoiceId || '-'],
                    ['开票时间', formatDate(invoice.issuedAt)],
                    ['失败/驳回原因', invoice.failureReason || '-'],
                  ].map(([label, value]) => (
                    <div key={label} className="grid gap-2 px-3 py-2 md:grid-cols-[82px_1fr]">
                      <span className="font-bold text-muted">{label}</span>
                      <span className="font-bold text-ink">{value}</span>
                    </div>
                  ))}
                </div>
                <div className="mt-3 flex flex-wrap gap-2">
                  <Link href={`/admin/orders/${encodeURIComponent(invoice.orderNo)}`} className="inline-flex h-8 items-center gap-1.5 rounded-[4px] border border-line px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">
                    <ExternalLink className="h-4 w-4" />
                    查看订单
                  </Link>
                  {invoice.pdfFileId && (
                    <button type="button" onClick={() => void downloadInvoiceFile()} className="inline-flex h-8 items-center gap-1.5 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white">
                      <Download className="h-4 w-4" />
                      下载发票文件
                    </button>
                  )}
                </div>
              </div>
            </div>
          </section>

          <aside className="min-h-0 overflow-y-auto border border-line bg-white p-4">
            <div className="text-sm font-extrabold text-ink">财务处理</div>
            {!canWriteInvoice && <div className="mt-3 rounded-[4px] bg-bg px-3 py-2 text-xs font-bold leading-5 text-muted">当前账号仅可查看发票申请，不能上传文件或变更开票状态。</div>}
            <div className="mt-3 space-y-3">
              {canWriteInvoice && (
                <>
                  <label className="block text-xs font-extrabold text-muted">
                    上传发票文件（PDF/OFD）
                    <input type="file" accept=".pdf,.ofd,application/pdf" onChange={(event) => setFile(event.target.files?.[0] || null)} className="mt-2 block w-full text-xs font-bold text-muted file:mr-3 file:h-8 file:rounded-[4px] file:border-0 file:bg-bg file:px-3 file:text-xs file:font-bold file:text-ink" />
                  </label>
                  <button type="button" disabled={!file || uploading} onClick={() => void uploadFile()} className="inline-flex h-8 w-full items-center justify-center gap-1.5 rounded-[4px] border border-line text-xs font-bold text-muted hover:border-brand hover:text-brand disabled:opacity-60">
                    <FileUp className="h-4 w-4" />
                    {uploading ? '上传中' : '上传文件'}
                  </button>
                </>
              )}

              <label className="block text-xs font-extrabold text-muted">
                真实发票号码
                <input value={providerInvoiceId} onChange={(event) => setProviderInvoiceId(event.target.value)} disabled={!canWriteInvoice} className="mt-1 h-8 w-full rounded-[4px] border border-line px-2 text-xs font-bold text-ink outline-none focus:border-brand disabled:bg-bg disabled:text-muted" />
              </label>
              <label className="block text-xs font-extrabold text-muted">
                开票时间
                <input type="datetime-local" value={issuedAt} onChange={(event) => setIssuedAt(event.target.value)} disabled={!canWriteInvoice} className="mt-1 h-8 w-full rounded-[4px] border border-line px-2 text-xs font-bold text-ink outline-none focus:border-brand disabled:bg-bg disabled:text-muted" />
              </label>
              <label className="block text-xs font-extrabold text-muted">
                开票人
                <input value={issuedBy} onChange={(event) => setIssuedBy(event.target.value)} disabled={!canWriteInvoice} className="mt-1 h-8 w-full rounded-[4px] border border-line px-2 text-xs font-bold text-ink outline-none focus:border-brand disabled:bg-bg disabled:text-muted" />
              </label>
              <label className="block text-xs font-extrabold text-muted">
                失败/驳回原因
                <textarea value={failureReason} onChange={(event) => setFailureReason(event.target.value)} disabled={!canWriteInvoice} rows={3} className="mt-1 w-full resize-none rounded-[4px] border border-line px-2 py-1.5 text-xs font-bold text-ink outline-none focus:border-brand disabled:bg-bg disabled:text-muted" />
              </label>
              <label className="block text-xs font-extrabold text-muted">
                财务备注
                <textarea value={adminNote} onChange={(event) => setAdminNote(event.target.value)} disabled={!canWriteInvoice} rows={3} className="mt-1 w-full resize-none rounded-[4px] border border-line px-2 py-1.5 text-xs font-bold text-ink outline-none focus:border-brand disabled:bg-bg disabled:text-muted" />
              </label>

              {canWriteInvoice && (
                <div className="grid gap-2">
                  <button type="button" disabled={saving || invoice.status === 'issued'} onClick={() => void updateStatus('processing')} className="inline-flex h-8 items-center justify-center gap-1.5 rounded-[4px] border border-line text-xs font-bold text-muted hover:border-brand hover:text-brand disabled:opacity-60">
                    标记开票中
                  </button>
                  <button type="button" disabled={saving || invoice.status !== 'processing'} onClick={() => void updateStatus('issued')} className="inline-flex h-8 items-center justify-center gap-1.5 rounded-[4px] bg-brand text-xs font-extrabold text-white disabled:opacity-60">
                    <Save className="h-4 w-4" />
                    录入已开票
                  </button>
                  <div className="grid grid-cols-2 gap-2">
                    <button type="button" disabled={saving || invoice.status === 'issued'} onClick={() => void updateStatus('rejected')} className="h-8 rounded-[4px] border border-line text-xs font-bold text-muted hover:border-red-300 hover:text-red-700 disabled:opacity-60">
                      驳回
                    </button>
                    <button type="button" disabled={saving || invoice.status === 'issued'} onClick={() => void updateStatus('failed')} className="h-8 rounded-[4px] border border-line text-xs font-bold text-muted hover:border-red-300 hover:text-red-700 disabled:opacity-60">
                      标记失败
                    </button>
                  </div>
                </div>
              )}
            </div>
          </aside>
        </div>
      )}
    </AdminShell>
  )
}
