'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { Pencil, Plus, SlidersHorizontal } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendExpert, type BackendExpertDirection, yuan } from '@/lib/backend'

const statusLabel: Record<string, string> = {
  draft: '草稿',
  published: '已发布',
  offline: '已下线',
}

export default function AdminExpertsPage() {
  const [experts, setExperts] = useState<BackendExpert[]>([])
  const [directions, setDirections] = useState<BackendExpertDirection[]>([])
  const [direction, setDirection] = useState('')
  const [status, setStatus] = useState('')
  const [keyword, setKeyword] = useState('')
  const [saved, setSaved] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)
  const summary = useMemo(() => ({
    total: experts.length,
    published: experts.filter((item) => item.status === 'published').length,
    accepting: experts.filter((item) => item.acceptingOrders).length,
    offline: experts.filter((item) => item.status === 'offline').length,
  }), [experts])
  const filteredExperts = useMemo(() => {
    const word = keyword.trim().toLowerCase()
    if (!word) return experts
    return experts.filter((item) => [
      item.name,
      item.title,
      item.organization,
      item.user?.phone,
      item.contactPhone,
      item.passportNo,
      item.user?.passportNo,
      ...(item.directions || item.specialties || []),
    ].filter(Boolean).join(' ').toLowerCase().includes(word))
  }, [experts, keyword])

  async function reload(nextDirection = direction, nextStatus = status) {
    setLoading(true)
    try {
      const [expertResult, directionResult] = await Promise.all([
        backend.adminExperts({ direction: nextDirection, status: nextStatus }),
        backend.adminExpertDirections(),
      ])
      setExperts(expertResult.items)
      setDirections(directionResult.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '专家资源库加载失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    const timer = window.setTimeout(() => {
      void reload('', '')
    }, 0)
    return () => window.clearTimeout(timer)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  async function updateExpert(item: BackendExpert, patch: Partial<BackendExpert>) {
    try {
      await backend.updateAdminExpert(item.id, { ...item, ...patch })
      setSaved('专家信息已更新')
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '专家更新失败')
    }
  }

  async function changeStatus(item: BackendExpert, action: 'publish' | 'offline' | 'delete') {
    try {
      if (action === 'publish') await backend.publishExpert(item.id)
      if (action === 'offline') await backend.offlineExpert(item.id)
      if (action === 'delete') {
        const confirmed = window.confirm('确定删除该专家吗？删除后用户端不再展示，历史订单仍保留快照。')
        if (!confirmed) return
        await backend.deleteAdminExpert(item.id)
      }
      setSaved(action === 'delete' ? '专家已删除' : '专家状态已更新')
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '操作失败')
    }
  }

  return (
    <AdminShell
      title="专家资源库"
      description="维护专家资料、方向、价格分成、接单状态和用户端展示。"
      topbarMetrics={[
        { label: '专家', value: summary.total },
        { label: '已发布', value: summary.published },
        { label: '接单中', value: summary.accepting },
        { label: '已下线', value: summary.offline },
      ]}
    >
      {(saved || error) && (
        <div className={`mb-3 rounded-[4px] px-4 py-3 text-sm font-bold ${error ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>
          {error || saved}
        </div>
      )}

      <div className="mb-2 flex flex-col gap-2 lg:flex-row lg:items-center lg:justify-between">
        <div className="flex flex-col gap-2 md:flex-row">
          <input
            value={keyword}
            onChange={(event) => setKeyword(event.target.value)}
            placeholder="搜姓名、机构、手机号、方向"
            className="h-8 rounded-[4px] border border-line bg-white px-3 text-xs font-bold outline-none focus:border-brand md:w-64"
          />
          <select
            value={direction}
            onChange={(event) => {
              setDirection(event.target.value)
              void reload(event.target.value, status)
            }}
            className="h-8 rounded-[4px] border border-line bg-white px-3 text-xs font-bold outline-none focus:border-brand"
          >
            <option value="">全部方向</option>
            {directions.map((item) => <option key={item.id} value={item.name}>{item.groupName} · {item.name}</option>)}
          </select>
          <select
            value={status}
            onChange={(event) => {
              setStatus(event.target.value)
              void reload(direction, event.target.value)
            }}
            className="h-8 rounded-[4px] border border-line bg-white px-3 text-xs font-bold outline-none focus:border-brand"
          >
            <option value="">全部状态</option>
            <option value="published">已发布</option>
            <option value="draft">草稿</option>
            <option value="offline">已下线</option>
          </select>
        </div>
        <div className="flex flex-wrap gap-2">
          <Link href="/admin/experts/directions" className="inline-flex h-8 items-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">
            <SlidersHorizontal className="h-3.5 w-3.5" />
            方向管理
          </Link>
          <Link href="/admin/experts/new" className="inline-flex h-8 items-center gap-1.5 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white hover:bg-brand">
            <Plus className="h-3.5 w-3.5" />
            新增专家
          </Link>
        </div>
      </div>

      <section className="h-[calc(100vh-198px)] min-h-[500px] overflow-hidden border border-line bg-white">
        <div className="grid grid-cols-[minmax(260px,1fr)_140px_100px_96px_220px] border-b border-line px-3 py-2 text-xs font-extrabold text-soft">
          <span>专家</span><span>价格分成</span><span>状态</span><span>订单</span><span>操作</span>
        </div>
        <div className="h-[calc(100%-33px)] overflow-y-auto">
        {loading && <div className="px-5 py-8 text-sm font-bold text-muted">正在加载专家...</div>}
        {!loading && filteredExperts.length === 0 && <div className="px-5 py-8 text-sm font-bold text-muted">暂无专家</div>}
        {!loading && filteredExperts.map((item) => (
          <div key={item.id} className="grid grid-cols-[minmax(260px,1fr)_140px_100px_96px_220px] items-center border-b border-line px-3 py-3 text-sm hover:bg-bg">
            <div className="min-w-0">
              <div className="truncate font-extrabold text-ink">{item.name} · {item.title || '未填写职务'}</div>
              <div className="mt-1 truncate text-xs font-bold text-muted">{item.organization || '未填写机构'} · 手机 {item.user?.phone || item.contactPhone || '未绑定'} · 通行证 {item.passportNo || item.user?.passportNo || '未绑定'}</div>
              <div className="mt-1.5 flex flex-wrap gap-1">
                {(item.directions || item.specialties || []).map((current) => (
                  <span key={current} className="rounded-[4px] bg-bg px-2 py-1 text-[11px] font-bold text-muted">{current}</span>
                ))}
              </div>
            </div>
            <div className="font-bold text-muted">
              <div>¥{yuan(item.priceAmount).toLocaleString()}/小时</div>
              <div className="mt-1">分成 {item.shareRatio ?? 80}%</div>
            </div>
            <div className="font-bold text-muted">
              <div>{statusLabel[item.status] || item.status}</div>
              <div className="mt-1">{item.acceptingOrders ? '接单中' : '停止接单'}</div>
            </div>
            <div className="font-bold text-muted">
              <div>总计 {item.bookingCount || 0}</div>
              <div className="mt-1">完成 {item.completedBookingCount || 0}</div>
            </div>
            <div className="flex flex-wrap gap-2">
              <Link href={`/admin/experts/${item.id}/edit`} className="inline-flex items-center gap-1 text-xs font-extrabold text-brand">
                <Pencil className="h-3.5 w-3.5" />
                编辑
              </Link>
              {item.status !== 'published' && <button type="button" onClick={() => void changeStatus(item, 'publish')} className="text-xs font-extrabold text-ink">发布</button>}
              {item.status === 'published' && <button type="button" onClick={() => void changeStatus(item, 'offline')} className="text-xs font-extrabold text-ink">下线</button>}
              <button type="button" onClick={() => void updateExpert(item, { acceptingOrders: !item.acceptingOrders })} className="text-xs font-extrabold text-ink">
                {item.acceptingOrders ? '停止接单' : '恢复接单'}
              </button>
              <button type="button" onClick={() => void changeStatus(item, 'delete')} className="text-xs font-extrabold text-red-600">删除</button>
            </div>
          </div>
        ))}
        </div>
      </section>
    </AdminShell>
  )
}
