'use client'

import Link from 'next/link'
import { use, useEffect, useMemo, useState } from 'react'
import { ArrowLeft, ArrowRight, CheckCircle2, Save } 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(type?: string | null, refId?: string | null) {
  if (!refId) return ''
  if (type === 'data_service') return `/admin/data-service/requests?selected=${encodeURIComponent(refId)}`
  return `/admin/consulting-requests?selected=${encodeURIComponent(refId)}`
}

export default function AdminCooperationRequestDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params)
  const [item, setItem] = useState<BackendCooperationRequest | null>(null)
  const [staff, setStaff] = useState<BackendStaffAccount[]>([])
  const [assignedAccountId, setAssignedAccountId] = useState('')
  const [processNote, setProcessNote] = useState('')
  const [convertType, setConvertType] = useState<'consulting' | 'data_service'>('consulting')
  const [message, setMessage] = useState('')
  const [error, setError] = useState('')
  const [saving, setSaving] = useState(false)

  async function load() {
    try {
      const [request, staffResult] = await Promise.all([
        backend.adminCooperationRequest(id),
        backend.adminStaffAccounts({ status: 'active' }).catch(() => ({ items: [] as BackendStaffAccount[] })),
      ])
      setItem(request)
      setAssignedAccountId(request.assignedAccountId || '')
      setProcessNote(request.processNote || '')
      setStaff(staffResult.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '合作咨询详情加载失败')
    }
  }

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

  const assignedStaff = useMemo(() => staff.find((account) => account.id === assignedAccountId), [assignedAccountId, staff])
  const convertedHref = targetHref(item?.convertedType, item?.convertedRefId)

  async function saveProcess(nextStatus?: BackendCooperationRequest['status']) {
    setSaving(true)
    setError('')
    try {
      const updated = await backend.updateCooperationRequest(id, {
        assignedAccountId: assignedAccountId || null,
        processNote,
        status: nextStatus,
      })
      setItem(updated)
      setMessage('处理信息已保存')
    } catch (err) {
      setError(err instanceof Error ? err.message : '保存处理信息失败')
    } finally {
      setSaving(false)
    }
  }

  async function convert() {
    if (!item) return
    setSaving(true)
    setError('')
    try {
      const result = await backend.convertCooperationRequest(id, {
        targetType: convertType,
        assignedAccountId: assignedAccountId || null,
        processNote,
        note: processNote,
      })
      setItem(result.cooperation)
      setMessage(`已转入${convertType === 'data_service' ? '数据服务' : '规划咨询'}：${result.target.requestNo || result.target.id}`)
    } catch (err) {
      setError(err instanceof Error ? err.message : '转化失败')
    } finally {
      setSaving(false)
    }
  }

  async function complete() {
    setSaving(true)
    setError('')
    try {
      setItem(await backend.completeCooperationRequest(id))
      setMessage('合作咨询已标记完成')
    } catch (err) {
      setError(err instanceof Error ? err.message : '标记完成失败')
    } finally {
      setSaving(false)
    }
  }

  return (
    <AdminShell title="合作咨询详情" description="处理关于我们页提交的合作线索，支持指派、备注、转规划咨询或转数据服务。">
      <div className="grid h-[calc(100vh-116px)] min-h-[620px] grid-rows-[auto_1fr] gap-3 overflow-hidden">
        <div className="flex flex-wrap items-center justify-between gap-2">
          <Link href="/admin/site/cooperation" 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">
            <ArrowLeft className="h-3.5 w-3.5" />
            返回列表
          </Link>
          {(message || error) && <div className={`rounded-[4px] px-3 py-2 text-xs font-bold ${error ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>{error || message}</div>}
        </div>

        {!item ? (
          <div className="grid place-items-center border border-line bg-white text-sm font-bold text-muted">正在加载...</div>
        ) : (
          <div className="grid min-h-0 gap-3 overflow-hidden lg:grid-cols-[minmax(0,1fr)_340px]">
            <section className="min-h-0 overflow-auto border border-line bg-white">
              <div className="border-b border-line px-4 py-3">
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div>
                    <div className="text-base font-extrabold text-ink">{item.organization}</div>
                    <div className="mt-1 text-xs font-bold text-soft">{item.requestNo} · {new Date(item.createdAt).toLocaleString('zh-CN')}</div>
                  </div>
                  <span className="rounded-[4px] bg-brand-light px-2.5 py-1 text-xs font-extrabold text-brand">{statusLabel(item.status)}</span>
                </div>
              </div>

              <div className="grid gap-0 divide-y divide-line text-sm">
                <DetailRow label="联系人" value={`${item.name} / ${item.phone}`} />
                <DetailRow label="所在机构" value={item.organization} />
                <DetailRow label="账号信息" value={`${item.user?.displayName || '-'} · ${item.user?.phone || '-'} · ${item.user?.membershipLevel || '-'}`} />
                <div className="grid gap-3 px-4 py-4 md:grid-cols-[96px_1fr]">
                  <div className="text-soft">合作需求</div>
                  <div className="whitespace-pre-wrap font-bold leading-7 text-text-body">{item.demand}</div>
                </div>
                {convertedHref && (
                  <div className="grid gap-3 px-4 py-4 md:grid-cols-[96px_1fr]">
                    <div className="text-soft">转化结果</div>
                    <Link href={convertedHref} className="inline-flex w-fit items-center gap-1.5 text-sm font-extrabold text-brand">
                      {item.convertedType === 'data_service' ? '数据服务需求' : '规划咨询需求'} · {item.convertedRefId}
                      <ArrowRight className="h-3.5 w-3.5" />
                    </Link>
                  </div>
                )}
              </div>
            </section>

            <aside className="min-h-0 space-y-3 overflow-auto">
              <section className="border border-line bg-white p-3">
                <div className="text-sm font-extrabold text-ink">处理信息</div>
                <label className="mt-3 block">
                  <span className="mb-1 block text-xs font-extrabold text-soft">负责人</span>
                  <select value={assignedAccountId} onChange={(event) => setAssignedAccountId(event.target.value)} className="h-9 w-full rounded-[4px] border border-line px-2 text-sm">
                    <option value="">未指派</option>
                    {staff.map((account) => <option key={account.id} value={account.id}>{account.displayName || account.phone || account.email}</option>)}
                  </select>
                </label>
                {assignedStaff && <div className="mt-1 text-[11px] font-bold text-soft">{assignedStaff.roleName || assignedStaff.positionTitle || assignedStaff.role}</div>}
                <label className="mt-3 block">
                  <span className="mb-1 block text-xs font-extrabold text-soft">处理备注</span>
                  <textarea value={processNote} onChange={(event) => setProcessNote(event.target.value)} rows={5} className="w-full rounded-[4px] border border-line p-2 text-sm leading-6" placeholder="记录沟通、判断、下一步动作" />
                </label>
                <button type="button" onClick={() => void saveProcess()} disabled={saving} className="mt-3 inline-flex h-8 w-full items-center justify-center gap-1.5 rounded-[4px] border border-brand bg-white text-xs font-extrabold text-brand hover:bg-brand-light disabled:opacity-60">
                  <Save className="h-3.5 w-3.5" />
                  保存处理信息
                </button>
              </section>

              <section className="border border-line bg-white p-3">
                <div className="text-sm font-extrabold text-ink">转入业务流程</div>
                <div className="mt-3 grid grid-cols-2 gap-2">
                  {[
                    ['consulting', '规划咨询'],
                    ['data_service', '数据服务'],
                  ].map(([value, label]) => (
                    <button key={value} type="button" onClick={() => setConvertType(value as 'consulting' | 'data_service')} className={`h-8 rounded-[4px] border px-2 text-xs font-extrabold ${convertType === value ? 'border-brand bg-brand-light text-brand' : 'border-line text-muted hover:border-brand hover:text-brand'}`}>
                      {label}
                    </button>
                  ))}
                </div>
                <button type="button" onClick={() => void convert()} disabled={saving || Boolean(item.convertedRefId)} className="mt-3 h-8 w-full rounded-[4px] bg-ink text-xs font-extrabold text-white hover:bg-brand disabled:bg-line-dark">
                  {item.convertedRefId ? '已转化' : '确认转入'}
                </button>
                <p className="mt-2 text-[11px] font-bold leading-5 text-soft">转化会保留原合作咨询编号，并把联系人、机构、需求带入目标单据。</p>
              </section>

              <section className="border border-line bg-white p-3">
                <div className="text-sm font-extrabold text-ink">完成处理</div>
                {item.completedAt && <div className="mt-2 text-xs font-bold text-soft">完成时间：{new Date(item.completedAt).toLocaleString('zh-CN')}</div>}
                <button type="button" onClick={() => void complete()} disabled={saving || item.status === 'completed'} className="mt-3 inline-flex h-8 w-full items-center justify-center gap-1.5 rounded-[4px] bg-brand text-xs font-extrabold text-white disabled:bg-line-dark">
                  <CheckCircle2 className="h-3.5 w-3.5" />
                  标记已完成
                </button>
              </section>
            </aside>
          </div>
        )}
      </div>
    </AdminShell>
  )
}

function DetailRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="grid gap-3 px-4 py-3 md:grid-cols-[96px_1fr]">
      <div className="text-soft">{label}</div>
      <div className="font-bold text-text-body">{value}</div>
    </div>
  )
}
