'use client'

import Link from 'next/link'
import { useParams, useRouter } from 'next/navigation'
import { ChevronRight, ClipboardList } from 'lucide-react'
import { useEffect, useState } from 'react'
import { useApp } from '@/components/providers/AppProvider'
import { assetUrl, backend, type BackendConsultingRequest, yuan } from '@/lib/backend'

function formatDate(value: string) {
  return new Date(value).toLocaleString('zh-CN')
}

const consultingSteps = ['提交需求', '受理', '沟通', '方案/报价', '付款', '服务中', '完成']

function statusLabel(status: BackendConsultingRequest['status']) {
  if (status === 'assigned') return '已分配顾问'
  if (status === 'communicating') return '沟通中'
  if (status === 'planning') return '方案制定中'
  if (status === 'proposal_ready') return '待确认报价'
  if (status === 'pending_payment') return '待支付'
  if (status === 'in_service') return '服务中'
  if (status === 'completed') return '已完成'
  if (status === 'cancelled') return '已取消'
  return '待受理'
}

function stepIndex(status: BackendConsultingRequest['status']) {
  if (status === 'assigned') return 1
  if (status === 'communicating') return 2
  if (status === 'planning' || status === 'proposal_ready') return 3
  if (status === 'pending_payment') return 4
  if (status === 'in_service') return 5
  if (status === 'completed') return 6
  return 0
}

export default function AccountConsultingDetailPage() {
  const params = useParams<{ id: string }>()
  const router = useRouter()
  const { user, token } = useApp()
  const [request, setRequest] = useState<BackendConsultingRequest | null>(null)
  const [loading, setLoading] = useState(true)
  const [loadError, setLoadError] = useState('')
  const [paying, setPaying] = useState(false)

  useEffect(() => {
    if (!token || !params.id) return
    let mounted = true
    setLoading(true)
    backend.accountConsultingRequests(token)
      .then((result) => {
        if (!mounted) return
        setRequest((result.items || []).find((item) => item.id === params.id || item.requestNo === params.id) || null)
        setLoadError('')
      })
      .catch((err) => {
        if (mounted) setLoadError(err instanceof Error ? err.message : '咨询记录加载失败')
      })
      .finally(() => {
        if (mounted) setLoading(false)
      })
    return () => {
      mounted = false
    }
  }, [params.id, token])

  if (!user) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center">
          <h1 className="text-2xl font-extrabold text-ink">尚未登录</h1>
          <Link href="/login?redirect=%2Faccount" className="mt-7 inline-flex rounded-[4px] bg-brand px-6 py-3 text-sm font-extrabold text-white">去登录</Link>
        </div>
      </section>
    )
  }

  if (loading) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center text-sm font-bold text-muted">
          正在加载咨询记录...
        </div>
      </section>
    )
  }

  if (!request) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center">
          <h1 className="text-2xl font-extrabold text-ink">咨询记录不存在</h1>
          {loadError && <p className="mt-3 text-sm font-bold text-muted">{loadError}</p>}
          <Link href="/account/consulting" className="mt-7 inline-flex rounded-[4px] bg-brand px-6 py-3 text-sm font-extrabold text-white">返回我的咨询</Link>
        </div>
      </section>
    )
  }

  const fields = [
    ['单位名称', request.company],
    ['组织类型', request.organizationType],
    ['联系人', request.contactName],
    ['联系电话', request.contactPhone],
    ['邮箱', request.email || '未填写'],
    ['所在城市', request.city || '未填写'],
    ['咨询方向', request.direction],
    ['所属行业', request.industry || '未填写'],
    ['项目阶段', request.projectStage],
    ['沟通紧急度', request.urgency],
    ['预算范围', request.budgetRange],
    ['期望启动时间', request.expectedStart],
    ['方便联系时间', request.preferredContactTime || '未填写'],
    ['受理部门', request.owner],
    ['负责人', request.assigneeName || '待分配'],
  ]
  const canPay = request.status === 'proposal_ready' || request.status === 'pending_payment'
  const hasQuote = request.chargeRequired || request.quotedTitle || request.quotedAmount
  const activeStep = Math.max(stepIndex(request.status), Number(request.currentStep || 0))

  async function payQuote() {
    if (!request || paying) return
    setPaying(true)
    try {
      router.push(`/checkout?consultingRequestId=${encodeURIComponent(request.id)}`)
    } finally {
      setPaying(false)
    }
  }

  return (
    <section className="bg-bg py-8">
      <div className="mx-auto max-w-[1080px] px-6">
        <nav className="mb-5 flex items-center gap-2 text-sm font-bold text-soft">
          <Link href="/account" className="text-muted hover:text-brand">个人中心</Link>
          <ChevronRight className="h-4 w-4" />
          <Link href="/account/consulting" className="text-muted hover:text-brand">我的咨询</Link>
          <ChevronRight className="h-4 w-4" />
          <span className="text-ink">{request.direction}</span>
        </nav>

        <div className="grid gap-8 lg:grid-cols-[1fr_340px]">
          <div className="rounded-[4px] border border-line bg-white">
            <div className="border-b border-line px-6 py-5">
              <div className="flex items-center gap-2 text-sm font-bold text-brand">
                <ClipboardList className="h-4 w-4" />
                {request.id}
              </div>
              <h1 className="mt-2 text-2xl font-extrabold text-ink">{request.company} · {request.direction}</h1>
              <div className="mt-1 text-sm text-muted">提交于 {formatDate(request.createdAt)} · {statusLabel(request.status)}</div>
            </div>

            <div className="p-6">
              <h2 className="text-lg font-extrabold text-ink">需求信息</h2>
              <div className="mt-4 overflow-hidden border-y border-line">
                {fields.map(([label, value]) => (
                  <div key={label} className="grid border-b border-line last:border-b-0 md:grid-cols-[160px_1fr]">
                    <div className="bg-bg/45 px-4 py-3 text-xs font-bold text-muted">{label}</div>
                    <div className="px-4 py-3 text-sm font-bold leading-6 text-ink">{value}</div>
                  </div>
                ))}
              </div>

              <div className="mt-8 space-y-7">
                <section className="border-t border-line pt-6">
                  <h2 className="text-lg font-extrabold text-ink">当前现状</h2>
                  <p className="mt-3 text-sm leading-7 text-muted">{request.currentSituation}</p>
                </section>
                <section className="border-t border-line pt-6">
                  <h2 className="text-lg font-extrabold text-ink">希望解决的问题</h2>
                  <p className="mt-3 text-sm leading-7 text-muted">{request.requirement}</p>
                </section>
                <section className="border-t border-line pt-6">
                  <h2 className="text-lg font-extrabold text-ink">期望成果</h2>
                  <p className="mt-3 text-sm leading-7 text-muted">{request.goals || '未填写'}</p>
                </section>
                <section className="border-t border-line pt-6">
                  <h2 className="text-lg font-extrabold text-ink">顾问进度</h2>
                  <p className="mt-3 whitespace-pre-wrap text-sm leading-7 text-muted">{request.progressNote || '顾问受理后会在这里同步当前进度。'}</p>
                </section>
                {request.solutionSummary && (
                  <section className="border-t border-line pt-6">
                    <h2 className="text-lg font-extrabold text-ink">方案摘要</h2>
                    <p className="mt-3 whitespace-pre-wrap text-sm leading-7 text-muted">{request.solutionSummary}</p>
                  </section>
                )}
                {request.finalSummary && (
                  <section className="border-t border-line pt-6">
                    <h2 className="text-lg font-extrabold text-ink">最终方案反馈</h2>
                    <p className="mt-3 whitespace-pre-wrap text-sm leading-7 text-muted">{request.finalSummary}</p>
                    {request.finalFileUrl && (
                      <a href={assetUrl(request.finalFileUrl)} target="_blank" rel="noreferrer" className="mt-4 inline-flex h-10 items-center rounded-[4px] border border-line px-5 text-sm font-extrabold text-muted hover:border-brand hover:text-brand">查看附件</a>
                    )}
                  </section>
                )}
              </div>
            </div>
          </div>

          <aside className="h-fit rounded-[4px] border border-line bg-white p-6">
            <div className="text-lg font-extrabold text-ink">处理进度</div>
            <div className="mt-5 space-y-4">
              {consultingSteps.map((step, index) => (
                <div key={step} className="flex gap-3">
                  <div className={`mt-0.5 grid h-6 w-6 shrink-0 place-items-center rounded-full text-xs font-bold ${index <= activeStep ? 'bg-brand text-white' : 'bg-bg text-muted'}`}>{index + 1}</div>
                  <div>
                    <div className={`text-sm font-bold ${index <= activeStep ? 'text-ink' : 'text-muted'}`}>{step}</div>
                  </div>
                </div>
              ))}
            </div>
            <div className="mt-6 rounded-[4px] bg-brand-light p-4 text-xs leading-6 text-brand">
              研究院顾问会按你填写的联系方式沟通需求；收费咨询会先展示报价，确认支付后进入服务执行。
            </div>
            {hasQuote && (
              <div className="mt-5 rounded-[4px] border border-line bg-white p-4">
                <div className="text-sm font-extrabold text-ink">咨询报价</div>
                <div className="mt-2 text-base font-extrabold text-brand">{request.quotedTitle || '规划咨询服务报价'}</div>
                {Number(request.originalQuotedAmount || 0) > 0 && (
                  <div className="mt-2 text-xs font-bold text-muted">原始报价：¥{yuan(request.originalQuotedAmount || 0).toLocaleString()}</div>
                )}
                {Number(request.membershipDiscountAmount || 0) > 0 && (
                  <div className="mt-1 text-xs font-bold text-green">会员人工优惠：- ¥{yuan(request.membershipDiscountAmount || 0).toLocaleString()}</div>
                )}
                <div className="mt-2 text-2xl font-extrabold text-ink">{request.quotedAmount ? `¥${yuan(request.quotedAmount).toLocaleString()}` : '金额待确认'}</div>
                {request.membershipDiscountNote && <p className="mt-2 whitespace-pre-wrap text-xs font-bold leading-6 text-green">{request.membershipDiscountNote}</p>}
                <p className="mt-3 whitespace-pre-wrap text-xs font-bold leading-6 text-muted">{request.quotedNote || '顾问会补充报价范围、服务内容和交付说明。'}</p>
                {request.paidAt ? (
                  <div className="mt-4 rounded-[4px] bg-green-50 px-3 py-2 text-xs font-extrabold text-green">已支付，服务执行中</div>
                ) : canPay ? (
                  <button type="button" onClick={() => void payQuote()} disabled={paying} className="mt-4 h-10 w-full rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white disabled:opacity-60">
                    {paying ? '正在提交...' : '确认并支付'}
                  </button>
                ) : (
                  <div className="mt-4 rounded-[4px] bg-bg px-3 py-2 text-xs font-bold text-muted">报价状态：{statusLabel(request.status)}</div>
                )}
              </div>
            )}
          </aside>
        </div>
      </div>
    </section>
  )
}
