'use client'

import { useMemo, useState } from 'react'
import type { FormEvent } from 'react'
import { useRouter } from 'next/navigation'
import { ArrowRight, Loader2, Search, X } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendBusinessSearchResult } from '@/lib/backend'

const quickPrefixes = [
  ['ORD', '订单'],
  ['PAY', '支付'],
  ['CON', '咨询'],
  ['DSR', '数据'],
  ['EXB', '预约'],
  ['REG', '报名'],
  ['TSK', '交付'],
  ['STL', '分账'],
  ['WDR', '提现'],
  ['EXA', '专家申请'],
  ['COO', '合作'],
] as const

function normalizeQuery(value: string) {
  return value.trim().toUpperCase().replace(/\s+/g, '')
}

export default function AdminBusinessSearchPage() {
  const router = useRouter()
  const [query, setQuery] = useState('')
  const [results, setResults] = useState<BackendBusinessSearchResult[]>([])
  const [loading, setLoading] = useState(false)
  const [searched, setSearched] = useState(false)
  const [error, setError] = useState('')
  const normalizedQuery = useMemo(() => normalizeQuery(query), [query])

  async function runSearch(nextQuery = normalizedQuery) {
    if (!nextQuery) {
      setResults([])
      setSearched(false)
      return
    }
    setLoading(true)
    setSearched(true)
    setError('')
    try {
      const result = await backend.businessSearch(nextQuery)
      setResults(result.items)
      if (result.items.length === 1) {
        router.push(result.items[0].href)
      }
    } catch (err) {
      setResults([])
      setError(err instanceof Error ? err.message : '编号搜索失败')
    } finally {
      setLoading(false)
    }
  }

  function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    void runSearch()
  }

  return (
    <AdminShell title="编号搜索" description="输入业务编号直达对应订单、咨询、数据服务、专家预约、报名、分账或合作记录。">
      <div className="flex h-[calc(100vh-88px)] flex-col gap-2 overflow-hidden">
        <section className="shrink-0 border border-line bg-white p-2.5">
          <form onSubmit={submit} className="flex flex-col gap-2 lg:flex-row">
            <div className="relative min-w-0 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={query}
                onChange={(event) => setQuery(event.target.value.toUpperCase())}
                autoFocus
                placeholder="输入编号，如 ORD20260603000001"
                className="h-9 w-full rounded-[4px] border border-line pl-9 pr-9 text-sm font-extrabold text-ink outline-none focus:border-brand"
              />
              {query && (
                <button type="button" onClick={() => { setQuery(''); setResults([]); setSearched(false); setError('') }} className="absolute right-3 top-1/2 grid h-6 w-6 -translate-y-1/2 place-items-center text-soft hover:text-ink" aria-label="清空">
                  <X className="h-4 w-4" />
                </button>
              )}
            </div>
            <button disabled={loading || !normalizedQuery} className="inline-flex h-9 items-center justify-center gap-2 rounded-[4px] bg-ink px-4 text-xs font-extrabold text-white disabled:opacity-55">
              {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}
              查询
            </button>
          </form>

          <div className="mt-2 grid gap-1.5 sm:grid-cols-3 lg:grid-cols-6 xl:grid-cols-11">
            {quickPrefixes.map(([prefix, label]) => (
              <button key={prefix} type="button" onClick={() => setQuery(prefix)} className="grid grid-cols-[42px_1fr] items-center rounded-[4px] border border-line px-2 py-1 text-left text-[11px] font-bold text-muted hover:border-brand hover:text-brand">
                <span className="font-extrabold text-ink">{prefix}</span>
                <span className="truncate">{label}</span>
              </button>
            ))}
          </div>
        </section>

        <section className="flex min-h-0 flex-1 flex-col border border-line bg-white">
          <div className="flex h-8 shrink-0 items-center justify-between border-b border-line px-3">
            <div className="text-sm font-extrabold text-ink">搜索结果</div>
            <div className="text-[11px] font-bold text-soft">{searched ? `${results.length} 条` : '等待输入'}</div>
          </div>
          <div className="min-h-0 flex-1 overflow-auto">
            {error && <div className="px-3 py-4 text-xs font-bold text-red-700">{error}</div>}
            {!error && loading && <div className="px-3 py-8 text-xs font-bold text-muted">正在查询...</div>}
            {!error && !loading && searched && results.length === 0 && <div className="px-3 py-8 text-xs font-bold text-muted">没有找到这个编号</div>}
            {!error && !loading && !searched && <div className="px-3 py-8 text-xs font-bold text-muted">输入完整编号后查询</div>}
            {!error && !loading && results.length > 0 && (
              <div className="divide-y divide-line">
                {results.map((item) => (
                  <button
                    key={`${item.type}-${item.number}`}
                    type="button"
                    onClick={() => router.push(item.href)}
                    className="grid w-full gap-2 px-3 py-2 text-left hover:bg-bg md:grid-cols-[150px_1fr_108px] md:items-center"
                  >
                    <div>
                      <div className="text-xs font-extrabold text-ink">{item.number}</div>
                      <div className="mt-0.5 text-[11px] font-bold text-brand">{item.label}</div>
                    </div>
                    <div className="min-w-0">
                      <div className="truncate text-xs font-extrabold text-ink">{item.title || '-'}</div>
                      <div className="mt-0.5 truncate text-[11px] font-bold text-muted">{item.description || '-'}</div>
                    </div>
                    <div className="flex items-center justify-end gap-2 text-[11px] font-extrabold text-muted">
                      <span className="truncate">{item.status || '-'}</span>
                      <ArrowRight className="h-4 w-4 text-soft" />
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>
        </section>
      </div>
    </AdminShell>
  )
}
