'use client'

import { useEffect, useMemo, useState } from 'react'
import { useSearchParams } from 'next/navigation'
import type { ReactNode } from 'react'
import { Database, RefreshCw, Search, Upload } from 'lucide-react'
import { AdminMetricPanel } from '@/components/admin/AdminMetrics'
import { AdminShell, hasAdminPermission } from '@/components/admin/AdminShell'
import { backend, type BackendDataServiceRequest, type BackendDataServiceRequestList, type StaffAccount, yuan } from '@/lib/backend'

const statusOptions = [
  { value: '', label: '全部状态' },
  { value: 'pending_contact', label: '待联系' },
  { value: 'contacting', label: '沟通中' },
  { value: 'quoted', label: '已报价' },
  { value: 'pending_payment', label: '待付款' },
  { value: 'in_service', label: '服务中' },
  { value: 'completed', label: '已完成' },
  { value: 'cancelled', label: '已取消' },
]

const statusLabel: Record<string, string> = {
  pending_contact: '待联系',
  contacting: '沟通中',
  quoted: '已报价',
  pending_payment: '待付款',
  in_service: '服务中',
  completed: '已完成',
  cancelled: '已取消',
}

function statusTone(status: string) {
  if (status === 'completed') return 'bg-emerald-50 text-emerald-700'
  if (status === 'cancelled') return 'bg-slate-100 text-slate-600'
  if (status === 'pending_contact') return 'bg-amber-50 text-amber-700'
  if (status === 'in_service') return 'bg-brand-light text-brand'
  return 'bg-blue-50 text-blue-700'
}

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

function blankList(): BackendDataServiceRequestList {
  return {
    items: [],
    summary: { total: 0, pendingContact: 0, contacting: 0, quoted: 0, pendingPayment: 0, inService: 0, completed: 0, cancelled: 0 },
    page: 1,
    pageSize: 50,
    total: 0,
  }
}

export default function AdminDataServicePage() {
  const searchParams = useSearchParams()
  const [account, setAccount] = useState<StaffAccount | null>(null)
  const [result, setResult] = useState<BackendDataServiceRequestList>(blankList)
  const [status, setStatus] = useState('')
  const [keyword, setKeyword] = useState('')
  const [scope, setScope] = useState('all')
  const [selectedId, setSelectedId] = useState('')
  const [loading, setLoading] = useState(false)
  const [saving, setSaving] = useState(false)
  const [uploading, setUploading] = useState('')
  const [error, setError] = useState('')
  const [saved, setSaved] = useState('')
  const [progressNote, setProgressNote] = useState<Record<string, string>>({})
  const [resultSummary, setResultSummary] = useState<Record<string, string>>({})
  const [quoteForms, setQuoteForms] = useState<Record<string, { title: string; amount: string; originalAmount: string; membershipDiscountAmount: string; membershipDiscountNote: string; note: string }>>({})
  const [deliverables, setDeliverables] = useState<Record<string, Array<{ id: string; name: string }>>>({})

  const selected = useMemo(() => result.items.find((item) => item.id === selectedId) || result.items[0] || null, [result.items, selectedId])
  const quote = selected ? quoteForms[selected.id] || {
    title: selected.quotedTitle || `${selected.dataTopic || '数据服务'}报价`,
    amount: selected.quotedAmount ? String(selected.quotedAmount / 100) : '',
    originalAmount: selected.originalQuotedAmount ? String(selected.originalQuotedAmount / 100) : selected.quotedAmount ? String((selected.quotedAmount + (selected.membershipDiscountAmount || 0)) / 100) : '',
    membershipDiscountAmount: selected.membershipDiscountAmount ? String(selected.membershipDiscountAmount / 100) : '',
    membershipDiscountNote: selected.membershipDiscountNote || '',
    note: selected.quotedNote || '',
  } : { title: '', amount: '', originalAmount: '', membershipDiscountAmount: '', membershipDiscountNote: '', note: '' }
  const note = selected ? progressNote[selected.id] ?? selected.progressNote ?? '' : ''
  const finalResult = selected ? resultSummary[selected.id] ?? selected.resultSummary ?? '' : ''
  const currentDeliverables = selected ? deliverables[selected.id] || [] : []
  const canWriteDataService = hasAdminPermission(account, 'data_service:update')

  async function reload(nextSelectedId = selectedId) {
    setLoading(true)
    try {
      const [currentAccount, data] = await Promise.all([
        account ? Promise.resolve(account) : backend.staffMe(),
        backend.adminDataServiceRequests({ status, keyword, scope, pageSize: 50 }),
      ])
      setAccount(currentAccount)
      setResult(data)
      const selectedParam = searchParams.get('selected') || ''
      const next = nextSelectedId || data.items.find((item) => item.id === selectedParam || item.requestNo === selectedParam)?.id || data.items[0]?.id || ''
      setSelectedId(data.items.some((item) => item.id === next) ? next : data.items[0]?.id || '')
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '数据服务需求加载失败')
    } finally {
      setLoading(false)
    }
  }

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

  function selectRequest(item: BackendDataServiceRequest) {
    setSelectedId(item.id)
    setQuoteForms((current) => ({
      ...current,
      [item.id]: current[item.id] || {
        title: item.quotedTitle || `${item.dataTopic || '定制数据'}报价`,
        amount: item.quotedAmount ? String(item.quotedAmount / 100) : '',
        originalAmount: item.originalQuotedAmount ? String(item.originalQuotedAmount / 100) : item.quotedAmount ? String((item.quotedAmount + (item.membershipDiscountAmount || 0)) / 100) : '',
        membershipDiscountAmount: item.membershipDiscountAmount ? String(item.membershipDiscountAmount / 100) : '',
        membershipDiscountNote: item.membershipDiscountNote || '',
        note: item.quotedNote || '',
      },
    }))
  }

  async function updateSelected(payload: Record<string, unknown>, successText: string) {
    if (!selected) return
    if (!canWriteDataService) {
      setError('当前账号没有数据服务处理权限')
      return
    }
    setSaving(true)
    setSaved('')
    setError('')
    try {
      const updated = await backend.updateAdminDataServiceRequest(selected.id, payload)
      setSaved(successText)
      await reload(updated.id)
    } catch (err) {
      setError(err instanceof Error ? err.message : '保存失败')
    } finally {
      setSaving(false)
    }
  }

  async function cancelSelected() {
    if (!selected) return
    if (!canWriteDataService) {
      setError('当前账号没有数据服务处理权限')
      return
    }
    if (!window.confirm('确认取消这条未付款数据服务需求？')) return
    setSaving(true)
    setSaved('')
    setError('')
    try {
      const updated = await backend.cancelAdminDataServiceRequest(selected.id, { progressNote: note })
      setSaved('需求已取消')
      await reload(updated.id)
    } catch (err) {
      setError(err instanceof Error ? err.message : '取消失败')
    } finally {
      setSaving(false)
    }
  }

  async function uploadFiles(files: FileList | null) {
    if (!selected || !files?.length) return
    if (!canWriteDataService) {
      setError('当前账号没有数据服务处理权限')
      return
    }
    setError('')
    for (const file of Array.from(files)) {
      setUploading(file.name)
      try {
        const uploaded = await backend.uploadStaffFile(file)
        setDeliverables((current) => ({
          ...current,
          [selected.id]: [...(current[selected.id] || []), { id: uploaded.id, name: uploaded.fileName }],
        }))
      } catch (err) {
        setError(err instanceof Error ? err.message : '上传失败')
      } finally {
        setUploading('')
      }
    }
  }

  const summaryTiles = [
    ['待联系', result.summary.pendingContact],
    ['沟通中', result.summary.contacting],
    ['待付款', result.summary.pendingPayment],
    ['服务中', result.summary.inService],
    ['已完成', result.summary.completed],
  ]
  const canAccept = canWriteDataService && selected?.status === 'pending_contact'
  const canQuote = canWriteDataService && selected?.status === 'contacting'
  const canEnterService = canWriteDataService && selected?.status === 'pending_payment' && Boolean(selected.paidAt)
  const canComplete = canWriteDataService && selected?.status === 'in_service'
  const canCancel = canWriteDataService && selected ? ['pending_contact', 'contacting', 'quoted', 'pending_payment'].includes(selected.status) && !selected.paidAt : false
  const readonly = selected ? ['completed', 'cancelled'].includes(selected.status) : true

  return (
    <AdminShell title="数据服务需求" description="受理用户数据定制需求，完成联系、报价、付款后服务推进和交付。">
      <div className="flex h-[calc(100vh-88px)] flex-col gap-2 overflow-hidden">
        {(error || saved) && (
          <div className={`shrink-0 rounded-[4px] px-3 py-2 text-xs font-bold ${error ? 'bg-red-50 text-red-700' : 'bg-emerald-50 text-emerald-700'}`}>
            {error || saved}
          </div>
        )}

        <AdminMetricPanel items={summaryTiles.map(([label, value]) => ({ label: String(label), value }))} />

        <section className="grid shrink-0 gap-2 border border-line bg-white p-2 lg:grid-cols-[150px_150px_minmax(0,1fr)_auto]">
          <select value={status} onChange={(event) => setStatus(event.target.value)} className="h-8 border border-line px-2 text-xs font-bold outline-none focus:border-brand">
            {statusOptions.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}
          </select>
          <select value={scope} onChange={(event) => setScope(event.target.value)} className="h-8 border border-line px-2 text-xs font-bold outline-none focus:border-brand">
            <option value="all">全部需求</option>
            <option value="mine">我负责的</option>
          </select>
          <div className="flex h-8 min-w-0 items-center border border-line px-2.5 focus-within:border-brand">
            <Search className="h-3.5 w-3.5 shrink-0 text-soft" />
            <input value={keyword} onChange={(event) => setKeyword(event.target.value)} onKeyDown={(event) => { if (event.key === 'Enter') void reload('') }} placeholder="搜索编号、单位、联系人、主题" className="min-w-0 flex-1 px-2 text-xs font-bold outline-none" />
          </div>
          <button type="button" onClick={() => void reload('')} disabled={loading} className="inline-flex h-8 items-center justify-center gap-1.5 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white hover:bg-brand disabled:bg-line-dark">
            <RefreshCw className="h-3.5 w-3.5" />
            {loading ? '刷新中' : '刷新'}
          </button>
        </section>

        <div className="grid min-h-0 flex-1 gap-2 xl:grid-cols-[360px_minmax(0,1fr)]">
        <aside className="flex min-h-0 flex-col border border-line bg-white">
          <div className="shrink-0 border-b border-line px-3 py-2 text-xs font-extrabold text-ink">需求队列 · {result.total}</div>
          <div className="min-h-0 flex-1 overflow-auto">
          {result.items.map((item) => (
            <button key={item.id} type="button" onClick={() => selectRequest(item)} className={`block w-full border-b border-line px-3 py-2 text-left hover:bg-bg ${selected?.id === item.id ? 'bg-bg' : ''}`}>
              <div className="flex items-start justify-between gap-3">
                <div className="min-w-0">
                  <div className="truncate text-xs font-extrabold text-ink">{item.dataTopic || item.quotedTitle || '数据服务需求'}</div>
                  <div className="mt-0.5 truncate text-[11px] font-bold text-muted">{item.requestNo} · {item.company}</div>
                </div>
                <span className={`shrink-0 px-2 py-1 text-[11px] font-extrabold ${statusTone(item.status)}`}>{statusLabel[item.status] || item.status}</span>
              </div>
              <div className="mt-1 grid grid-cols-2 gap-2 text-[11px] font-bold text-soft">
                <span>{item.contactName} / {item.contactPhone}</span>
                <span className="text-right">{item.assigneeName || '未接单'}</span>
              </div>
              <div className="mt-1 flex items-center justify-between gap-2 text-[11px] font-bold text-soft">
                <span>{item.budgetRange || item.serviceType || '-'}</span>
                <span>{formatDate(item.updatedAt || item.createdAt)}</span>
              </div>
            </button>
          ))}
          {!result.items.length && <div className="px-4 py-10 text-center text-sm font-bold text-muted">暂无数据服务需求</div>}
          </div>
        </aside>

        <section className="flex min-h-0 flex-col border border-line bg-white">
          {!selected ? (
            <div className="grid min-h-0 flex-1 place-items-center text-sm font-bold text-muted">
              <div className="text-center">
                <Database className="mx-auto mb-3 h-8 w-8 text-soft" />
                请选择一个数据服务需求
              </div>
            </div>
          ) : (
            <div className="min-h-0 flex-1 overflow-auto">
              <div className="border-b border-line px-3 py-3">
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div className="min-w-0">
                    <div className="text-xs font-bold text-muted">{selected.requestNo} · {selected.company}</div>
                    <h2 className="mt-1 break-words text-lg font-extrabold text-ink">{selected.dataTopic || selected.quotedTitle || '数据服务'}</h2>
                  </div>
                  <span className={`px-2.5 py-1 text-xs font-extrabold ${statusTone(selected.status)}`}>{statusLabel[selected.status] || selected.status}</span>
                </div>
              </div>

              <div className="grid gap-3 p-3 2xl:grid-cols-[minmax(0,1fr)_260px]">
                <div className="min-w-0">
                  <div className="grid gap-2 md:grid-cols-4">
                    <Info label="联系人" value={`${selected.contactName} / ${selected.contactPhone}`} />
                    <Info label="邮箱" value={selected.email} />
                    <Info label="城市" value={selected.city} />
                    <Info label="服务类型" value={selected.serviceType || '-'} />
                    <Info label="负责人" value={selected.assigneeName || '未接单'} />
                    <Info label="范围/时间" value={`${selected.regionScope || '-'} / ${selected.timeRange || '-'}`} />
                    <Info label="行业场景" value={selected.industryScene || '-'} />
                    <Info label="期望格式" value={selected.expectedFormat || '-'} />
                    <Info label="数据量" value={selected.dataVolume || '-'} />
                    <Info label="预算" value={selected.budgetRange || '-'} />
                    <Info label="创建时间" value={formatDate(selected.createdAt)} />
                    <Info label="期望期限" value={selected.deadline || '-'} />
                    <Info label="偏好联系" value={selected.preferredContactTime || '-'} />
                    <Info label="敏感数据" value={selected.sensitiveData ? '涉及' : '不涉及/未填'} />
                    <Info label="报价金额" value={selected.quotedAmount ? yuan(selected.quotedAmount) : '-'} />
                    <Info label="会员优惠" value={selected.membershipDiscountAmount ? `-${yuan(selected.membershipDiscountAmount)} · ${selected.membershipLevelSnapshot || '未快照'}` : '-'} />
                    <Info label="订单" value={selected.orderNo || '未成单'} />
                    <Info label="付款时间" value={formatDate(selected.paidAt)} />
                    <Info label="完成时间" value={formatDate(selected.completedAt)} />
                  </div>

                  <LongText title="需求描述" value={selected.requirement} />
                  <LongText title="期望成果" value={selected.expectedResult} />
                  <LongText title="用途/场景" value={selected.usagePurpose || selected.industryScene} />
                  <LongText title="补充说明" value={selected.extraNote} />

                  <div className="mt-3 border border-line p-3">
                    <div className="text-xs font-extrabold text-ink">报价</div>
                    <div className="mt-2 grid gap-2 md:grid-cols-[1fr_130px_130px_130px]">
                      <input value={quote.title} onChange={(event) => setQuoteForms((current) => ({ ...current, [selected.id]: { ...quote, title: event.target.value } }))} placeholder="报价标题" className="h-8 border border-line px-2.5 text-xs font-bold outline-none focus:border-brand" />
                      <input value={quote.originalAmount} onChange={(event) => {
                        const originalAmount = event.target.value
                        const nextFinal = Math.max(Number(originalAmount || 0) - Number(quote.membershipDiscountAmount || 0), 0)
                        setQuoteForms((current) => ({ ...current, [selected.id]: { ...quote, originalAmount, amount: nextFinal ? String(nextFinal) : '' } }))
                      }} type="number" min="0" placeholder="原始报价（元）" className="h-8 border border-line px-2.5 text-xs font-bold outline-none focus:border-brand" />
                      <input value={quote.membershipDiscountAmount} onChange={(event) => {
                        const membershipDiscountAmount = event.target.value
                        const nextFinal = Math.max(Number(quote.originalAmount || quote.amount || 0) - Number(membershipDiscountAmount || 0), 0)
                        setQuoteForms((current) => ({ ...current, [selected.id]: { ...quote, membershipDiscountAmount, amount: nextFinal ? String(nextFinal) : '' } }))
                      }} type="number" min="0" placeholder="会员优惠（元）" className="h-8 border border-line px-2.5 text-xs font-bold outline-none focus:border-brand" />
                      <input value={quote.amount} onChange={(event) => setQuoteForms((current) => ({ ...current, [selected.id]: { ...quote, amount: event.target.value } }))} type="number" min="0" placeholder="最终应付（元）" className="h-8 border border-line px-2.5 text-xs font-bold outline-none focus:border-brand" />
                    </div>
                    <input value={quote.membershipDiscountNote} onChange={(event) => setQuoteForms((current) => ({ ...current, [selected.id]: { ...quote, membershipDiscountNote: event.target.value } }))} placeholder="会员优惠说明，如：高级会员重点客户人工优惠" className="mt-2 h-8 w-full border border-line px-2.5 text-xs font-bold outline-none focus:border-brand" />
                    <textarea value={quote.note} onChange={(event) => setQuoteForms((current) => ({ ...current, [selected.id]: { ...quote, note: event.target.value } }))} rows={2} placeholder="报价说明" className="mt-2 w-full border border-line p-2.5 text-xs font-bold outline-none focus:border-brand" />
                  </div>

                  <div className="mt-3 grid gap-3 md:grid-cols-2">
                    <label className="block">
                      <span className="mb-1 block text-xs font-extrabold text-ink">处理记录</span>
                      <textarea value={note} onChange={(event) => setProgressNote((current) => ({ ...current, [selected.id]: event.target.value }))} rows={4} className="w-full border border-line p-2.5 text-xs font-bold leading-6 outline-none focus:border-brand" />
                    </label>
                    <label className="block">
                      <span className="mb-1 block text-xs font-extrabold text-ink">交付说明</span>
                      <textarea value={finalResult} onChange={(event) => setResultSummary((current) => ({ ...current, [selected.id]: event.target.value }))} rows={4} className="w-full border border-line p-2.5 text-xs font-bold leading-6 outline-none focus:border-brand" />
                    </label>
                  </div>

                  <div className="mt-3 border border-line p-3">
                    <div className="text-xs font-extrabold text-ink">交付文件</div>
                    {canWriteDataService && (
                      <label className="mt-2 inline-flex h-8 cursor-pointer items-center gap-2 border border-line px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
                        <Upload className="h-4 w-4" />
                        {uploading ? `正在上传：${uploading}` : '上传交付文件'}
                        <input type="file" multiple className="sr-only" onChange={(event) => {
                          void uploadFiles(event.target.files)
                          event.currentTarget.value = ''
                        }} />
                      </label>
                    )}
                    <div className="mt-2 grid gap-1 text-xs font-bold text-muted">
                      {currentDeliverables.map((file) => <div key={file.id}>待提交：{file.name}</div>)}
                      {(selected.deliverableFiles || []).map((file) => <a key={file.id} href={file.url} target="_blank" rel="noreferrer" className="text-brand hover:underline">已交付：{file.fileName}</a>)}
                      {selected.deliverableFileName && !(selected.deliverableFiles || []).length && <div>已交付：{selected.deliverableFileName}</div>}
                      {selected.deliverableFileIds?.length && !(selected.deliverableFiles || []).length ? <div>已登记交付文件 {selected.deliverableFileIds.length} 个</div> : null}
                      {!currentDeliverables.length && !selected.deliverableFileName && !selected.deliverableFileIds?.length && <div>暂未上传交付文件</div>}
                    </div>
                  </div>
                </div>

                <ActionPanel title="操作">
                  {!canWriteDataService && <div className="rounded-[4px] bg-white px-3 py-2 text-xs font-bold leading-5 text-muted">当前账号仅可查看数据服务需求，不能接单、报价、交付或取消。</div>}
                  {canAccept && <button type="button" disabled={saving} onClick={() => void updateSelected({ accept: true, status: 'contacting', progressNote: note, contactNote: note }, '已接单并进入联系')} className="h-10 bg-ink text-sm font-extrabold text-white hover:bg-brand disabled:bg-line-dark">接单联系</button>}
                  {canQuote && <button type="button" disabled={saving} onClick={() => void updateSelected({ status: 'quoted', quotedTitle: quote.title, originalQuotedAmount: Math.round(Number(quote.originalAmount || quote.amount || 0) * 100), membershipDiscountAmount: Math.round(Number(quote.membershipDiscountAmount || 0) * 100), membershipDiscountNote: quote.membershipDiscountNote, quotedAmount: Math.round(Number(quote.amount || 0) * 100), quotedNote: quote.note, progressNote: note }, '报价已发送')} className="h-10 border border-line text-sm font-extrabold text-muted hover:border-brand hover:text-brand disabled:opacity-60">发送报价</button>}
                  {selected.status === 'quoted' || selected.status === 'pending_payment' ? <div className="rounded-[4px] bg-amber-50 px-3 py-2 text-xs font-bold leading-5 text-amber-700">等待用户确认并付款，付款成功后系统会进入服务中。</div> : null}
                  {canEnterService && <button type="button" disabled={saving} onClick={() => void updateSelected({ status: 'in_service', progressNote: note }, '已进入服务中')} className="h-10 border border-line text-sm font-extrabold text-muted hover:border-brand hover:text-brand disabled:opacity-60">进入服务</button>}
                  {canComplete && <button type="button" disabled={saving} onClick={() => {
                    if (!window.confirm('确认完成该数据服务交付？')) return
                    const existing = selected.deliverableFileIds?.length ? selected.deliverableFileIds : selected.deliverableFileId ? [selected.deliverableFileId] : []
                    const nextIds = [...existing, ...currentDeliverables.map((file) => file.id)]
                    void updateSelected({ status: 'completed', progressNote: note, resultSummary: finalResult, deliverableFileIds: nextIds, deliverableFileId: nextIds[0] }, '已完成交付')
                  }} className="h-10 border border-line text-sm font-extrabold text-muted hover:border-brand hover:text-brand disabled:opacity-60">完成交付</button>}
                  {canCancel && <button type="button" disabled={saving} onClick={() => void cancelSelected()} className="h-10 border border-red-100 text-sm font-extrabold text-red-700 hover:border-red-300 disabled:opacity-60">未付款取消</button>}
                  {readonly && <div className="rounded-[4px] bg-bg px-3 py-2 text-xs font-bold leading-5 text-muted">当前单据已归档，后台只读查看。</div>}
                </ActionPanel>
              </div>
            </div>
          )}
        </section>
        </div>
      </div>
    </AdminShell>
  )
}

function Info({ label, value }: { label: string; value?: string | number | null }) {
  return (
    <div className="border border-line bg-bg 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 LongText({ title, value }: { title: string; value?: string | null }) {
  if (!value) return null
  return (
    <div className="mt-3 border border-line p-3">
      <div className="text-xs font-extrabold text-ink">{title}</div>
      <p className="mt-1.5 whitespace-pre-wrap text-xs font-bold leading-6 text-muted">{value}</p>
    </div>
  )
}

function ActionPanel({ title, children }: { title: string; children: ReactNode }) {
  return (
    <aside className="border border-line bg-bg p-3">
      <div className="mb-2 text-xs font-extrabold text-ink">{title}</div>
      <div className="grid gap-2">{children}</div>
    </aside>
  )
}
