'use client'

import { Suspense, useEffect, useMemo, useState } from 'react'
import { useSearchParams } from 'next/navigation'
import { AdminShell, hasAdminPermission } from '@/components/admin/AdminShell'
import { apiBase, backend, type BackendExpertWithdrawal, type StaffAccount, yuan } from '@/lib/backend'

const tabs = [
  { label: '待处理', value: 'pending' },
  { label: '已完成', value: 'completed' },
  { label: '已驳回', value: 'rejected' },
]

function formatDateTime(value?: string) {
  if (!value) return '-'
  const date = new Date(value)
  return `${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

function statusLabel(status: BackendExpertWithdrawal['status']) {
  return tabs.find((item) => item.value === status)?.label || status
}

function AdminExpertWithdrawalsContent() {
  const searchParams = useSearchParams()
  const [account, setAccount] = useState<StaffAccount | null>(null)
  const [status, setStatus] = useState('pending')
  const [items, setItems] = useState<BackendExpertWithdrawal[]>([])
  const [selectedId, setSelectedId] = useState(searchParams.get('selected') || '')
  const [saved, setSaved] = useState('')
  const [error, setError] = useState('')
  const [adminNote, setAdminNote] = useState('')
  const [paymentForm, setPaymentForm] = useState({ paidBank: '', paymentSerialNo: '', paymentProofFileId: '', payoutNote: '' })
  const selected = useMemo(() => items.find((item) => item.id === selectedId || item.withdrawalNo === selectedId) || items[0] || null, [items, selectedId])
  const canWriteWithdrawal = hasAdminPermission(account, 'withdrawal:update')
  const isPendingWithdrawal = selected?.status === 'pending'
  const canComplete = Boolean(paymentForm.paidBank.trim() && paymentForm.paymentSerialNo.trim() && paymentForm.paymentProofFileId)
  const summary = useMemo(() => ({
    count: items.length,
    amount: items.reduce((total, item) => total + item.amount, 0),
  }), [items])

  async function reload(nextStatus = status) {
    try {
      const [currentAccount, result] = await Promise.all([
        account ? Promise.resolve(account) : backend.staffMe(),
        backend.adminExpertWithdrawals(nextStatus),
      ])
      setAccount(currentAccount)
      setItems(result.items)
      setSelectedId((current) => result.items.some((item) => item.id === current || item.withdrawalNo === current) ? current : result.items[0]?.id || '')
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '提现申请加载失败')
    }
  }

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

  useEffect(() => {
    setAdminNote(selected?.adminNote || '')
    setPaymentForm({
      paidBank: selected?.paidBank || '',
      paymentSerialNo: selected?.paymentSerialNo || '',
      paymentProofFileId: selected?.paymentProofFileId || '',
      payoutNote: selected?.payoutNote || '',
    })
  }, [selected])

  async function updateWithdrawal(nextStatus: BackendExpertWithdrawal['status']) {
    if (!selected) return
    if (!canWriteWithdrawal) {
      setError('当前账号没有提现处理权限')
      return
    }
    if (nextStatus === 'rejected' && !adminNote.trim()) {
      setError('驳回提现前请填写处理备注')
      return
    }
    if (!window.confirm(nextStatus === 'completed' ? '确认已完成线下付款并记录提现完成？' : '确认驳回这笔提现申请？')) return
    try {
      await backend.updateAdminExpertWithdrawal(selected.id, { status: nextStatus, adminNote, ...paymentForm })
      setSaved('提现申请已处理')
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '提现处理失败')
    }
  }

  async function uploadProof(file: File) {
    if (!canWriteWithdrawal) {
      setError('当前账号没有提现处理权限')
      return
    }
    try {
      const uploaded = await backend.uploadAdminFile(file)
      setPaymentForm((current) => ({ ...current, paymentProofFileId: uploaded.id }))
      setSaved(`已上传凭证：${uploaded.fileName}`)
    } catch (err) {
      setError(err instanceof Error ? err.message : '付款凭证上传失败')
    }
  }

  return (
    <AdminShell
      title="专家提现申请"
      description="处理专家提现、付款流水、付款银行和凭证。"
      topbarMetrics={[
        { label: '当前申请', value: summary.count },
        { label: '当前金额', value: `¥${yuan(summary.amount).toLocaleString()}` },
      ]}
    >
      {(saved || error) && <div className={`mb-2 rounded-[4px] px-3 py-2 text-xs font-bold ${error ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>{error || saved}</div>}
      <div className="mb-2 flex flex-wrap gap-2">
        {tabs.map((tab) => (
          <button key={tab.value} onClick={() => setStatus(tab.value)} className={`h-8 rounded-[4px] border px-3 text-xs font-extrabold ${status === tab.value ? 'border-brand bg-brand-light text-brand' : 'border-line bg-white text-muted hover:border-brand hover:text-brand'}`}>
            {tab.label}
          </button>
        ))}
      </div>

      <div className="grid h-[calc(100vh-188px)] min-h-[520px] gap-3 overflow-hidden xl:grid-cols-[minmax(520px,1fr)_360px]">
        <section className="min-h-0 overflow-hidden border border-line bg-white">
          <div className="flex h-10 items-center justify-between border-b border-line px-3">
            <div className="text-sm font-extrabold text-ink">提现队列</div>
            <div className="text-xs font-bold text-muted">{items.length} 条</div>
          </div>
          <div className="h-[calc(100%-40px)] divide-y divide-line overflow-y-auto">
            {items.length === 0 ? (
              <div className="px-4 py-10 text-center text-sm font-bold text-muted">暂无提现申请</div>
            ) : items.map((item) => (
              <button key={item.id} onClick={() => setSelectedId(item.id)} className={`grid w-full gap-2 px-3 py-3 text-left hover:bg-bg lg:grid-cols-[1fr_110px_80px] lg:items-center ${selected?.id === item.id ? 'bg-brand-light' : ''}`}>
                <div>
                  <div className="text-sm font-extrabold text-ink">{item.expert.name} · {item.payeeName}</div>
                  <div className="mt-1 text-xs font-bold text-muted">{item.passportNo} · {item.user?.phone || '-'} · {formatDateTime(item.createdAt)}</div>
                </div>
                <div className="font-extrabold text-brand">¥{yuan(item.amount).toLocaleString()}</div>
                <div className="text-xs font-extrabold text-muted">{statusLabel(item.status)}</div>
              </button>
            ))}
          </div>
        </section>

        {selected && (
          <aside className="min-h-0 overflow-hidden border border-line bg-white">
            <div className="flex h-10 items-center justify-between border-b border-line px-3">
              <div className="text-sm font-extrabold text-ink">申请信息</div>
              <div className="text-xs font-extrabold text-brand">¥{yuan(selected.amount).toLocaleString()}</div>
            </div>
            <div className="h-[calc(100%-40px)] overflow-y-auto p-3">
            <div className="space-y-2 text-xs font-bold text-muted">
              <div>专家：{selected.expert.name}</div>
              <div>通行证：{selected.passportNo}</div>
              <div>金额：¥{yuan(selected.amount).toLocaleString()}</div>
              <div>收款人：{selected.payeeName}</div>
              <div>银行卡号：{selected.bankAccount}</div>
              <div>开户银行：{selected.bankName}</div>
              <div>状态：{statusLabel(selected.status)}</div>
              {selected.paymentSerialNo && <div>付款流水：{selected.paymentSerialNo}</div>}
              {selected.paidBank && <div>付款银行：{selected.paidBank}</div>}
            </div>
            {!canWriteWithdrawal && <div className="mt-3 rounded-[4px] bg-bg px-2 py-1.5 text-[11px] font-bold text-muted">当前账号仅可查看提现申请，不能上传付款凭证或处理提现。</div>}
            <div className="mt-3 grid gap-2">
              <input value={paymentForm.paidBank} onChange={(event) => setPaymentForm((current) => ({ ...current, paidBank: event.target.value }))} disabled={!canWriteWithdrawal} placeholder="付款银行" className="h-8 rounded-[4px] border border-line px-2 text-xs outline-none focus:border-brand disabled:bg-bg disabled:text-muted" />
              <input value={paymentForm.paymentSerialNo} onChange={(event) => setPaymentForm((current) => ({ ...current, paymentSerialNo: event.target.value }))} disabled={!canWriteWithdrawal} placeholder="付款流水号" className="h-8 rounded-[4px] border border-line px-2 text-xs outline-none focus:border-brand disabled:bg-bg disabled:text-muted" />
              <input value={paymentForm.payoutNote} onChange={(event) => setPaymentForm((current) => ({ ...current, payoutNote: event.target.value }))} disabled={!canWriteWithdrawal} placeholder="付款备注" className="h-8 rounded-[4px] border border-line px-2 text-xs outline-none focus:border-brand disabled:bg-bg disabled:text-muted" />
              {canWriteWithdrawal && (
                <label className="inline-flex h-8 cursor-pointer items-center justify-center rounded-[4px] border border-line px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
                  {paymentForm.paymentProofFileId ? '已上传凭证，可重新上传' : '上传付款凭证'}
                  <input type="file" accept="image/*,application/pdf" className="sr-only" onChange={(event) => {
                    const file = event.target.files?.[0]
                    if (file) void uploadProof(file)
                    event.target.value = ''
                  }} />
                </label>
              )}
              {paymentForm.paymentProofFileId && <a href={`${apiBase.replace(/\/api$/, '')}/api/files/${paymentForm.paymentProofFileId}`} target="_blank" rel="noreferrer" className="text-xs font-bold text-brand hover:underline">查看付款凭证</a>}
            </div>
            <div className="mt-3 border border-line">
              <div className="border-b border-line bg-bg px-2 py-1.5 text-xs font-extrabold text-ink">关联结算记录</div>
              {(selected.items || []).length === 0 ? (
                <div className="px-2 py-3 text-xs font-bold text-muted">暂无结算拆分记录</div>
              ) : (selected.items || []).map((item) => (
                <div key={item.id} className="border-b border-line px-2 py-2 text-xs last:border-b-0">
                  <div className="flex items-center justify-between gap-2">
                    <span className="font-extrabold text-ink">{item.settlementNo}</span>
                    <span className="font-extrabold text-brand">¥{yuan(item.amount).toLocaleString()}</span>
                  </div>
                  <div className="mt-1 truncate font-bold text-muted">{item.orderNo} · {item.productTitle}</div>
                </div>
              ))}
            </div>
            <textarea value={adminNote} onChange={(event) => setAdminNote(event.target.value)} disabled={!canWriteWithdrawal} rows={3} placeholder="处理备注" className="mt-3 w-full rounded-[4px] border border-line p-2 text-xs outline-none focus:border-brand disabled:bg-bg disabled:text-muted" />
            {!canComplete && selected.status === 'pending' && <div className="mt-2 rounded-[4px] bg-bg px-2 py-1.5 text-[11px] font-bold text-muted">完成提现必须填写付款银行、付款流水号并上传付款凭证。</div>}
            {canWriteWithdrawal && (
              <div className="mt-3 grid grid-cols-2 gap-2">
                <button onClick={() => void updateWithdrawal('completed')} disabled={!isPendingWithdrawal || !canComplete} className="h-8 rounded-[4px] bg-brand px-4 text-xs font-extrabold text-white disabled:cursor-not-allowed disabled:bg-line-dark">已完成</button>
                <button onClick={() => void updateWithdrawal('rejected')} disabled={!isPendingWithdrawal} className="h-8 rounded-[4px] border border-red-100 text-xs font-extrabold text-red-600 hover:border-red-300 disabled:cursor-not-allowed disabled:border-line disabled:text-muted">驳回</button>
              </div>
            )}
            </div>
          </aside>
        )}
      </div>
    </AdminShell>
  )
}

export default function AdminExpertWithdrawalsPage() {
  return (
    <Suspense fallback={<AdminShell title="专家提现申请" description="查看专家提现申请和收款信息，管理员可标记已完成或驳回。"><div className="border border-line bg-white px-4 py-6 text-sm font-bold text-muted">正在加载提现申请...</div></AdminShell>}>
      <AdminExpertWithdrawalsContent />
    </Suspense>
  )
}
