'use client'

import { useEffect, useMemo, useState } from 'react'
import type { FormEvent, ReactNode } from 'react'
import Link from 'next/link'
import { useParams } from 'next/navigation'
import { ArrowLeft, ExternalLink, RefreshCw } from 'lucide-react'
import { AdminMetricPanel } from '@/components/admin/AdminMetrics'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendAdminUserDetail, type BackendOrder, type BackendTask } from '@/lib/backend'
import { AdminUserForm, adminUserDraftPayload, draftFromAdminUser, emptyAdminUserDraft } from '../UserForm'

const levelLabel: Record<string, string> = {
  registered: '注册用户',
  junior: '初级会员',
  senior: '高级会员',
}

const accountStatusLabel: Record<string, string> = {
  active: '正常',
  disabled: '已禁用',
}

const orderStatusLabel: Record<string, string> = {
  pending_payment: '待支付',
  paid: '已支付',
  closed: '已关闭',
}

const expertStatusLabel: Record<string, string> = {
  pending: '待审核',
  approved: '申请通过',
  rejected: '申请驳回',
  withdrawn: '已撤回',
  draft: '草稿',
  published: '已发布',
  offline: '已下线',
}

function formatDate(value?: string | null) {
  if (!value) return '-'
  return new Date(value).toLocaleString('zh-CN')
}

function formatMoney(value?: number | null) {
  return `¥${Number(value || 0).toLocaleString('zh-CN')}`
}

function valueText(value?: ReactNode) {
  if (value === null || value === undefined || value === '') return '-'
  return value
}

function InfoGrid({ items }: { items: { label: string; value?: ReactNode }[] }) {
  return (
    <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
      {items.map((item) => (
        <div key={item.label} className="border border-line bg-bg px-3 py-2">
          <div className="text-[11px] font-bold text-soft">{item.label}</div>
          <div className="mt-1 break-words text-sm font-bold text-ink">{valueText(item.value)}</div>
        </div>
      ))}
    </div>
  )
}

function Section({ title, children, count }: { title: string; count?: number; children: ReactNode }) {
  return (
    <section className="border border-line bg-white p-5">
      <div className="mb-4 flex items-center justify-between gap-3">
        <h2 className="text-base font-extrabold text-ink">{title}</h2>
        {typeof count === 'number' && <span className="text-xs font-bold text-muted">{count} 条</span>}
      </div>
      {children}
    </section>
  )
}

function EmptyState({ label }: { label: string }) {
  return <div className="border border-dashed border-line px-4 py-8 text-center text-sm font-bold text-muted">{label}</div>
}

function OrderRow({ order }: { order: BackendOrder }) {
  return (
    <div className="border border-line px-4 py-3">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <Link href={`/admin/orders/${encodeURIComponent(order.id)}`} className="font-extrabold text-ink hover:text-brand">
            {order.orderNo}
          </Link>
          <div className="mt-1 text-xs font-bold text-muted">结算批次 {order.settlementNo || '-'} · {formatDate(order.createdAt)}</div>
        </div>
        <div className="text-right text-sm font-extrabold text-ink">
          <div>{formatMoney(order.totalAmount)}</div>
          <div className="mt-1 text-xs text-muted">{orderStatusLabel[order.status] || order.status}</div>
        </div>
      </div>
      <div className="mt-3 grid gap-2">
        {order.items.map((item) => (
          <div key={`${order.id}-${item.productId}`} className="flex flex-wrap items-center justify-between gap-2 bg-bg px-3 py-2 text-xs font-bold text-muted">
            <span>{item.titleSnapshot}</span>
            <span>{item.productType} · x{item.quantity} · {formatMoney(item.payableAmount)}</span>
          </div>
        ))}
      </div>
    </div>
  )
}

function TaskRow({ task }: { task: BackendTask }) {
  return (
    <div className="border border-line px-4 py-3">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <Link href={`/admin/tasks?selected=${encodeURIComponent(task.taskNo || task.id)}`} className="font-extrabold text-ink hover:text-brand">
            {task.taskNo || task.id}
          </Link>
          <div className="mt-1 text-xs font-bold text-muted">{task.productTitle || task.title} · 订单 {task.orderNo || '-'}</div>
        </div>
        <div className="text-right text-xs font-bold text-muted">
          <div>{task.status} · {task.priority}</div>
          <div className="mt-1">负责人 {task.assigneeName || '-'}</div>
        </div>
      </div>
      {(task.progressNote || task.resultSummary) && (
        <div className="mt-3 bg-bg px-3 py-2 text-xs font-bold leading-5 text-muted">
          {task.progressNote && <div>进度：{task.progressNote}</div>}
          {task.resultSummary && <div>结果：{task.resultSummary}</div>}
        </div>
      )}
    </div>
  )
}

export default function AdminUserDetailPage() {
  const params = useParams<{ id: string }>()
  const userKey = useMemo(() => decodeURIComponent(String(params.id || '')), [params.id])
  const [detail, setDetail] = useState<BackendAdminUserDetail | null>(null)
  const [draft, setDraft] = useState(emptyAdminUserDraft)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [saved, setSaved] = useState('')
  const [error, setError] = useState('')

  async function reload() {
    setLoading(true)
    try {
      const result = await backend.adminUser(userKey)
      setDetail(result)
      setDraft(draftFromAdminUser(result.user))
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '用户详情加载失败')
    } finally {
      setLoading(false)
    }
  }

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

  async function saveUser(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!detail) return
    setSaving(true)
    setSaved('')
    setError('')
    try {
      await backend.updateAdminUser(detail.user.id, adminUserDraftPayload(draft))
      setSaved('用户资料已更新')
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '用户保存失败')
    } finally {
      setSaving(false)
    }
  }

  const user = detail?.user
  const expert = detail?.expertProfile
  const application = detail?.expertApplication

  return (
    <AdminShell title="用户详情" description="查看用户个人资料、订单商品、服务进度、报名记录和专家档案。">
      <div className="mb-4 flex flex-wrap justify-between gap-3">
        <Link href="/admin/users" className="inline-flex h-10 items-center gap-2 rounded-[4px] border border-line px-4 text-sm font-bold text-muted hover:border-brand hover:text-brand">
          <ArrowLeft className="h-4 w-4" />
          返回用户列表
        </Link>
        <button type="button" onClick={() => void reload()} className="inline-flex h-10 items-center gap-2 rounded-[4px] border border-line px-4 text-sm font-bold text-muted hover:border-brand hover:text-brand">
          <RefreshCw className="h-4 w-4" />
          刷新
        </button>
      </div>

      {(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>
      )}

      {loading && <div className="border border-line bg-white px-5 py-10 text-sm font-bold text-muted">正在加载用户详情...</div>}
      {!loading && !detail && <EmptyState label="没有找到这个用户" />}

      {detail && user && (
        <div className="grid gap-4">
          <Section title={user.displayName || user.phone || user.wechatId || '未命名用户'}>
            <div className="mb-4 flex flex-wrap gap-2">
              <span className="rounded-[4px] bg-bg px-2 py-1 text-xs font-bold text-muted">通行证 {user.passportNo}</span>
              <span className={`rounded-[4px] px-2 py-1 text-xs font-bold ${user.status === 'disabled' ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>{accountStatusLabel[user.status || 'active']}</span>
              <span className="rounded-[4px] bg-brand-light px-2 py-1 text-xs font-bold text-brand">{levelLabel[user.membershipLevel] || user.membershipLevel}</span>
              {(user.expertProfileStatus || user.expertApplicationStatus) && <span className="rounded-[4px] bg-amber-50 px-2 py-1 text-xs font-bold text-amber-700">专家 {expertStatusLabel[user.expertProfileStatus || user.expertApplicationStatus || ''] || user.expertProfileStatus || user.expertApplicationStatus}</span>}
            </div>
            <InfoGrid items={[
              { label: '手机号', value: user.phone },
              { label: '微信号', value: user.wechatId },
              { label: '联系人电话', value: user.contactPhone },
              { label: '邮箱', value: user.email },
              { label: '所属机构', value: user.organization },
              { label: '职务/头衔', value: user.title },
              { label: '城市', value: user.city },
              { label: '地址', value: user.address },
              { label: '行业', value: user.industry },
              { label: '发票抬头', value: user.invoiceTitle },
              { label: '税号', value: user.taxNumber },
              { label: '收票邮箱', value: user.invoiceEmail },
              { label: '基础资料', value: user.onboardingCompleted ? '已完成' : '未完成' },
              { label: '创建时间', value: formatDate(user.createdAt) },
              { label: '最近登录', value: formatDate(user.lastLoginAt) },
            ]} />
          </Section>

          <AdminMetricPanel
            items={[
              { label: '订单', value: detail.orders.length },
              { label: '履约任务', value: detail.tasks.length },
              { label: '咨询/数据服务', value: detail.consultingRequests.length + detail.dataServiceRequests.length },
              { label: '报名/预约', value: detail.courseRegistrations.length + detail.eventRegistrations.length + detail.expertBookings.length },
            ]}
          />

          <Section title="编辑用户资料">
            <AdminUserForm draft={draft} setDraft={setDraft} saving={saving} submitLabel="保存用户资料" onSubmit={saveUser} />
          </Section>

          <Section title="订单与商品" count={detail.orders.length}>
            {detail.orders.length === 0 ? <EmptyState label="暂无订单" /> : <div className="grid gap-3">{detail.orders.map((order) => <OrderRow key={order.id} order={order} />)}</div>}
          </Section>

          <Section title="履约进度" count={detail.tasks.length}>
            {detail.tasks.length === 0 ? <EmptyState label="暂无履约任务" /> : <div className="grid gap-3">{detail.tasks.map((task) => <TaskRow key={task.id} task={task} />)}</div>}
          </Section>

          <Section title="咨询需求" count={detail.consultingRequests.length}>
            {detail.consultingRequests.length === 0 ? <EmptyState label="暂无咨询需求" /> : (
              <div className="grid gap-3">
                {detail.consultingRequests.map((item) => (
                  <div key={item.id} className="border border-line px-4 py-3">
                    <Link href={`/admin/consulting-requests?selected=${encodeURIComponent(item.requestNo)}`} className="font-extrabold text-ink hover:text-brand">{item.requestNo}</Link>
                    <div className="mt-1 text-xs font-bold text-muted">{item.company} · {item.direction || '-'} · {item.status} · 第 {item.currentStep} 步</div>
                    <div className="mt-2 text-xs font-bold leading-5 text-muted">{item.requirement || item.progressNote || '-'}</div>
                  </div>
                ))}
              </div>
            )}
          </Section>

          <Section title="数据服务" count={detail.dataServiceRequests.length}>
            {detail.dataServiceRequests.length === 0 ? <EmptyState label="暂无数据服务" /> : (
              <div className="grid gap-3">
                {detail.dataServiceRequests.map((item) => (
                  <div key={item.id} className="border border-line px-4 py-3">
                    <Link href={`/admin/data-service/requests?selected=${encodeURIComponent(item.requestNo)}`} className="font-extrabold text-ink hover:text-brand">{item.requestNo}</Link>
                    <div className="mt-1 text-xs font-bold text-muted">{item.dataTopic || item.quotedTitle || '-'} · {item.status} · 第 {item.currentStep} 步 · 报价 {formatMoney(item.quotedAmount)}</div>
                    <div className="mt-2 text-xs font-bold leading-5 text-muted">{item.requirement || item.expectedResult || item.progressNote || '-'}</div>
                  </div>
                ))}
              </div>
            )}
          </Section>

          <Section title="课程与活动报名" count={detail.courseRegistrations.length + detail.eventRegistrations.length}>
            {detail.courseRegistrations.length + detail.eventRegistrations.length === 0 ? <EmptyState label="暂无报名记录" /> : (
              <div className="grid gap-3 md:grid-cols-2">
                {detail.courseRegistrations.map((item) => (
                  <div key={item.id} className="border border-line px-4 py-3">
                    <div className="font-extrabold text-ink">{item.registrationNo || item.id}</div>
                    <div className="mt-1 text-xs font-bold text-muted">课程 · {item.course?.title || '-'} · {item.status} · 订单 {item.orderNo || '-'}</div>
                  </div>
                ))}
                {detail.eventRegistrations.map((item) => (
                  <div key={item.id} className="border border-line px-4 py-3">
                    <div className="font-extrabold text-ink">{item.registrationNo || item.id}</div>
                    <div className="mt-1 text-xs font-bold text-muted">活动 · {item.event?.title || '-'} · {item.status} · 订单 {item.orderNo || '-'}</div>
                  </div>
                ))}
              </div>
            )}
          </Section>

          <Section title="专家信息">
            {!expert && !application ? <EmptyState label="暂无专家资料或申请" /> : (
              <div className="grid gap-4">
                {expert && (
                  <div className="border border-line p-4">
                    <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
                      <div className="font-extrabold text-ink">{expert.name}</div>
                      <span className="rounded-[4px] bg-brand-light px-2 py-1 text-xs font-bold text-brand">{expertStatusLabel[expert.status] || expert.status}</span>
                    </div>
                    <InfoGrid items={[
                      { label: '专家编号', value: expert.passportNo },
                      { label: '机构', value: expert.organization },
                      { label: '头衔', value: expert.title },
                      { label: '方向', value: expert.directions?.join('、') || expert.specialties?.join('、') },
                      { label: '咨询价格', value: formatMoney(expert.priceAmount) },
                      { label: '专家分成', value: `${expert.shareRatio ?? '-'}%` },
                      { label: '接单状态', value: expert.acceptingOrders ? '接单中' : '暂停接单' },
                      { label: '预约次数', value: expert.bookingCount ?? 0 },
                      { label: '完成预约', value: expert.completedBookingCount ?? 0 },
                    ]} />
                    <div className="mt-3 grid gap-2 text-xs font-bold leading-5 text-muted">
                      {expert.projectExperience && <div className="whitespace-pre-wrap">项目经验：{expert.projectExperience}</div>}
                      {expert.representativeAchievements && <div className="whitespace-pre-wrap">代表成果：{expert.representativeAchievements}</div>}
                      {expert.homepageIntro && <div className="whitespace-pre-wrap">主页介绍：{expert.homepageIntro}</div>}
                    </div>
                  </div>
                )}
                {application && (
                  <div className="border border-line p-4">
                    <div className="mb-3 font-extrabold text-ink">专家申请 {application.applicationNo || application.id}</div>
                    <InfoGrid items={[
                      { label: '申请状态', value: expertStatusLabel[application.status] || application.status },
                      { label: '申请姓名', value: application.name },
                      { label: '申请机构', value: application.organization },
                      { label: '申请头衔', value: application.title },
                      { label: '申请方向', value: application.directions?.join('、') },
                      { label: '审核价格', value: formatMoney(application.reviewPriceAmount) },
                      { label: '审核分成', value: `${application.reviewShareRatio ?? '-'}%` },
                      { label: '附件数量', value: application.attachments?.length || application.attachmentFileIds?.length || 0 },
                      { label: '提交时间', value: formatDate(application.createdAt) },
                    ]} />
                    {application.rejectReason && <div className="mt-3 bg-red-50 px-3 py-2 text-xs font-bold text-red-700">驳回原因：{application.rejectReason}</div>}
                  </div>
                )}
              </div>
            )}
          </Section>

          <Section title="专家预约与收支" count={detail.expertBookings.length + detail.expertWithdrawals.length + detail.settlements.length}>
            {detail.expertBookings.length + detail.expertWithdrawals.length + detail.settlements.length === 0 ? <EmptyState label="暂无专家预约、提现或结算记录" /> : (
              <div className="grid gap-4">
                <div className="grid gap-3">
                  {detail.expertBookings.map((booking) => (
                    <div key={booking.id} className="border border-line px-4 py-3">
                      <Link href={`/admin/expert-bookings?selected=${encodeURIComponent(booking.bookingNo)}`} className="inline-flex items-center gap-1 font-extrabold text-ink hover:text-brand">
                        {booking.bookingNo}
                        <ExternalLink className="h-3.5 w-3.5" />
                      </Link>
                      <div className="mt-1 text-xs font-bold text-muted">{booking.expert?.name || '-'} · {booking.contactName} · {booking.status} · {formatDate(booking.startsAt)}</div>
                    </div>
                  ))}
                </div>
                <div className="grid gap-3 md:grid-cols-2">
                  {detail.settlements.map((settlement) => (
                    <div key={settlement.id} className="border border-line px-4 py-3">
                      <div className="font-extrabold text-ink">{settlement.settlementNo || settlement.id}</div>
                      <div className="mt-1 text-xs font-bold text-muted">{settlement.productTitle} · {settlement.status} · 专家 {formatMoney(settlement.expertShareAmount)} / 平台 {formatMoney(settlement.platformShareAmount)}</div>
                    </div>
                  ))}
                  {detail.expertWithdrawals.map((withdrawal) => (
                    <div key={withdrawal.id} className="border border-line px-4 py-3">
                      <Link href={`/admin/expert-withdrawals?selected=${encodeURIComponent(withdrawal.withdrawalNo || withdrawal.id)}`} className="font-extrabold text-ink hover:text-brand">{withdrawal.withdrawalNo || withdrawal.id}</Link>
                      <div className="mt-1 text-xs font-bold text-muted">{withdrawal.payeeName} · {formatMoney(withdrawal.amount)} · {withdrawal.status}</div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </Section>
        </div>
      )}
    </AdminShell>
  )
}
