'use client'

import { useEffect, useMemo, useState } from 'react'
import { AdminMetricPanel } from '@/components/admin/AdminMetrics'
import { AdminShell, hasAdminPermission } from '@/components/admin/AdminShell'
import { backend, type BackendConsultingRequest, type BackendConsultingRequestList, type StaffAccount, yuan } from '@/lib/backend'

const statusLabels: Record<BackendConsultingRequest['status'], string> = {
  pending: '待受理',
  assigned: '已指派',
  communicating: '沟通中',
  planning: '规划中',
  proposal_ready: '方案待确认',
  pending_payment: '待付款',
  in_service: '服务中',
  completed: '已完成',
  cancelled: '已取消',
}

const emptyList: BackendConsultingRequestList = {
  items: [],
  summary: {
    total: 0,
    pending: 0,
    assigned: 0,
    communicating: 0,
    planning: 0,
    proposalReady: 0,
    pendingPayment: 0,
    inService: 0,
    completed: 0,
    cancelled: 0,
  },
  page: 1,
  pageSize: 20,
  total: 0,
}

function formatDate(value?: string | null) {
  if (!value) return '-'
  return new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
}

export default function AdminConsultingRequestsPage() {
  const [account, setAccount] = useState<StaffAccount | null>(null)
  const [data, setData] = useState<BackendConsultingRequestList>(emptyList)
  const [status, setStatus] = useState('')
  const [keyword, setKeyword] = useState('')
  const [selectedId, setSelectedId] = useState(() => {
    if (typeof window === 'undefined') return ''
    return new URLSearchParams(window.location.search).get('selected') || ''
  })
  const [detail, setDetail] = useState<BackendConsultingRequest | null>(null)
  const [form, setForm] = useState({
    quotedTitle: '',
    quotedAmount: '',
    originalQuotedAmount: '',
    membershipDiscountAmount: '',
    membershipDiscountNote: '',
    quotedNote: '',
    progressNote: '',
    solutionSummary: '',
    finalSummary: '',
    internalNote: '',
  })
  const [error, setError] = useState('')
  const [saving, setSaving] = useState(false)
  const canWriteConsulting = hasAdminPermission(account, 'consulting:update')

  async function load() {
    try {
      const [currentAccount, result] = await Promise.all([
        account ? Promise.resolve(account) : backend.staffMe(),
        backend.adminConsultingRequests({ status, keyword, pageSize: 30 }),
      ])
      setAccount(currentAccount)
      setData(result)
      const nextId = result.items.find((item) => item.id === selectedId || item.requestNo === selectedId)?.id || result.items[0]?.id || ''
      setSelectedId(nextId)
      if (nextId) {
        const item = await backend.adminConsultingRequest(nextId)
        setDetail(item)
        setForm({
          quotedTitle: item.quotedTitle || item.direction || '',
          quotedAmount: item.quotedAmount ? String(yuan(item.quotedAmount)) : '',
          originalQuotedAmount: item.originalQuotedAmount ? String(yuan(item.originalQuotedAmount)) : item.quotedAmount ? String(yuan(item.quotedAmount + (item.membershipDiscountAmount || 0))) : '',
          membershipDiscountAmount: item.membershipDiscountAmount ? String(yuan(item.membershipDiscountAmount)) : '',
          membershipDiscountNote: item.membershipDiscountNote || '',
          quotedNote: item.quotedNote || '',
          progressNote: item.progressNote || '',
          solutionSummary: item.solutionSummary || '',
          finalSummary: item.finalSummary || '',
          internalNote: item.internalNote || '',
        })
      } else {
        setDetail(null)
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '咨询需求加载失败')
    }
  }

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

  async function openDetail(id: string) {
    setSelectedId(id)
    setError('')
    try {
      const item = await backend.adminConsultingRequest(id)
      setDetail(item)
      setForm({
        quotedTitle: item.quotedTitle || item.direction || '',
        quotedAmount: item.quotedAmount ? String(yuan(item.quotedAmount)) : '',
        originalQuotedAmount: item.originalQuotedAmount ? String(yuan(item.originalQuotedAmount)) : item.quotedAmount ? String(yuan(item.quotedAmount + (item.membershipDiscountAmount || 0))) : '',
        membershipDiscountAmount: item.membershipDiscountAmount ? String(yuan(item.membershipDiscountAmount)) : '',
        membershipDiscountNote: item.membershipDiscountNote || '',
        quotedNote: item.quotedNote || '',
        progressNote: item.progressNote || '',
        solutionSummary: item.solutionSummary || '',
        finalSummary: item.finalSummary || '',
        internalNote: item.internalNote || '',
      })
    } catch (err) {
      setError(err instanceof Error ? err.message : '咨询详情加载失败')
    }
  }

  async function update(payload: Record<string, unknown>) {
    if (!detail) return
    if (!canWriteConsulting) {
      setError('当前账号没有咨询需求处理权限')
      return
    }
    setSaving(true)
    setError('')
    try {
      const updated = await backend.updateAdminConsultingRequest(detail.id, payload)
      setDetail(updated)
      await load()
    } catch (err) {
      setError(err instanceof Error ? err.message : '操作失败')
    } finally {
      setSaving(false)
    }
  }

  const summaryCards = useMemo(() => [
    ['待受理', data.summary.pending],
    ['沟通中', data.summary.communicating],
    ['待付款', data.summary.pendingPayment],
    ['服务中', data.summary.inService],
    ['已完成', data.summary.completed],
  ], [data.summary])
  const canAccept = canWriteConsulting && detail?.status === 'pending'
  const canCommunicate = canWriteConsulting && detail?.status === 'assigned'
  const canPlan = canWriteConsulting && detail?.status === 'communicating'
  const canQuote = canWriteConsulting && detail?.status === 'planning'
  const canSaveQuote = canWriteConsulting && detail ? ['proposal_ready', 'pending_payment'].includes(detail.status) : false
  const canEnterService = canWriteConsulting && detail ? ['proposal_ready', 'pending_payment'].includes(detail.status) && Boolean(detail.paidAt) : false
  const canComplete = canWriteConsulting && detail?.status === 'in_service'
  const canCancel = canWriteConsulting && detail ? ['pending', 'assigned', 'communicating', 'planning', 'proposal_ready', 'pending_payment'].includes(detail.status) && !detail.paidAt : false
  const readonly = detail ? ['completed', 'cancelled'].includes(detail.status) : true

  return (
    <AdminShell title="咨询需求" description="规划咨询从申请、接单、报价、付款、服务到最终反馈的后台闭环。">
      <div className="flex h-[calc(100vh-88px)] flex-col gap-2 overflow-hidden">
        {error && <div className="shrink-0 border border-red-100 bg-red-50 px-3 py-2 text-xs font-bold text-red-700">{error}</div>}
        <AdminMetricPanel items={summaryCards.map(([label, value]) => ({ label: String(label), value }))} />

        <div className="grid min-h-0 flex-1 gap-2 xl:grid-cols-[380px_minmax(0,1fr)]">
          <section className="flex min-h-0 flex-col border border-line bg-white">
            <div className="grid shrink-0 gap-2 border-b border-line px-3 py-2 md:grid-cols-[1fr_126px_auto]">
              <input value={keyword} onChange={(event) => setKeyword(event.target.value)} placeholder="搜索编号、公司、联系人、方向" className="h-8 rounded-[4px] border border-line px-2.5 text-xs font-bold" />
              <select value={status} onChange={(event) => setStatus(event.target.value)} className="h-8 rounded-[4px] border border-line px-2 text-xs font-bold">
                <option value="">全部状态</option>
                {Object.entries(statusLabels).map(([value, label]) => <option key={value} value={value}>{label}</option>)}
              </select>
              <button type="button" onClick={() => load()} className="h-8 rounded-[4px] bg-brand px-3 text-xs font-extrabold text-white">筛选</button>
            </div>
            <div className="min-h-0 flex-1 divide-y divide-line overflow-auto">
              {data.items.map((item) => (
                <button key={item.id} type="button" onClick={() => openDetail(item.id)} className={`block w-full px-3 py-2 text-left hover:bg-brand-light/40 ${selectedId === item.id ? 'bg-brand-light/60' : ''}`}>
                  <div className="flex items-center justify-between gap-3">
                    <span className="text-xs font-extrabold text-ink">{item.requestNo}</span>
                    <span className="rounded-[3px] bg-bg px-2 py-0.5 text-[11px] font-bold text-brand">{statusLabels[item.status]}</span>
                  </div>
                  <div className="mt-1 truncate text-xs font-bold text-ink">{item.company || item.contactName}</div>
                  <div className="mt-0.5 truncate text-[11px] text-muted">{item.direction} · {item.contactName} · {item.contactPhone}</div>
                  <div className="mt-1 flex items-center justify-between gap-2 text-[11px] font-bold text-soft">
                    <span>{item.assigneeName || item.owner || '未指派'}</span>
                    <span>{formatDate(item.updatedAt || item.createdAt)}</span>
                  </div>
                </button>
              ))}
              {data.items.length === 0 && <div className="px-4 py-10 text-center text-sm font-bold text-soft">暂无咨询需求</div>}
            </div>
          </section>

          <section className="flex min-h-0 flex-col border border-line bg-white">
            {!detail ? (
              <div className="grid min-h-0 flex-1 place-items-center text-sm font-bold text-soft">选择左侧需求查看详情</div>
            ) : (
              <div className="min-h-0 flex-1 overflow-auto p-3">
                <div className="flex flex-wrap items-start justify-between gap-3 border-b border-line pb-3">
                  <div>
                    <div className="text-lg font-extrabold text-ink">{detail.requestNo} · {detail.direction}</div>
                    <div className="mt-1 text-xs font-bold text-muted">{detail.company} · {detail.contactName} · {detail.contactPhone}</div>
                  </div>
                  <div className="rounded-[4px] bg-brand-light px-2.5 py-1 text-xs font-extrabold text-brand">{statusLabels[detail.status]}</div>
                </div>

                <div className="mt-3 grid gap-2 md:grid-cols-4">
                  <Info label="组织类型" value={detail.organizationType} />
                  <Info label="所属行业" value={detail.industry} />
                  <Info label="城市" value={detail.city} />
                  <Info label="项目阶段" value={detail.projectStage} />
                  <Info label="紧急度" value={detail.urgency} />
                  <Info label="预算范围" value={detail.budgetRange} />
                  <Info label="负责人" value={detail.assigneeName || detail.owner || '未指派'} />
                  <Info label="期望启动" value={detail.expectedStart} />
                  <Info label="偏好联系" value={detail.preferredContactTime} />
                  <Info label="邮箱" value={detail.email} />
                  <Info label="订单" value={detail.orderId || '未成单'} />
                  <Info label="付款时间" value={formatDate(detail.paidAt)} />
                  <Info label="提交时间" value={formatDate(detail.createdAt)} />
                  <Info label="受理时间" value={formatDate(detail.acceptedAt)} />
                  <Info label="报价时间" value={formatDate(detail.quotedAt)} />
                  <Info label="完成时间" value={formatDate(detail.completedAt)} />
                  <Info label="会员优惠" value={detail.membershipDiscountAmount ? `-${yuan(detail.membershipDiscountAmount)} · ${detail.membershipLevelSnapshot || '未快照'}` : '-'} />
                </div>
                <div className="mt-3 space-y-3">
                <LongInfo label="当前现状" value={detail.currentSituation} />
                <LongInfo label="需求问题" value={detail.requirement} />
                <LongInfo label="期望成果" value={detail.goals} />
                </div>

                <div className="mt-3 flex flex-wrap gap-2 border-y border-line py-2">
                  {!canWriteConsulting && <div className="rounded-[4px] bg-bg px-3 py-1.5 text-xs font-bold leading-5 text-muted">当前账号仅可查看咨询需求，不能接单、报价、推进或取消。</div>}
                  {canAccept && <button disabled={saving} type="button" onClick={() => update({ accept: true, status: 'assigned' })} className="h-8 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white hover:bg-brand">接单</button>}
                  {canCommunicate && <button disabled={saving} type="button" onClick={() => update({ status: 'communicating', progressNote: form.progressNote })} className="h-8 rounded-[4px] border border-line px-3 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">进入沟通</button>}
                  {canPlan && <button disabled={saving} type="button" onClick={() => update({ status: 'planning', progressNote: form.progressNote, solutionSummary: form.solutionSummary })} className="h-8 rounded-[4px] border border-line px-3 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">进入规划</button>}
                  {canSaveQuote && <div className="rounded-[4px] bg-amber-50 px-3 py-1.5 text-xs font-bold leading-5 text-amber-700">等待用户确认并付款，付款成功后进入服务执行。</div>}
                  {readonly && <div className="rounded-[4px] bg-bg px-3 py-1.5 text-xs font-bold leading-5 text-muted">当前单据已归档，只读查看。</div>}
                </div>

                <div className="mt-3 grid gap-3 md:grid-cols-2">
                  <label className="block">
                    <span className="mb-1 block text-xs font-bold text-ink">报价标题</span>
                    <input value={form.quotedTitle} onChange={(event) => setForm((current) => ({ ...current, quotedTitle: event.target.value }))} className="h-8 w-full rounded-[4px] border border-line px-2.5 text-xs font-bold" />
                  </label>
                  <label className="block">
                    <span className="mb-1 block text-xs font-bold text-ink">最终应付（元）</span>
                    <input value={form.quotedAmount} onChange={(event) => setForm((current) => ({ ...current, quotedAmount: event.target.value }))} className="h-8 w-full rounded-[4px] border border-line px-2.5 text-xs font-bold" />
                  </label>
                  <label className="block">
                    <span className="mb-1 block text-xs font-bold text-ink">原始报价（元）</span>
                    <input value={form.originalQuotedAmount} onChange={(event) => {
                      const originalQuotedAmount = event.target.value
                      const quotedAmount = Math.max(Number(originalQuotedAmount || 0) - Number(form.membershipDiscountAmount || 0), 0)
                      setForm((current) => ({ ...current, originalQuotedAmount, quotedAmount: quotedAmount ? String(quotedAmount) : '' }))
                    }} className="h-8 w-full rounded-[4px] border border-line px-2.5 text-xs font-bold" />
                  </label>
                  <label className="block">
                    <span className="mb-1 block text-xs font-bold text-ink">会员优惠（元）</span>
                    <input value={form.membershipDiscountAmount} onChange={(event) => {
                      const membershipDiscountAmount = event.target.value
                      const quotedAmount = Math.max(Number(form.originalQuotedAmount || form.quotedAmount || 0) - Number(membershipDiscountAmount || 0), 0)
                      setForm((current) => ({ ...current, membershipDiscountAmount, quotedAmount: quotedAmount ? String(quotedAmount) : '' }))
                    }} className="h-8 w-full rounded-[4px] border border-line px-2.5 text-xs font-bold" />
                  </label>
                  <label className="block md:col-span-2">
                    <span className="mb-1 block text-xs font-bold text-ink">会员优惠说明</span>
                    <input value={form.membershipDiscountNote} onChange={(event) => setForm((current) => ({ ...current, membershipDiscountNote: event.target.value }))} className="h-8 w-full rounded-[4px] border border-line px-2.5 text-xs font-bold" />
                  </label>
                  <label className="block md:col-span-2">
                    <span className="mb-1 block text-xs font-bold text-ink">报价说明</span>
                    <textarea value={form.quotedNote} onChange={(event) => setForm((current) => ({ ...current, quotedNote: event.target.value }))} rows={2} className="w-full rounded-[4px] border border-line px-2.5 py-2 text-xs font-bold" />
                  </label>
                  {(canQuote || canSaveQuote) && <button disabled={saving} type="button" onClick={() => update({ chargeRequired: true, quotedTitle: form.quotedTitle, originalQuotedAmount: Math.round(Number(form.originalQuotedAmount || form.quotedAmount || 0) * 100), membershipDiscountAmount: Math.round(Number(form.membershipDiscountAmount || 0) * 100), membershipDiscountNote: form.membershipDiscountNote, quotedAmount: Math.round(Number(form.quotedAmount || 0) * 100), quotedNote: form.quotedNote, status: canQuote ? 'proposal_ready' : detail?.status })} className="h-9 rounded-[4px] bg-brand px-4 text-xs font-extrabold text-white disabled:bg-line-dark">{canQuote ? '发送报价' : '保存报价'}</button>}
                </div>

                <div className="mt-3 grid gap-3">
                  <label className="block">
                    <span className="mb-1 block text-xs font-bold text-ink">进度备注</span>
                    <textarea value={form.progressNote} onChange={(event) => setForm((current) => ({ ...current, progressNote: event.target.value }))} rows={2} className="w-full rounded-[4px] border border-line px-2.5 py-2 text-xs font-bold" />
                  </label>
                  <label className="block">
                    <span className="mb-1 block text-xs font-bold text-ink">方案摘要</span>
                    <textarea value={form.solutionSummary} onChange={(event) => setForm((current) => ({ ...current, solutionSummary: event.target.value }))} rows={2} className="w-full rounded-[4px] border border-line px-2.5 py-2 text-xs font-bold" />
                  </label>
                  <label className="block">
                    <span className="mb-1 block text-xs font-bold text-ink">最终反馈</span>
                    <textarea value={form.finalSummary} onChange={(event) => setForm((current) => ({ ...current, finalSummary: event.target.value }))} rows={2} className="w-full rounded-[4px] border border-line px-2.5 py-2 text-xs font-bold" />
                  </label>
                </div>

                <div className="mt-3 flex flex-wrap gap-2 border-t border-line pt-3">
                  {canEnterService && <button disabled={saving} type="button" onClick={() => update({ status: 'in_service', progressNote: form.progressNote, solutionSummary: form.solutionSummary })} className="h-9 rounded-[4px] border border-line px-4 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">进入服务</button>}
                  {canComplete && <button disabled={saving} type="button" onClick={() => {
                    if (!window.confirm('确认完成该咨询服务？')) return
                    void update({ status: 'completed', finalSummary: form.finalSummary })
                  }} className="h-9 rounded-[4px] bg-brand px-4 text-xs font-extrabold text-white disabled:bg-line-dark">完成咨询</button>}
                  {canQuote && <button disabled={saving} type="button" onClick={() => update({ status: 'completed', chargeRequired: false, solutionSummary: form.solutionSummary, finalSummary: form.finalSummary })} className="h-9 rounded-[4px] border border-line px-4 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">免费完成</button>}
                  {canCancel && <button disabled={saving} type="button" onClick={() => {
                    if (!window.confirm('确认取消这条未付款咨询需求？')) return
                    void backend.cancelAdminConsultingRequest(detail.id, { reason: form.internalNote || '后台取消' }).then((item) => { setDetail(item); void load() }).catch((err) => setError(err instanceof Error ? err.message : '取消失败'))
                  }} className="h-9 rounded-[4px] border border-red-100 px-4 text-xs font-extrabold text-red-600">未付款取消</button>}
                </div>
              </div>
            )}
          </section>
        </div>
      </div>
    </AdminShell>
  )
}

function Info({ label, value }: { label: string; value?: string | number | null }) {
  return (
    <div className="border border-line bg-bg/40 px-2.5 py-1.5">
      <div className="text-[11px] font-bold text-soft">{label}</div>
      <div className="mt-0.5 break-words text-xs font-extrabold text-ink">{value || '-'}</div>
    </div>
  )
}

function LongInfo({ label, value }: { label: string; value?: string }) {
  return (
    <div>
      <div className="mb-1 text-xs font-extrabold text-ink">{label}</div>
      <div className="rounded-[4px] border border-line bg-bg/40 px-2.5 py-2 text-xs font-bold leading-6 text-muted">{value || '-'}</div>
    </div>
  )
}
