'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { ArrowRight, Search } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendCooperationRequest, type BackendStaffAccount } from '@/lib/backend'

function statusLabel(status: BackendCooperationRequest['status']) {
  return status === 'completed' ? '已完成' : '待处理'
}

function targetHref(item: BackendCooperationRequest) {
  if (!item.convertedRefId) return ''
  if (item.convertedType === 'data_service') return `/admin/data-service/requests?selected=${encodeURIComponent(item.convertedRefId)}`
  return `/admin/consulting-requests?selected=${encodeURIComponent(item.convertedRefId)}`
}

export default function AdminCooperationRequestsPage() {
  const [items, setItems] = useState<BackendCooperationRequest[]>([])
  const [staff, setStaff] = useState<BackendStaffAccount[]>([])
  const [status, setStatus] = useState('')
  const [assigneeId, setAssigneeId] = useState('')
  const [keyword, setKeyword] = useState('')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  async function load(nextStatus = status) {
    setLoading(true)
    try {
      const [requestResult, staffResult] = await Promise.all([
        backend.adminCooperationRequests(nextStatus),
        backend.adminStaffAccounts({ status: 'active' }).catch(() => ({ items: [] as BackendStaffAccount[] })),
      ])
      setItems(requestResult.items)
      setStaff(staffResult.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '合作咨询加载失败')
    } finally {
      setLoading(false)
    }
  }

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

  const staffById = useMemo(() => new Map(staff.map((item) => [item.id, item])), [staff])
  const filtered = useMemo(() => {
    const query = keyword.trim().toLowerCase()
    return items.filter((item) => {
      const assigneeMatched = !assigneeId || item.assignedAccountId === assigneeId
      const keywordMatched = !query || [item.requestNo, item.organization, item.name, item.phone, item.demand].some((value) => String(value || '').toLowerCase().includes(query))
      return assigneeMatched && keywordMatched
    })
  }, [assigneeId, items, keyword])
  const stats = useMemo(() => ({
    total: items.length,
    pending: items.filter((item) => item.status !== 'completed').length,
    converted: items.filter((item) => item.convertedRefId).length,
    completed: items.filter((item) => item.status === 'completed').length,
  }), [items])

  function changeStatus(nextStatus: string) {
    setStatus(nextStatus)
    void load(nextStatus)
  }

  return (
    <AdminShell
      title="合作咨询"
      description="承接关于我们页提交的合作需求，可指派、备注，并转入规划咨询或数据服务。"
      topbarMetrics={[
        { label: '总线索', value: stats.total },
        { label: '待处理', value: stats.pending },
        { label: '已转化', value: stats.converted },
        { label: '已完成', value: stats.completed },
      ]}
    >
      <div className="grid h-[calc(100vh-144px)] min-h-[560px] grid-rows-[auto_1fr] gap-3 overflow-hidden">
        <section className="border border-line bg-white px-3 py-3">
          <div className="flex flex-wrap items-center gap-2">
            <div className="relative min-w-[220px] flex-1">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-soft" />
              <input value={keyword} onChange={(event) => setKeyword(event.target.value)} className="h-8 w-full rounded-[4px] border border-line pl-8 pr-3 text-xs font-bold outline-none focus:border-brand" placeholder="搜编号、机构、联系人、电话、需求" />
            </div>
            <select value={status} onChange={(event) => changeStatus(event.target.value)} className="h-8 rounded-[4px] border border-line px-2 text-xs font-bold">
              <option value="">全部状态</option>
              <option value="pending">待处理</option>
              <option value="completed">已完成</option>
            </select>
            <select value={assigneeId} onChange={(event) => setAssigneeId(event.target.value)} className="h-8 rounded-[4px] border border-line px-2 text-xs font-bold">
              <option value="">全部负责人</option>
              {staff.map((item) => <option key={item.id} value={item.id}>{item.displayName || item.phone || item.email}</option>)}
            </select>
          </div>
          {error && <div className="mt-2 rounded-[4px] bg-red-50 px-3 py-2 text-xs font-bold text-red-700">{error}</div>}
        </section>

        <section className="min-h-0 overflow-hidden border border-line bg-white">
          <div className="grid grid-cols-[140px_1fr_160px_116px_136px_92px] border-b border-line bg-bg px-3 py-2 text-[11px] font-extrabold text-soft">
            <span>编号</span><span>机构/需求</span><span>联系人</span><span>负责人</span><span>状态</span><span>操作</span>
          </div>
          <div className="h-full overflow-auto pb-8">
            {loading && <div className="px-4 py-10 text-sm font-bold text-muted">正在加载合作咨询...</div>}
            {!loading && filtered.length === 0 && <div className="px-4 py-10 text-sm font-bold text-muted">暂无匹配合作咨询</div>}
            {!loading && filtered.map((item) => {
              const assignee = item.assignedAccountId ? staffById.get(item.assignedAccountId) : null
              const href = targetHref(item)
              return (
                <div key={item.id} className="grid grid-cols-[140px_1fr_160px_116px_136px_92px] items-center border-b border-line px-3 py-2 text-sm hover:bg-bg/70">
                  <div>
                    <div className="font-extrabold text-brand">{item.requestNo}</div>
                    <div className="mt-0.5 text-[11px] font-bold text-soft">{new Date(item.createdAt).toLocaleDateString('zh-CN')}</div>
                  </div>
                  <div className="min-w-0 pr-3">
                    <div className="truncate font-extrabold text-ink">{item.organization}</div>
                    <div className="mt-0.5 truncate text-[11px] font-bold text-muted">{item.demand}</div>
                  </div>
                  <div className="text-xs font-bold leading-5 text-muted">
                    <div>{item.name}</div>
                    <div>{item.phone}</div>
                  </div>
                  <div className="truncate text-xs font-bold text-muted">{assignee?.displayName || '未指派'}</div>
                  <div>
                    <div className="text-xs font-extrabold text-ink">{statusLabel(item.status)}</div>
                    {href && <Link href={href} className="mt-0.5 inline-flex items-center gap-1 text-[11px] font-extrabold text-brand">已转化 <ArrowRight className="h-3 w-3" /></Link>}
                  </div>
                  <Link href={`/admin/site/cooperation/${item.requestNo}`} className="text-xs font-extrabold text-brand">详情</Link>
                </div>
              )
            })}
          </div>
        </section>
      </div>
    </AdminShell>
  )
}
