'use client'

import type { ReactNode } from 'react'
import { useEffect, useMemo, useState } from 'react'
import { BarChart3, CheckCircle2, Clock3, PlayCircle, RefreshCw } from 'lucide-react'
import { AdminShell, hasAdminPermission } from '@/components/admin/AdminShell'
import { backend, type BackendTask, type StaffAccount } from '@/lib/backend'

const statusOptions = [
  { label: '全部', value: '' },
  { label: '待资料', value: 'pending_material' },
  { label: '已接单', value: 'assigned' },
  { label: '处理中', value: 'in_progress' },
  { label: '待确认', value: 'pending_confirm' },
  { label: '已完成', value: 'completed' },
  { label: '已取消', value: 'cancelled' },
]

const statusLabel: Record<string, string> = {
  pending_material: '待资料',
  assigned: '已接单',
  in_progress: '处理中',
  pending_confirm: '待确认',
  completed: '已完成',
  cancelled: '已取消',
}

const typeLabel: Record<string, string> = {
  agent: '智能体',
  data: '历史资料',
  course: '课程',
  event: '活动',
  membership: '会员',
  expert: '专家预约',
  consulting: '规划咨询',
}

function statusTone(status: string) {
  if (status === 'completed') return 'bg-green-50 text-green'
  if (status === 'cancelled') return 'bg-bg text-soft'
  if (['in_progress', 'pending_confirm'].includes(status)) return 'bg-amber-50 text-amber-700'
  if (status === 'assigned') return 'bg-brand-light text-brand'
  return 'bg-bg text-muted'
}

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' })
}

function stringifyValue(value: unknown) {
  if (value === null || value === undefined || value === '') return ''
  if (Array.isArray(value)) return value.filter(Boolean).join('、')
  if (typeof value === 'object') return JSON.stringify(value)
  return String(value)
}

function materialEntries(payload?: Record<string, unknown>) {
  return Object.entries(payload || {})
    .filter(([key]) => !['files', 'fileIds'].includes(key))
    .map(([key, value]) => ({ key, value: stringifyValue(value) }))
    .filter((item) => item.value)
}

export default function AdminTasksPage() {
  const [account, setAccount] = useState<StaffAccount | null>(null)
  const [items, setItems] = useState<BackendTask[]>([])
  const [status, setStatus] = useState('')
  const [scope, setScope] = useState<'all' | 'mine'>('all')
  const [type, setType] = useState('')
  const [keyword, setKeyword] = useState('')
  const [selectedId, setSelectedId] = useState(() => {
    if (typeof window === 'undefined') return ''
    return new URLSearchParams(window.location.search).get('selected') || ''
  })
  const [note, setNote] = useState('')
  const [result, setResult] = useState('')
  const [loading, setLoading] = useState(false)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const canUpdateTask = hasAdminPermission(account, 'task:update')

  const typeOptions = useMemo(() => Array.from(new Set(items.map((item) => item.type).filter(Boolean))), [items])
  const visibleItems = useMemo(() => {
    const words = keyword.trim().toLowerCase()
    if (!words) return items
    return items.filter((item) => [
      item.taskNo,
      item.orderNo,
      item.userPhone,
      item.title,
      item.productTitle,
      item.assigneeName,
    ].some((value) => String(value || '').toLowerCase().includes(words)))
  }, [items, keyword])
  const selected = useMemo(() => visibleItems.find((item) => item.id === selectedId || item.taskNo === selectedId) || visibleItems[0] || null, [selectedId, visibleItems])
  const stats = useMemo(() => ({
    total: items.length,
    waiting: items.filter((item) => item.status === 'pending_material').length,
    doing: items.filter((item) => ['assigned', 'in_progress', 'pending_confirm'].includes(item.status)).length,
    completed: items.filter((item) => item.status === 'completed').length,
  }), [items])

  async function reload() {
    setLoading(true)
    setError('')
    try {
      const [currentAccount, result] = await Promise.all([
        account ? Promise.resolve(account) : backend.staffMe(),
        backend.staffTasks({
          status,
          type,
          scope: scope === 'mine' ? 'mine' : '',
        }),
      ])
      setAccount(currentAccount)
      setItems(result.items)
      setSelectedId((current) => current || result.items[0]?.taskNo || result.items[0]?.id || '')
    } catch (err) {
      setError(err instanceof Error ? err.message : '交付任务加载失败')
    } finally {
      setLoading(false)
    }
  }

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

  useEffect(() => {
    if (!selected) {
      setNote('')
      setResult('')
      return
    }
    setNote(selected.progressNote || '')
    setResult(selected.resultSummary || '')
  }, [selected])

  async function updateSelected(nextStatus: string, payload: Record<string, unknown> = {}) {
    if (!selected) return
    if (!canUpdateTask) {
      setError('当前账号没有交付任务处理权限')
      return
    }
    setSaving(true)
    setError('')
    try {
      const updated = await backend.updateStaffTask(selected.id, nextStatus, payload)
      setItems((current) => current.map((item) => item.id === updated.id ? updated : item))
      setSelectedId(updated.taskNo || updated.id)
    } catch (err) {
      setError(err instanceof Error ? err.message : '任务更新失败')
    } finally {
      setSaving(false)
    }
  }

  const materials = materialEntries(selected?.materialPayload)
  const materialFiles = [
    ...(selected?.materials || []),
    ...((selected?.materialPayload?.files as BackendTask['materials']) || []),
  ].filter((file, index, list) => Boolean(file?.id) && list.findIndex((item) => item?.id === file?.id) === index)
  const readonly = selected ? ['completed', 'cancelled'].includes(selected.status) : true

  return (
    <AdminShell
      title="交付任务"
      description="管理员查看全局交付池；员工执行仍进入员工工作台。"
      topbarMetrics={[
        { label: '任务总数', value: stats.total },
        { label: '待资料', value: stats.waiting },
        { label: '进行中', value: stats.doing },
        { label: '已完成', value: stats.completed },
      ]}
    >
      <div className="flex h-[calc(100vh-144px)] 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>}

        <section className="grid shrink-0 gap-2 border border-line bg-white p-2 lg:grid-cols-[130px_130px_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">
            {statusOptions.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}
          </select>
          <select value={scope} onChange={(event) => setScope(event.target.value as 'all' | 'mine')} className="h-8 border border-line px-2 text-xs font-bold">
            <option value="all">全部任务</option>
            <option value="mine">我负责的</option>
          </select>
          <select value={type} onChange={(event) => setType(event.target.value)} className="h-8 border border-line px-2 text-xs font-bold">
            <option value="">全部类型</option>
            {typeOptions.map((item) => <option key={item} value={item}>{typeLabel[item] || item}</option>)}
          </select>
          <input value={keyword} onChange={(event) => setKeyword(event.target.value)} placeholder="搜索任务号、订单号、用户、商品、负责人" className="h-8 border border-line px-2.5 text-xs font-bold outline-none focus:border-brand" />
          <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" />
            刷新
          </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">交付池 · {visibleItems.length}</div>
            <div className="min-h-0 flex-1 overflow-auto">
              {visibleItems.map((item) => (
                <button key={item.id} type="button" onClick={() => setSelectedId(item.taskNo || item.id)} className={`block w-full border-b border-line px-3 py-2 text-left hover:bg-bg ${selected?.id === item.id ? 'bg-brand-light/60' : ''}`}>
                  <div className="flex items-start justify-between gap-2">
                    <div className="min-w-0">
                      <div className="truncate text-sm font-extrabold text-ink">{item.taskNo || item.id}</div>
                      <div className="mt-0.5 truncate text-xs font-bold text-muted">{item.productTitle || item.title}</div>
                    </div>
                    <span className={`shrink-0 px-2 py-0.5 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>{typeLabel[item.type] || item.type} · {item.orderNo || item.orderId}</span>
                    <span className="text-right">{item.assigneeName || '未分派'}</span>
                  </div>
                </button>
              ))}
              {!loading && !visibleItems.length && <div className="px-4 py-10 text-center text-sm font-bold text-muted">暂无交付任务</div>}
              {loading && <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>
            ) : (
              <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.taskNo || selected.id} · 订单 {selected.orderNo || selected.orderId}</div>
                      <h2 className="mt-1 break-words text-lg font-extrabold text-ink">{selected.title}</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)_250px]">
                  <div className="min-w-0">
                    <div className="grid gap-2 md:grid-cols-4">
                      <Info label="交付类型" value={typeLabel[selected.type] || selected.type} />
                      <Info label="商品" value={selected.productTitle || selected.productId} />
                      <Info label="负责人" value={selected.assigneeName || '未分派'} />
                      <Info label="用户手机号" value={selected.userPhone || '-'} />
                      <Info label="优先级" value={selected.priority} />
                      <Info label="受理时间" value={formatDate(selected.acceptedAt)} />
                      <Info label="资料提交" value={formatDate(selected.submittedAt)} />
                      <Info label="完成时间" value={formatDate(selected.completedAt)} />
                      <Info label="更新时间" value={formatDate(selected.updatedAt)} />
                    </div>

                    <div className="mt-3 border border-line p-3">
                      <div className="text-xs font-extrabold text-ink">用户提交材料</div>
                      {materials.length ? (
                        <div className="mt-2 grid gap-1.5">
                          {materials.map((item) => (
                            <div key={item.key} className="grid gap-2 bg-bg px-2.5 py-2 text-xs md:grid-cols-[110px_1fr]">
                              <span className="font-extrabold text-muted">{item.key}</span>
                              <span className="break-words font-bold text-ink">{item.value}</span>
                            </div>
                          ))}
                        </div>
                      ) : <div className="mt-2 text-xs font-bold text-muted">暂无材料，可能仍处于待提交资料状态。</div>}
                      {materialFiles.length ? (
                        <div className="mt-2 grid gap-1 text-xs font-bold">
                          {materialFiles.map((file) => (
                            <a key={file.id} href={file.url} target="_blank" rel="noreferrer" className="text-brand hover:underline">
                              附件：{file.fileName}
                            </a>
                          ))}
                        </div>
                      ) : null}
                      {selected.reviewNote && <div className="mt-2 rounded-[4px] bg-amber-50 px-2.5 py-2 text-xs font-bold text-amber-700">审核备注：{selected.reviewNote}</div>}
                    </div>

                    <div className="mt-3 grid gap-3 md:grid-cols-2">
                      <label className="block">
                        <span className="mb-1.5 block text-xs font-extrabold text-ink">处理记录</span>
                        <textarea value={note} onChange={(event) => setNote(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.5 block text-xs font-extrabold text-ink">交付结果</span>
                        <textarea value={result} onChange={(event) => setResult(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>

                  <aside className="h-fit border border-line bg-bg p-3">
                    <div className="mb-2 flex items-center gap-2 text-xs font-extrabold text-ink">
                      <BarChart3 className="h-4 w-4 text-brand" />
                      任务操作
                    </div>
                    <div className="grid gap-2">
                      {!canUpdateTask && <div className="rounded-[4px] bg-white px-3 py-2 text-xs font-bold leading-5 text-muted">当前账号仅可查看交付任务，不能接单、流转或完成任务。</div>}
                      {selected.status === 'pending_material' && <div className="rounded-[4px] bg-white px-3 py-2 text-xs font-bold leading-5 text-muted">等待用户提交资料，暂不推进。</div>}
                      {canUpdateTask && selected.status === 'assigned' && !selected.assigneeName && (
                        <ActionButton icon={<CheckCircle2 className="h-3.5 w-3.5" />} disabled={saving} onClick={() => void updateSelected('assigned', { accept: true, progressNote: note })}>接单</ActionButton>
                      )}
                      {canUpdateTask && selected.status === 'assigned' && (
                        <ActionButton icon={<PlayCircle className="h-3.5 w-3.5" />} disabled={saving} onClick={() => void updateSelected('in_progress', { progressNote: note })}>开始处理</ActionButton>
                      )}
                      {canUpdateTask && selected.status === 'in_progress' && (
                        <>
                          <ActionButton icon={<Clock3 className="h-3.5 w-3.5" />} disabled={saving} onClick={() => void updateSelected('in_progress', { progressNote: note })}>保存进度</ActionButton>
                          <ActionButton disabled={saving} onClick={() => void updateSelected('pending_confirm', { progressNote: note, resultSummary: result })}>提交确认</ActionButton>
                        </>
                      )}
                      {canUpdateTask && selected.status === 'pending_confirm' && (
                        <ActionButton disabled={saving} onClick={() => void updateSelected('completed', { progressNote: note, resultSummary: result })}>标记完成</ActionButton>
                      )}
                      {readonly && <div className="rounded-[4px] bg-white px-3 py-2 text-xs font-bold leading-5 text-muted">当前任务已归档，只读查看。</div>}
                    </div>
                  </aside>
                </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-2">
      <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 ActionButton({
  children,
  disabled,
  icon,
  onClick,
}: {
  children: ReactNode
  disabled?: boolean
  icon?: ReactNode
  onClick: () => void
}) {
  return (
    <button type="button" disabled={disabled} onClick={onClick} className="inline-flex h-8 items-center justify-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand disabled:opacity-50">
      {icon}
      {children}
    </button>
  )
}
