'use client'

import { Suspense, useEffect, useMemo, useState } from 'react'
import { useSearchParams } from 'next/navigation'
import { AdminShell } from '@/components/admin/AdminShell'
import { assetUrl, backend, type BackendExpertApplication, cents } from '@/lib/backend'

const tabs = [
  { label: '全部', value: '' },
  { label: '待审核', value: 'pending' },
  { label: '已通过', value: 'approved' },
  { label: '未通过', value: 'rejected' },
]

function statusLabel(status: BackendExpertApplication['status']) {
  if (status === 'pending') return '待审核'
  if (status === 'approved') return '已通过'
  if (status === 'rejected') return '未通过'
  return '已撤回'
}

function AdminExpertApplicationsContent() {
  const searchParams = useSearchParams()
  const selectedFromQuery = searchParams.get('selected') || ''
  const [status, setStatus] = useState(selectedFromQuery ? '' : 'pending')
  const [items, setItems] = useState<BackendExpertApplication[]>([])
  const [selectedId, setSelectedId] = useState(selectedFromQuery)
  const [keyword, setKeyword] = useState('')
  const [saved, setSaved] = useState('')
  const [error, setError] = useState('')
  const [review, setReview] = useState({ price: '1200', shareRatio: '80', publish: true, rejectReason: '' })
  const summary = useMemo(() => ({
    pending: items.filter((item) => item.status === 'pending').length,
    approved: items.filter((item) => item.status === 'approved').length,
    rejected: items.filter((item) => item.status === 'rejected').length,
    total: items.length,
  }), [items])
  const visibleItems = useMemo(() => {
    const word = keyword.trim().toLowerCase()
    if (!word) return items
    return items.filter((item) => [
      item.applicationNo,
      item.name,
      item.contactPhone,
      item.organization,
      item.title,
      item.passportNo,
      item.user?.phone,
      ...item.directions,
    ].filter(Boolean).join(' ').toLowerCase().includes(word))
  }, [items, keyword])

  const selected = useMemo(() => items.find((item) => item.id === selectedId || item.applicationNo === selectedId) || visibleItems[0] || items[0] || null, [items, selectedId, visibleItems])

  async function reload(nextStatus = status) {
    try {
      const result = await backend.adminExpertApplications(nextStatus)
      setItems(result.items)
      setSelectedId((current) => result.items.some((item) => item.id === current || item.applicationNo === 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(() => {
    if (!selectedFromQuery) return
    setStatus('')
    setSelectedId(selectedFromQuery)
  }, [selectedFromQuery])

  async function approve(item: BackendExpertApplication) {
    try {
      await backend.reviewExpertApplication(item.id, {
        action: 'approved',
        priceAmount: cents(Number(review.price || 0)),
        shareRatio: Number(review.shareRatio || 80),
        publish: review.publish,
      })
      setSaved('申请已通过，专家档案已生成')
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '审核通过失败')
    }
  }

  async function reject(item: BackendExpertApplication) {
    if (!review.rejectReason.trim()) {
      setError('未通过必须填写原因')
      return
    }
    try {
      await backend.reviewExpertApplication(item.id, {
        action: 'rejected',
        rejectReason: review.rejectReason.trim(),
      })
      setSaved('申请已驳回')
      setReview((current) => ({ ...current, rejectReason: '' }))
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '驳回失败')
    }
  }

  return (
    <AdminShell
      title="专家申请审核"
      description="审核入驻材料，通过后生成专家档案，驳回必须写原因。"
      topbarMetrics={[
        { label: '待审', value: summary.pending },
        { label: '已通过', value: summary.approved },
        { label: '未通过', value: summary.rejected },
        { label: '当前列表', value: summary.total },
      ]}
    >
      {(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 items-center gap-2">
        <input value={keyword} onChange={(event) => setKeyword(event.target.value)} placeholder="搜申请编号、姓名、机构、手机号、方向" className="h-8 w-full rounded-[4px] border border-line bg-white px-3 text-xs font-bold outline-none focus:border-brand md:w-80" />
        {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-198px)] min-h-[520px] gap-3 overflow-hidden xl:grid-cols-[340px_1fr]">
        <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">{visibleItems.length} 条</div>
          </div>
          <div className="h-[calc(100%-40px)] divide-y divide-line overflow-y-auto">
            {visibleItems.length === 0 ? (
              <div className="px-4 py-10 text-center text-sm font-bold text-muted">暂无申请</div>
            ) : visibleItems.map((item) => (
              <button key={item.id} onClick={() => setSelectedId(item.id)} className={`block w-full px-3 py-3 text-left hover:bg-bg ${selected?.id === item.id ? 'bg-brand-light' : ''}`}>
                <div className="truncate text-sm font-extrabold text-ink">{item.name} · {item.title || '未填职务'}</div>
                <div className="mt-1 text-xs font-bold text-muted">{item.organization} · {item.passportNo}</div>
                <div className="mt-1 text-xs font-extrabold text-brand">{statusLabel(item.status)}</div>
              </button>
            ))}
          </div>
        </section>

        {selected && (
          <section className="min-h-0 overflow-hidden border border-line bg-white">
            <div className="border-b border-line px-4 py-3">
              <div className="text-base font-extrabold text-ink">{selected.name} · {selected.title}</div>
              <div className="mt-1 text-xs font-bold text-muted">账号：{selected.user?.phone || '-'} · 通行证：{selected.passportNo}</div>
            </div>
            <div className="grid h-[calc(100%-65px)] gap-4 overflow-y-auto p-4 xl:grid-cols-[1fr_300px]">
              <div className="space-y-4">
                <div>
                  <div className="text-xs font-extrabold text-muted">所属机构</div>
                  <div className="mt-1 font-bold text-ink">{selected.organization}</div>
                </div>
                <div>
                  <div className="text-xs font-extrabold text-muted">联系电话</div>
                  <div className="mt-1 font-bold text-ink">{selected.contactPhone}</div>
                </div>
                <div>
                  <div className="text-xs font-extrabold text-muted">专家方向</div>
                  <div className="mt-2 flex flex-wrap gap-1.5">
                    {selected.directions.map((item) => <span key={item} className="rounded-[4px] bg-bg px-2 py-1 text-xs font-bold text-muted">{item}</span>)}
                  </div>
                </div>
                <div>
                  <div className="text-xs font-extrabold text-muted">主页简介</div>
                  <p className="mt-2 whitespace-pre-wrap text-sm leading-6 text-text-body">{selected.homepageIntro || '-'}</p>
                </div>
                <div>
                  <div className="text-xs font-extrabold text-muted">项目经验</div>
                  <p className="mt-2 whitespace-pre-wrap text-sm leading-6 text-text-body">{selected.projectExperience || '-'}</p>
                </div>
                <div>
                  <div className="text-xs font-extrabold text-muted">代表成果</div>
                  <p className="mt-2 whitespace-pre-wrap text-sm leading-6 text-text-body">{selected.representativeAchievements || '-'}</p>
                </div>
                <div>
                  <div className="text-xs font-extrabold text-muted">附件材料</div>
                  <div className="mt-2 flex flex-wrap gap-2">
                    {(selected.attachments || []).length === 0 ? <span className="text-sm font-bold text-muted">暂无附件</span> : selected.attachments?.map((file) => (
                      <a key={file.id} href={assetUrl(file.url)} target="_blank" className="rounded-[4px] border border-line px-3 py-1.5 text-xs font-bold text-brand hover:border-brand">
                        {file.fileName}
                      </a>
                    ))}
                  </div>
                </div>
                {selected.status === 'rejected' && <div className="rounded-[4px] bg-bg px-4 py-3 text-sm font-bold text-[#b45309]">驳回原因：{selected.rejectReason}</div>}
              </div>

              <aside className="h-fit rounded-[4px] border border-line p-3">
                <div className="text-sm font-extrabold text-ink">审核处理</div>
                <div className="mt-3 grid gap-2">
                  <label className="grid gap-2">
                    <span className="text-[11px] font-extrabold text-muted">咨询价格（元/小时）</span>
                    <input value={review.price} onChange={(event) => setReview((current) => ({ ...current, price: event.target.value }))} type="number" min="0" className="h-8 rounded-[4px] border border-line px-2 text-xs outline-none focus:border-brand" />
                  </label>
                  <label className="grid gap-2">
                    <span className="text-[11px] font-extrabold text-muted">专家分成比例</span>
                    <input value={review.shareRatio} onChange={(event) => setReview((current) => ({ ...current, shareRatio: event.target.value }))} type="number" min="0" max="100" className="h-8 rounded-[4px] border border-line px-2 text-xs outline-none focus:border-brand" />
                  </label>
                  <label className="flex items-center gap-2 text-xs font-bold text-muted">
                    <input type="checkbox" checked={review.publish} onChange={(event) => setReview((current) => ({ ...current, publish: event.target.checked }))} className="accent-brand" />
                    通过后立即发布
                  </label>
                  <button disabled={selected.status !== 'pending'} onClick={() => void approve(selected)} className="h-8 rounded-[4px] bg-brand px-4 text-xs font-extrabold text-white disabled:cursor-not-allowed disabled:bg-line-dark">通过审核</button>
                  <textarea value={review.rejectReason} onChange={(event) => setReview((current) => ({ ...current, rejectReason: event.target.value }))} rows={3} placeholder="未通过原因" className="rounded-[4px] border border-line p-2 text-xs outline-none focus:border-brand" />
                  <button disabled={selected.status !== 'pending'} onClick={() => void reject(selected)} 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:text-soft">驳回申请</button>
                </div>
              </aside>
            </div>
          </section>
        )}
      </div>
    </AdminShell>
  )
}

export default function AdminExpertApplicationsPage() {
  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>}>
      <AdminExpertApplicationsContent />
    </Suspense>
  )
}
