'use client'

import Link from 'next/link'
import { Suspense, useCallback, useEffect, useMemo, useState } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { BarChart3, ClipboardCheck, Database, RefreshCw, UserCheck } from 'lucide-react'
import { backend, getStaffToken, type BackendConsultingRequest, type BackendDataServiceRequest, type BackendTask, type StaffAccount, yuan } from '@/lib/backend'

type WorkMode = 'tasks' | 'consulting' | 'data-service'

const moduleItems: Array<{ label: string; value: WorkMode; icon: typeof ClipboardCheck; description: string; permissions: string[] }> = [
  { label: '交付任务', value: 'tasks', icon: ClipboardCheck, description: '智能体、专家等交付工单', permissions: ['task:read'] },
  { label: '咨询需求', value: 'consulting', icon: UserCheck, description: '规划咨询线索受理和方案跟进', permissions: ['consulting:read'] },
  { label: '数据服务', value: 'data-service', icon: Database, description: '数据定制需求、报价、交付', permissions: ['data_service:read'] },
]

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

const consultingStatuses = [
  { label: '全部', value: '' },
  { label: '待受理', value: 'pending' },
  { label: '已分配', value: 'assigned' },
  { label: '沟通中', value: 'communicating' },
  { label: '方案中', value: 'planning' },
  { label: '待确认报价', value: 'proposal_ready' },
  { label: '待支付', value: 'pending_payment' },
  { label: '服务中', value: 'in_service' },
  { label: '已完成', value: 'completed' },
]

const dataServiceStatuses = [
  { label: '全部', value: '' },
  { label: '待联系', value: 'pending_contact' },
  { label: '联系中', value: 'contacting' },
  { label: '已报价', value: 'quoted' },
  { label: '待支付', value: 'pending_payment' },
  { label: '服务中', value: 'in_service' },
  { label: '已完成', value: 'completed' },
]

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

const consultingStatusLabel: Record<string, string> = {
  pending: '待受理',
  assigned: '已分配',
  communicating: '沟通中',
  planning: '方案制定中',
  proposal_ready: '待确认报价',
  pending_payment: '待支付',
  in_service: '服务中',
  completed: '已完成',
  cancelled: '已取消',
}

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

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

function modeFromParam(value: string | null): WorkMode {
  if (value === 'consulting') return 'consulting'
  if (value === 'data-service') return 'data-service'
  return 'tasks'
}

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 statusTone(status: string) {
  if (status === 'completed') return 'bg-green-50 text-green'
  if (['in_progress', 'pending_confirm', 'planning', 'proposal_ready', 'quoted', 'pending_payment', 'in_service'].includes(status)) return 'bg-amber-50 text-amber-700'
  if (['assigned', 'communicating', 'contacting'].includes(status)) return 'bg-brand-light text-brand'
  return 'bg-bg text-muted'
}

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 || {})
    .map(([key, value]) => ({ key, value: stringifyValue(value) }))
    .filter((item) => item.value)
}

function isPermissionError(error: unknown) {
  const message = error instanceof Error ? error.message : String(error || '')
  return message.includes('权限') || message.includes('forbidden')
}

function itemsFromResult<T>(result: PromiseSettledResult<{ items: T[] }>) {
  if (result.status === 'fulfilled') return result.value.items
  if (isPermissionError(result.reason)) return []
  throw result.reason
}

function canOpenAdmin(account: StaffAccount | null) {
  if (!account) return false
  if (account.defaultEntry?.startsWith('/admin')) return true
  const adminPermissions = [
    '*',
    'order:read',
    'payment:read',
    'settlement:read',
    'reconcile:export',
    'product:read',
    'coupon:read',
    'news:read',
    'site:read',
    'cooperation:read',
    'expert_profile:read',
    'expert_application:read',
    'expert_booking:read',
    'expert_schedule:read',
    'event:read',
    'staff:read',
    'role:read',
    'audit:read',
    'user:read',
  ]
  return adminPermissions.some((permission) => account.permissions?.includes(permission))
}

function canUseModule(account: StaffAccount | null, permissions: string[]) {
  if (!account) return false
  if (account.permissions?.includes('*')) return true
  return permissions.some((permission) => account.permissions?.includes(permission))
}

function textareaValue<T extends { id: string }>(store: Record<string, string>, item: T | null, fallback?: string) {
  if (!item) return ''
  return store[item.id] ?? fallback ?? ''
}

function StaffWorkbenchContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const modeParam = searchParams.get('mode')
  const selectedParam = searchParams.get('selected') || ''
  const [account, setAccount] = useState<StaffAccount | null>(null)
  const [workMode, setWorkMode] = useState<WorkMode>(modeFromParam(modeParam))
  const [activeStatus, setActiveStatus] = useState('')
  const [scope, setScope] = useState<'pool' | 'mine' | 'all'>('pool')
  const [taskType, setTaskType] = useState('')
  const [selectedId, setSelectedId] = useState(selectedParam)
  const [tasks, setTasks] = useState<BackendTask[]>([])
  const [consultingRequests, setConsultingRequests] = useState<BackendConsultingRequest[]>([])
  const [dataRequests, setDataRequests] = useState<BackendDataServiceRequest[]>([])
  const [notes, setNotes] = useState<Record<string, string>>({})
  const [results, setResults] = useState<Record<string, string>>({})
  const [quoteForms, setQuoteForms] = useState<Record<string, { title: string; amount: string; note: string }>>({})
  const [finalFiles, setFinalFiles] = useState<Record<string, { id: string; name: string }>>({})
  const [deliverableFiles, setDeliverableFiles] = useState<Record<string, Array<{ id: string; name: string }>>>({})
  const [uploading, setUploading] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)

  const selectedTask = useMemo(() => tasks.find((item) => item.id === selectedId || item.taskNo === selectedId) || tasks[0] || null, [selectedId, tasks])
  const selectedConsulting = useMemo(() => consultingRequests.find((item) => item.id === selectedId || item.requestNo === selectedId) || consultingRequests[0] || null, [consultingRequests, selectedId])
  const selectedData = useMemo(() => dataRequests.find((item) => item.id === selectedId || item.requestNo === selectedId) || dataRequests[0] || null, [dataRequests, selectedId])
  const visibleModuleItems = useMemo(() => moduleItems.filter((item) => canUseModule(account, item.permissions)), [account])

  const statusOptions = workMode === 'tasks' ? taskStatuses : workMode === 'consulting' ? consultingStatuses : dataServiceStatuses
  const currentModule = visibleModuleItems.find((item) => item.value === workMode) || visibleModuleItems[0] || moduleItems[0]
  const taskTypes = useMemo(() => Array.from(new Set(tasks.map((item) => item.type).filter(Boolean))), [tasks])
  const canUseAllScope = Boolean(account?.permissions?.includes('*') || account?.role === 'super_admin' || account?.role === 'operations_admin' || account?.permissions?.includes('operations:read'))

  const currentItems = workMode === 'tasks' ? tasks : workMode === 'consulting' ? consultingRequests : dataRequests
  const stats = {
    all: currentItems.length,
    waiting: currentItems.filter((item) => ['pending_material', 'pending', 'pending_contact'].includes(item.status)).length,
    doing: currentItems.filter((item) => ['assigned', 'in_progress', 'pending_confirm', 'communicating', 'planning', 'proposal_ready', 'contacting', 'quoted', 'pending_payment', 'in_service'].includes(item.status)).length,
    done: currentItems.filter((item) => item.status === 'completed').length,
  }

  const reload = useCallback(async () => {
    setLoading(true)
    try {
      const [taskResult, consultingResult, dataResult] = await Promise.allSettled([
        backend.staffTasks({
          status: workMode === 'tasks' ? activeStatus : '',
          scope,
          type: workMode === 'tasks' ? taskType : '',
        }),
        backend.staffConsultingRequests({
          status: workMode === 'consulting' ? activeStatus : '',
          scope,
        }),
        backend.staffDataServiceRequests({
          status: workMode === 'data-service' ? activeStatus : '',
          scope,
        }),
      ])
      const nextTasks = itemsFromResult<BackendTask>(taskResult)
      const nextConsultingRequests = itemsFromResult<BackendConsultingRequest>(consultingResult)
      const nextDataRequests = itemsFromResult<BackendDataServiceRequest>(dataResult)
      setTasks(nextTasks)
      setConsultingRequests(nextConsultingRequests)
      setDataRequests(nextDataRequests)
      setSelectedId((current) => {
        if (current) return current
        if (workMode === 'tasks') return nextTasks[0]?.taskNo || nextTasks[0]?.id || ''
        if (workMode === 'consulting') return nextConsultingRequests[0]?.requestNo || nextConsultingRequests[0]?.id || ''
        return nextDataRequests[0]?.requestNo || nextDataRequests[0]?.id || ''
      })
      const deniedCurrentMode =
        (workMode === 'tasks' && taskResult.status === 'rejected' && isPermissionError(taskResult.reason)) ||
        (workMode === 'consulting' && consultingResult.status === 'rejected' && isPermissionError(consultingResult.reason)) ||
        (workMode === 'data-service' && dataResult.status === 'rejected' && isPermissionError(dataResult.reason))
      setError(deniedCurrentMode ? '当前账号没有该模块权限' : '')
    } catch (err) {
      setError(err instanceof Error ? err.message : '员工工作台加载失败')
    } finally {
      setLoading(false)
    }
  }, [activeStatus, scope, taskType, workMode])

  useEffect(() => {
    queueMicrotask(async () => {
      if (!getStaffToken()) {
        router.replace('/login?redirect=%2Fstaff')
        return
      }
      try {
        setAccount(await backend.staffMe())
        await reload()
      } catch {
        router.replace('/login?redirect=%2Fstaff')
      }
    })
  }, [reload, router])

  useEffect(() => {
    const nextMode = modeFromParam(modeParam)
    setWorkMode(nextMode)
    setSelectedId(selectedParam)
    setActiveStatus('')
  }, [modeParam, selectedParam])

  useEffect(() => {
    if (!account || !visibleModuleItems.length) return
    if (!visibleModuleItems.some((item) => item.value === workMode)) {
      selectMode(visibleModuleItems[0].value)
    }
  }, [account, visibleModuleItems, workMode])

  async function updateTask(status: string, payload: Record<string, unknown> = {}) {
    if (!selectedTask) return
    try {
      await backend.updateStaffTask(selectedTask.id, status, payload)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '任务更新失败')
    }
  }

  async function updateConsulting(status: string, payload: Record<string, unknown> = {}) {
    if (!selectedConsulting) return
    try {
      await backend.updateStaffConsultingRequest(selectedConsulting.requestNo || selectedConsulting.id, status, payload)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '咨询需求更新失败')
    }
  }

  async function updateDataService(payload: Record<string, unknown>) {
    if (!selectedData) return
    try {
      await backend.updateStaffDataServiceRequest(selectedData.requestNo || selectedData.id, payload)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '数据服务更新失败')
    }
  }

  async function uploadStaffFile(file: File | null | undefined, onDone: (file: { id: string; name: string }) => void) {
    if (!file) return
    setUploading(file.name)
    try {
      const uploaded = await backend.uploadStaffFile(file)
      onDone({ id: uploaded.id, name: uploaded.fileName || file.name })
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '文件上传失败')
    } finally {
      setUploading('')
    }
  }

  function selectMode(nextMode: WorkMode) {
    setWorkMode(nextMode)
    setActiveStatus('')
    setSelectedId('')
  }

  if (loading && !account) {
    return (
      <section className="grid min-h-screen place-items-center bg-[#f5f7fb] px-6">
        <div className="text-sm font-extrabold text-muted">正在打开员工工作台...</div>
      </section>
    )
  }

  const taskNote = textareaValue(notes, selectedTask, selectedTask?.progressNote)
  const taskResult = textareaValue(results, selectedTask, selectedTask?.resultSummary)
  const consultingNote = textareaValue(notes, selectedConsulting, selectedConsulting?.progressNote)
  const consultingResult = textareaValue(results, selectedConsulting, selectedConsulting?.finalSummary || selectedConsulting?.solutionSummary)
  const consultingFinalFile = selectedConsulting ? finalFiles[selectedConsulting.id] : undefined
  const consultingQuote = selectedConsulting ? quoteForms[selectedConsulting.id] || {
    title: selectedConsulting.quotedTitle || `${selectedConsulting.direction || '规划咨询'}服务报价`,
    amount: selectedConsulting.quotedAmount ? String(yuan(selectedConsulting.quotedAmount)) : '',
    note: selectedConsulting.quotedNote || selectedConsulting.solutionSummary || '',
  } : { title: '', amount: '', note: '' }
  const dataNote = textareaValue(notes, selectedData, selectedData?.progressNote || selectedData?.contactNote)
  const dataResult = textareaValue(results, selectedData, selectedData?.resultSummary)
  const dataDeliverables = selectedData ? deliverableFiles[selectedData.id] || [] : []
  const dataQuote = selectedData ? quoteForms[selectedData.id] || {
    title: selectedData.quotedTitle || selectedData.dataTopic || '数据服务报价',
    amount: selectedData.quotedAmount ? String(yuan(selectedData.quotedAmount)) : '',
    note: selectedData.quotedNote || '',
  } : { title: '', amount: '', note: '' }

  return (
    <section className="min-h-screen bg-[#f5f7fb]">
      <aside className="fixed inset-y-0 left-0 z-50 w-[260px] border-r border-line bg-white">
        <div className="flex h-full flex-col">
          <div className="border-b border-line px-4 py-3">
            <div className="text-[11px] font-extrabold uppercase tracking-[0.14em] text-soft">WORKBENCH</div>
            <div className="mt-1 text-[15px] font-extrabold text-ink">员工工作台</div>
            <div className="mt-1 truncate text-xs font-bold text-muted">{account?.displayName || '员工'} · {account?.role || 'staff'}</div>
          </div>

          <nav className="min-h-0 flex-1 overflow-y-auto px-3 py-3">
            <div className="mb-5">
              <div className="mb-1 px-2 text-[11px] font-extrabold text-soft">业务队列</div>
              {visibleModuleItems.map((item) => {
                const Icon = item.icon
                return (
                  <button key={item.value} type="button" onClick={() => selectMode(item.value)} className={`mt-1 grid w-full grid-cols-[18px_1fr] gap-2 px-2 py-2 text-left ${workMode === item.value ? 'bg-ink text-white' : 'text-muted hover:bg-bg hover:text-ink'}`}>
                    <Icon className="mt-0.5 h-4 w-4" />
                    <span className="min-w-0">
                      <span className="block text-[13px] font-extrabold">{item.label}</span>
                      <span className={`mt-0.5 block text-[11px] font-bold leading-4 ${workMode === item.value ? 'text-white/70' : 'text-soft'}`}>{item.description}</span>
                    </span>
                  </button>
                )
              })}
            </div>

            <div className="mb-5">
              <div className="mb-1 px-2 text-[11px] font-extrabold text-soft">任务范围</div>
              <button type="button" onClick={() => setScope('pool')} className={`flex h-8 w-full items-center px-2 text-[13px] font-bold ${scope === 'pool' ? 'bg-bg text-ink' : 'text-muted hover:bg-bg hover:text-ink'}`}>待接单池</button>
              <button type="button" onClick={() => setScope('mine')} className={`mt-1 flex h-8 w-full items-center px-2 text-[13px] font-bold ${scope === 'mine' ? 'bg-bg text-ink' : 'text-muted hover:bg-bg hover:text-ink'}`}>只看我负责</button>
              {canUseAllScope && <button type="button" onClick={() => setScope('all')} className={`mt-1 flex h-8 w-full items-center px-2 text-[13px] font-bold ${scope === 'all' ? 'bg-bg text-ink' : 'text-muted hover:bg-bg hover:text-ink'}`}>全部</button>}
            </div>

            {workMode === 'tasks' && (
              <div>
                <div className="mb-1 px-2 text-[11px] font-extrabold text-soft">交付类型</div>
                <button type="button" onClick={() => setTaskType('')} className={`flex h-8 w-full items-center px-2 text-[13px] font-bold ${!taskType ? 'bg-bg text-ink' : 'text-muted hover:bg-bg hover:text-ink'}`}>全部类型</button>
                {taskTypes.map((type) => (
                  <button key={type} type="button" onClick={() => setTaskType(type)} className={`mt-1 flex h-8 w-full items-center px-2 text-[13px] font-bold ${taskType === type ? 'bg-bg text-ink' : 'text-muted hover:bg-bg hover:text-ink'}`}>{taskTypeLabel[type] || type}</button>
                ))}
              </div>
            )}
          </nav>

          {canOpenAdmin(account) && (
            <div className="border-t border-line px-4 py-3">
              <Link href={account?.defaultEntry?.startsWith('/admin') ? account.defaultEntry : '/admin'} className="block h-8 border border-line px-3 py-1.5 text-center text-xs font-extrabold text-muted hover:border-brand hover:text-brand">管理端</Link>
            </div>
          )}
        </div>
      </aside>

      <main className="min-h-screen pl-[260px]">
        <div className="sticky top-0 z-30 border-b border-line bg-white/95 px-5 py-3 backdrop-blur">
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div className="min-w-0">
              <h1 className="truncate text-lg font-extrabold text-ink">{currentModule.label}</h1>
              <div className="mt-0.5 text-xs font-bold text-muted">当前 {stats.all} · 待处理 {stats.waiting} · 进行中 {stats.doing} · 已完成 {stats.done}</div>
            </div>
            <div className="flex items-center gap-2">
              <button type="button" onClick={() => void reload()} className="grid h-8 w-8 place-items-center border border-line text-muted hover:border-brand hover:text-brand" aria-label="刷新">
                <RefreshCw className="h-4 w-4" />
              </button>
            </div>
          </div>
        </div>

        <div className="px-5 py-4">
          {error && <div className="mb-4 border border-red-200 bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}

          <div className="mb-4 flex flex-wrap gap-2">
            {statusOptions.map((item) => (
              <button key={item.label} type="button" onClick={() => setActiveStatus(item.value)} className={`h-9 border px-3 text-sm font-bold ${activeStatus === item.value ? 'border-brand bg-brand-light text-brand' : 'border-line bg-white text-muted hover:border-brand hover:text-brand'}`}>
                {item.label}
              </button>
            ))}
          </div>

          <div className="grid gap-4 xl:grid-cols-[390px_1fr]">
            <section className="border border-line bg-white">
              <div className="border-b border-line px-5 py-4 text-base font-extrabold text-ink">{currentModule.label}列表</div>
              {loading ? <div className="px-5 py-12 text-sm font-bold text-muted">正在加载...</div> : null}
              {!loading && workMode === 'tasks' && (tasks.length === 0 ? <EmptyList /> : (
                <div className="divide-y divide-line">
                  {tasks.map((task) => (
                    <button key={task.id} type="button" onClick={() => setSelectedId(task.taskNo || task.id)} className={`block w-full px-5 py-4 text-left hover:bg-[#f8fbff] ${selectedTask?.id === task.id ? 'bg-brand-light/60' : ''}`}>
                      <div className="flex items-start justify-between gap-3">
                        <div className="font-extrabold leading-6 text-ink">{task.taskNo || task.id}</div>
                        <span className={`shrink-0 px-2 py-1 text-xs font-bold ${statusTone(task.status)}`}>{taskStatusLabel[task.status] || task.status}</span>
                      </div>
                      <div className="mt-1 text-sm font-bold text-muted">{task.productTitle || task.title}</div>
                      <div className="mt-1 text-xs text-soft">{taskTypeLabel[task.type] || task.type} · 订单 {task.orderNo || task.orderId} · {task.userPhone || '-'}</div>
                    </button>
                  ))}
                </div>
              ))}
              {!loading && workMode === 'consulting' && (consultingRequests.length === 0 ? <EmptyList /> : (
                <div className="divide-y divide-line">
                  {consultingRequests.map((request) => (
                    <button key={request.id} type="button" onClick={() => setSelectedId(request.requestNo || request.id)} className={`block w-full px-5 py-4 text-left hover:bg-[#f8fbff] ${selectedConsulting?.id === request.id ? 'bg-brand-light/60' : ''}`}>
                      <div className="flex items-start justify-between gap-3">
                        <div className="font-extrabold leading-6 text-ink">{request.requestNo}</div>
                        <span className={`shrink-0 px-2 py-1 text-xs font-bold ${statusTone(request.status)}`}>{consultingStatusLabel[request.status] || request.status}</span>
                      </div>
                      <div className="mt-1 text-sm font-bold text-muted">{request.direction || '规划咨询'}</div>
                      <div className="mt-1 text-xs text-soft">{request.company} · {request.contactName} / {request.contactPhone}</div>
                    </button>
                  ))}
                </div>
              ))}
              {!loading && workMode === 'data-service' && (dataRequests.length === 0 ? <EmptyList /> : (
                <div className="divide-y divide-line">
                  {dataRequests.map((request) => (
                    <button key={request.id} type="button" onClick={() => setSelectedId(request.requestNo || request.id)} className={`block w-full px-5 py-4 text-left hover:bg-[#f8fbff] ${selectedData?.id === request.id ? 'bg-brand-light/60' : ''}`}>
                      <div className="flex items-start justify-between gap-3">
                        <div className="font-extrabold leading-6 text-ink">{request.requestNo}</div>
                        <span className={`shrink-0 px-2 py-1 text-xs font-bold ${statusTone(request.status)}`}>{dataServiceStatusLabel[request.status] || request.status}</span>
                      </div>
                      <div className="mt-1 text-sm font-bold text-muted">{request.dataTopic || request.quotedTitle || '数据服务'}</div>
                      <div className="mt-1 text-xs text-soft">{request.company} · {request.serviceType} · {request.orderNo || '未成单'}</div>
                    </button>
                  ))}
                </div>
              ))}
            </section>

            <section className="border border-line bg-white">
              {workMode === 'tasks' && <TaskDetail task={selectedTask} note={taskNote} result={taskResult} setNotes={setNotes} setResults={setResults} updateTask={updateTask} />}
              {workMode === 'consulting' && <ConsultingDetail request={selectedConsulting} note={consultingNote} result={consultingResult} quote={consultingQuote} finalFile={consultingFinalFile} uploading={uploading} uploadStaffFile={uploadStaffFile} setFinalFiles={setFinalFiles} setNotes={setNotes} setResults={setResults} setQuoteForms={setQuoteForms} updateConsulting={updateConsulting} />}
              {workMode === 'data-service' && <DataServiceDetail request={selectedData} note={dataNote} result={dataResult} quote={dataQuote} deliverables={dataDeliverables} uploading={uploading} uploadStaffFile={uploadStaffFile} setDeliverableFiles={setDeliverableFiles} setNotes={setNotes} setResults={setResults} setQuoteForms={setQuoteForms} updateDataService={updateDataService} />}
            </section>
          </div>
        </div>
      </main>
    </section>
  )
}

export default function StaffWorkbenchPage() {
  return (
    <Suspense fallback={<section className="grid min-h-screen place-items-center bg-white text-sm font-bold text-muted">正在加载员工工作台...</section>}>
      <StaffWorkbenchContent />
    </Suspense>
  )
}

function EmptyList() {
  return <div className="px-5 py-16 text-center text-sm font-bold text-muted">当前筛选下暂无记录</div>
}

function Info({ label, value }: { label: string; value?: string | number | null }) {
  return (
    <div className="border border-line p-3">
      <div className="text-xs font-bold text-soft">{label}</div>
      <div className="mt-1 break-words text-sm font-extrabold text-ink">{value || '-'}</div>
    </div>
  )
}

function TaskDetail({
  task,
  note,
  result,
  setNotes,
  setResults,
  updateTask,
}: {
  task: BackendTask | null
  note: string
  result: string
  setNotes: React.Dispatch<React.SetStateAction<Record<string, string>>>
  setResults: React.Dispatch<React.SetStateAction<Record<string, string>>>
  updateTask: (status: string, payload?: Record<string, unknown>) => Promise<void>
}) {
  if (!task) return <div className="grid min-h-[520px] place-items-center text-sm font-bold text-muted">选择一个交付任务</div>
  const materials = materialEntries(task.materialPayload)
  const readonly = ['completed', 'cancelled'].includes(task.status)
  return (
    <div>
      <Header title={task.title} meta={`${task.taskNo || task.id} · 订单 ${task.orderNo || task.orderId}`} status={taskStatusLabel[task.status] || task.status} statusClass={statusTone(task.status)} />
      <div className="grid gap-6 p-5 2xl:grid-cols-[1fr_280px]">
        <div className="min-w-0">
          <div className="grid gap-3 md:grid-cols-3">
            <Info label="交付类型" value={taskTypeLabel[task.type] || task.type} />
            <Info label="商品" value={task.productTitle || task.productId} />
            <Info label="负责人" value={task.assigneeName || '未接单'} />
            <Info label="用户手机号" value={task.userPhone} />
            <Info label="优先级" value={task.priority} />
            <Info label="更新时间" value={formatDate(task.updatedAt)} />
          </div>

          <div className="mt-5 border border-line p-4">
            <div className="text-sm font-extrabold text-ink">用户提交材料</div>
            {materials.length === 0 ? <div className="mt-3 text-sm font-bold text-muted">暂无材料，可能仍处于待提交资料状态。</div> : (
              <div className="mt-3 grid gap-2">
                {materials.map((item) => (
                  <div key={item.key} className="grid gap-2 bg-bg px-3 py-2 text-sm md:grid-cols-[120px_1fr]">
                    <span className="font-extrabold text-muted">{item.key}</span>
                    <span className="break-words font-bold text-ink">{item.value}</span>
                  </div>
                ))}
              </div>
            )}
          </div>

          <WorkTextareas id={task.id} note={note} result={result} resultLabel="交付结果" setNotes={setNotes} setResults={setResults} />
        </div>
        <ActionPanel title="任务操作">
          {task.status === 'pending_material' && <div className="rounded-[4px] bg-bg px-3 py-2 text-xs font-bold leading-5 text-muted">等待用户提交资料，暂不推进。</div>}
          {task.status === 'assigned' && !task.assigneeName && (
            <button type="button" onClick={() => void updateTask('assigned', { accept: true, progressNote: note })} className="h-9 bg-ink text-xs font-extrabold text-white hover:bg-brand">接单</button>
          )}
          {task.status === 'assigned' && (
            <button type="button" onClick={() => void updateTask('in_progress', { progressNote: note })} className="h-9 border border-line text-xs font-extrabold text-muted hover:border-brand hover:text-brand">开始处理</button>
          )}
          {task.status === 'in_progress' && (
            <>
              <button type="button" onClick={() => void updateTask('in_progress', { progressNote: note })} className="h-9 border border-line text-xs font-extrabold text-muted hover:border-brand hover:text-brand">保存进度</button>
              <button type="button" onClick={() => void updateTask('pending_confirm', { progressNote: note, resultSummary: result })} className="h-9 border border-line text-xs font-extrabold text-muted hover:border-brand hover:text-brand">提交确认</button>
            </>
          )}
          {task.status === 'pending_confirm' && (
            <button type="button" onClick={() => void updateTask('completed', { progressNote: note, resultSummary: result })} className="h-9 border border-line text-xs font-extrabold text-muted hover:border-brand hover:text-brand">标记完成</button>
          )}
          {readonly && <div className="rounded-[4px] bg-bg px-3 py-2 text-xs font-bold leading-5 text-muted">当前任务已归档，只读查看。</div>}
        </ActionPanel>
      </div>
    </div>
  )
}

function ConsultingDetail({
  request,
  note,
  result,
  quote,
  finalFile,
  uploading,
  uploadStaffFile,
  setFinalFiles,
  setNotes,
  setResults,
  setQuoteForms,
  updateConsulting,
}: {
  request: BackendConsultingRequest | null
  note: string
  result: string
  quote: { title: string; amount: string; note: string }
  finalFile?: { id: string; name: string }
  uploading: string
  uploadStaffFile: (file: File | null | undefined, onDone: (file: { id: string; name: string }) => void) => Promise<void>
  setFinalFiles: React.Dispatch<React.SetStateAction<Record<string, { id: string; name: string }>>>
  setNotes: React.Dispatch<React.SetStateAction<Record<string, string>>>
  setResults: React.Dispatch<React.SetStateAction<Record<string, string>>>
  setQuoteForms: React.Dispatch<React.SetStateAction<Record<string, { title: string; amount: string; note: string }>>>
  updateConsulting: (status: string, payload?: Record<string, unknown>) => Promise<void>
}) {
  if (!request) return <div className="grid min-h-[520px] place-items-center text-sm font-bold text-muted">选择一个咨询需求</div>
  const quoteAmount = Math.round(Number(quote.amount || 0) * 100)
  return (
    <div>
      <Header title={request.direction || '规划咨询'} meta={`${request.requestNo} · ${request.company}`} status={consultingStatusLabel[request.status] || request.status} statusClass={statusTone(request.status)} />
      <div className="grid gap-6 p-5 2xl:grid-cols-[1fr_280px]">
        <div>
          <div className="grid gap-3 md:grid-cols-3">
            <Info label="联系人" value={`${request.contactName} / ${request.contactPhone}`} />
            <Info label="城市/行业" value={`${request.city || '-'} / ${request.industry || '-'}`} />
            <Info label="负责人" value={request.assigneeName || '未接单'} />
            <Info label="项目阶段" value={request.projectStage} />
            <Info label="预算" value={request.budgetRange} />
            <Info label="期望启动" value={request.expectedStart} />
          </div>
          <LongText title="客户现状" value={request.currentSituation} />
          <LongText title="核心需求" value={request.requirement} />
          <LongText title="目标" value={request.goals} />
          <LongText title="已发送报价说明" value={request.quotedNote} />
          <LongText title="最终方案反馈" value={request.finalSummary} />

          <div className="mt-5 border border-line p-4">
            <div className="text-sm font-extrabold text-ink">收费报价</div>
            <div className="mt-2 text-xs font-bold leading-6 text-muted">需要收费时填写报价并发送给用户；免费咨询请直接在下方填写最终方案反馈后完成。</div>
            <div className="mt-3 grid gap-3 md:grid-cols-[1fr_140px]">
              <input value={quote.title} onChange={(event) => setQuoteForms((current) => ({ ...current, [request.id]: { ...quote, title: event.target.value } }))} placeholder="报价标题" className="h-10 border border-line px-3 text-sm font-bold outline-none focus:border-brand" />
              <input value={quote.amount} onChange={(event) => setQuoteForms((current) => ({ ...current, [request.id]: { ...quote, amount: event.target.value } }))} type="number" min="0" placeholder="金额（元）" className="h-10 border border-line px-3 text-sm font-bold outline-none focus:border-brand" />
            </div>
            <textarea value={quote.note} onChange={(event) => setQuoteForms((current) => ({ ...current, [request.id]: { ...quote, note: event.target.value } }))} rows={3} placeholder="报价说明/方案摘要" className="mt-3 w-full border border-line p-3 text-sm font-bold outline-none focus:border-brand" />
          </div>

          <WorkTextareas id={request.id} note={note} result={result} resultLabel="最终方案反馈" setNotes={setNotes} setResults={setResults} />
          <div className="mt-5 border border-line p-4">
            <div className="text-sm font-extrabold text-ink">最终方案附件</div>
            <div className="mt-2 text-xs font-bold leading-6 text-muted">可上传 PDF、Word、PPT、ZIP 等最终反馈材料；完成服务时会同步开放给用户。</div>
            <label className="mt-3 inline-flex h-10 cursor-pointer items-center border border-line px-4 text-sm font-extrabold text-muted hover:border-brand hover:text-brand">
              {uploading ? `正在上传：${uploading}` : '上传最终附件'}
              <input type="file" className="sr-only" onChange={(event) => {
                const file = event.target.files?.[0]
                void uploadStaffFile(file, (uploaded) => setFinalFiles((current) => ({ ...current, [request.id]: uploaded })))
                event.currentTarget.value = ''
              }} />
            </label>
            <div className="mt-3 text-xs font-bold text-muted">
              {finalFile ? `已选择：${finalFile.name}` : request.finalFileId ? '已存在最终附件，可重新上传覆盖。' : '暂未上传附件'}
            </div>
          </div>
        </div>
        <ActionPanel title="咨询操作">
          {request.status === 'pending' && (
            <button type="button" onClick={() => void updateConsulting('assigned', { accept: true, progressNote: note })} className="h-10 bg-ink text-sm font-extrabold text-white hover:bg-brand">接单</button>
          )}
          {request.status === 'assigned' && (
            <button type="button" onClick={() => void updateConsulting('communicating', { progressNote: note })} className="h-10 border border-line text-sm font-extrabold text-muted hover:border-brand hover:text-brand">进入沟通</button>
          )}
          {request.status === 'communicating' && (
            <button type="button" onClick={() => void updateConsulting('planning', { progressNote: note, solutionSummary: result })} className="h-10 border border-line text-sm font-extrabold text-muted hover:border-brand hover:text-brand">制定方案</button>
          )}
          {request.status === 'planning' && (
            <>
              <button type="button" onClick={() => void updateConsulting('proposal_ready', { chargeRequired: true, quotedTitle: quote.title, quotedAmount: quoteAmount, quotedNote: quote.note, progressNote: note, solutionSummary: result || quote.note })} className="h-10 border border-line text-sm font-extrabold text-muted hover:border-brand hover:text-brand">发送收费报价</button>
              <button type="button" onClick={() => void updateConsulting('completed', { chargeRequired: false, progressNote: note, solutionSummary: result, finalSummary: result, finalFileId: finalFile?.id })} className="h-10 border border-line text-sm font-extrabold text-muted hover:border-brand hover:text-brand">免费完成并反馈</button>
            </>
          )}
          {['proposal_ready', 'pending_payment'].includes(request.status) && (
            <button type="button" onClick={() => void updateConsulting(request.status, { progressNote: note, solutionSummary: result, quotedTitle: quote.title, quotedAmount: quoteAmount, quotedNote: quote.note })} className="h-10 border border-line text-sm font-extrabold text-muted hover:border-brand hover:text-brand">保存报价/进度</button>
          )}
          {request.status === 'in_service' && (
            <button type="button" onClick={() => void updateConsulting('completed', { progressNote: note, solutionSummary: result, finalSummary: result, finalFileId: finalFile?.id })} className="h-10 border border-line text-sm font-extrabold text-muted hover:border-brand hover:text-brand">服务完成并反馈</button>
          )}
        </ActionPanel>
      </div>
    </div>
  )
}

function DataServiceDetail({
  request,
  note,
  result,
  quote,
  deliverables,
  uploading,
  uploadStaffFile,
  setDeliverableFiles,
  setNotes,
  setResults,
  setQuoteForms,
  updateDataService,
}: {
  request: BackendDataServiceRequest | null
  note: string
  result: string
  quote: { title: string; amount: string; note: string }
  deliverables: Array<{ id: string; name: string }>
  uploading: string
  uploadStaffFile: (file: File | null | undefined, onDone: (file: { id: string; name: string }) => void) => Promise<void>
  setDeliverableFiles: React.Dispatch<React.SetStateAction<Record<string, Array<{ id: string; name: string }>>>>
  setNotes: React.Dispatch<React.SetStateAction<Record<string, string>>>
  setResults: React.Dispatch<React.SetStateAction<Record<string, string>>>
  setQuoteForms: React.Dispatch<React.SetStateAction<Record<string, { title: string; amount: string; note: string }>>>
  updateDataService: (payload: Record<string, unknown>) => Promise<void>
}) {
  if (!request) return <div className="grid min-h-[520px] place-items-center text-sm font-bold text-muted">选择一个数据服务需求</div>
  const quoteAmount = Math.round(Number(quote.amount || 0) * 100)
  const canAccept = request.status === 'pending_contact'
  const canQuote = request.status === 'contacting'
  const canEnterService = request.status === 'pending_payment' && Boolean(request.paidAt)
  const canComplete = request.status === 'in_service'
  const canCancel = ['pending_contact', 'contacting', 'quoted', 'pending_payment'].includes(request.status) && !request.paidAt
  const readonly = ['completed', 'cancelled'].includes(request.status)
  return (
    <div>
      <Header title={request.dataTopic || request.quotedTitle || '数据服务'} meta={`${request.requestNo} · ${request.company}`} status={dataServiceStatusLabel[request.status] || request.status} statusClass={statusTone(request.status)} />
      <div className="grid gap-6 p-5 2xl:grid-cols-[1fr_280px]">
        <div>
          <div className="grid gap-3 md:grid-cols-3">
            <Info label="联系人" value={`${request.contactName} / ${request.contactPhone}`} />
            <Info label="服务类型" value={request.serviceType} />
            <Info label="负责人" value={request.assigneeName || '未接单'} />
            <Info label="数据范围" value={request.regionScope || request.timeRange} />
            <Info label="期望格式" value={request.expectedFormat} />
            <Info label="订单" value={request.orderNo || '未成单'} />
          </div>
          <LongText title="需求描述" value={request.requirement} />
          <LongText title="期望成果" value={request.expectedResult} />
          <LongText title="补充说明" value={request.extraNote} />

          <div className="mt-5 border border-line p-4">
            <div className="text-sm font-extrabold text-ink">报价</div>
            <div className="mt-3 grid gap-3 md:grid-cols-[1fr_140px]">
              <input value={quote.title} onChange={(event) => setQuoteForms((current) => ({ ...current, [request.id]: { ...quote, title: event.target.value } }))} placeholder="报价标题" className="h-10 border border-line px-3 text-sm font-bold outline-none focus:border-brand" />
              <input value={quote.amount} onChange={(event) => setQuoteForms((current) => ({ ...current, [request.id]: { ...quote, amount: event.target.value } }))} type="number" min="0" placeholder="金额（元）" className="h-10 border border-line px-3 text-sm font-bold outline-none focus:border-brand" />
            </div>
            <textarea value={quote.note} onChange={(event) => setQuoteForms((current) => ({ ...current, [request.id]: { ...quote, note: event.target.value } }))} rows={3} placeholder="报价说明" className="mt-3 w-full border border-line p-3 text-sm font-bold outline-none focus:border-brand" />
          </div>

          <WorkTextareas id={request.id} note={note} result={result} resultLabel="交付说明" setNotes={setNotes} setResults={setResults} />
          <div className="mt-5 border border-line p-4">
            <div className="text-sm font-extrabold text-ink">交付文件</div>
            <div className="mt-2 text-xs font-bold leading-6 text-muted">支持一次选择多个文件。完成交付时会把这些文件开放给用户下载。</div>
            <label className="mt-3 inline-flex h-10 cursor-pointer items-center border border-line px-4 text-sm font-extrabold text-muted hover:border-brand hover:text-brand">
              {uploading ? `正在上传：${uploading}` : '上传交付文件'}
              <input type="file" multiple className="sr-only" onChange={(event) => {
                const files = Array.from(event.target.files || [])
                files.forEach((file) => {
                  void uploadStaffFile(file, (uploaded) => setDeliverableFiles((current) => ({
                    ...current,
                    [request.id]: [...(current[request.id] || []), uploaded],
                  })))
                })
                event.currentTarget.value = ''
              }} />
            </label>
            <div className="mt-3 grid gap-1 text-xs font-bold text-muted">
              {deliverables.length ? deliverables.map((file) => <div key={file.id}>已上传：{file.name}</div>) : request.deliverableFileIds?.length ? <div>已有 {request.deliverableFileIds.length} 个交付附件，可继续追加。</div> : <div>暂未上传交付文件</div>}
            </div>
          </div>
        </div>
        <ActionPanel title="数据服务操作">
          {canAccept && <button type="button" onClick={() => void updateDataService({ accept: true, status: 'contacting', progressNote: note, contactNote: note })} className="h-9 bg-ink text-xs font-extrabold text-white hover:bg-brand">接单联系</button>}
          {canQuote && <button type="button" onClick={() => void updateDataService({ status: 'quoted', quotedTitle: quote.title, quotedAmount: quoteAmount, quotedNote: quote.note, progressNote: note })} className="h-9 border border-line text-xs font-extrabold text-muted hover:border-brand hover:text-brand">发送报价</button>}
          {['quoted', 'pending_payment'].includes(request.status) && (
            <>
              <div className="rounded-[4px] bg-amber-50 px-3 py-2 text-xs font-bold leading-5 text-amber-700">等待用户确认并付款，付款后系统会推进到服务中。</div>
              <button type="button" onClick={() => void updateDataService({ progressNote: note, quotedNote: quote.note })} className="h-9 border border-line text-xs font-extrabold text-muted hover:border-brand hover:text-brand">保存说明</button>
            </>
          )}
          {canEnterService && <button type="button" onClick={() => void updateDataService({ status: 'in_service', progressNote: note })} className="h-9 border border-line text-xs font-extrabold text-muted hover:border-brand hover:text-brand">进入服务</button>}
          {canComplete && <button type="button" onClick={() => {
            const existingIds = request.deliverableFileIds?.length ? request.deliverableFileIds : request.deliverableFileId ? [request.deliverableFileId] : []
            const nextIds = [...existingIds, ...deliverables.map((file) => file.id)]
            void updateDataService({ status: 'completed', progressNote: note, solutionSummary: request.solutionSummary || quote.note, resultSummary: result, deliverableFileIds: nextIds, deliverableFileId: nextIds[0] })
          }} className="h-9 border border-line text-xs font-extrabold text-muted hover:border-brand hover:text-brand">完成交付</button>}
          {canCancel && <button type="button" onClick={() => void updateDataService({ status: 'cancelled', progressNote: note })} className="h-9 border border-red-100 text-xs font-extrabold text-red-700 hover:border-red-300">未付款取消</button>}
          {readonly && <div className="rounded-[4px] bg-bg px-3 py-2 text-xs font-bold leading-5 text-muted">当前服务单已归档，只读查看。</div>}
        </ActionPanel>
      </div>
    </div>
  )
}

function Header({ title, meta, status, statusClass }: { title: string; meta: string; status: string; statusClass: string }) {
  return (
    <div className="border-b border-line px-6 py-5">
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div className="min-w-0">
          <div className="text-sm font-bold text-muted">{meta}</div>
          <h2 className="mt-2 break-words text-2xl font-extrabold text-ink">{title}</h2>
        </div>
        <span className={`shrink-0 px-3 py-1.5 text-sm font-extrabold ${statusClass}`}>{status}</span>
      </div>
    </div>
  )
}

function LongText({ title, value }: { title: string; value?: string }) {
  if (!value) return null
  return (
    <div className="mt-5 border border-line p-4">
      <div className="text-sm font-extrabold text-ink">{title}</div>
      <p className="mt-2 whitespace-pre-wrap text-sm font-bold leading-7 text-muted">{value}</p>
    </div>
  )
}

function WorkTextareas({
  id,
  note,
  result,
  resultLabel,
  setNotes,
  setResults,
}: {
  id: string
  note: string
  result: string
  resultLabel: string
  setNotes: React.Dispatch<React.SetStateAction<Record<string, string>>>
  setResults: React.Dispatch<React.SetStateAction<Record<string, string>>>
}) {
  return (
    <div className="mt-5 grid gap-4 md:grid-cols-2">
      <label className="block">
        <span className="mb-2 block text-sm font-extrabold text-ink">处理记录</span>
        <textarea value={note} onChange={(event) => setNotes((current) => ({ ...current, [id]: event.target.value }))} rows={6} className="w-full border border-line p-3 text-sm font-bold leading-7 text-ink outline-none focus:border-brand" />
      </label>
      <label className="block">
        <span className="mb-2 block text-sm font-extrabold text-ink">{resultLabel}</span>
        <textarea value={result} onChange={(event) => setResults((current) => ({ ...current, [id]: event.target.value }))} rows={6} className="w-full border border-line p-3 text-sm font-bold leading-7 text-ink outline-none focus:border-brand" />
      </label>
    </div>
  )
}

function ActionPanel({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <aside className="h-fit border border-line p-4">
      <div className="flex items-center gap-2 text-lg font-extrabold text-ink">
        <BarChart3 className="h-5 w-5 text-brand" />
        {title}
      </div>
      <div className="mt-4 grid gap-2">{children}</div>
      <div className="mt-5 border-t border-line pt-4 text-xs font-bold leading-6 text-muted">
        操作会直接写入后台真实工单、咨询或数据服务记录。
      </div>
    </aside>
  )
}
