'use client'

import Link from 'next/link'
import { useEffect, useState } from 'react'
import { AccountEmptyState } from '@/components/account/AccountEmptyState'
import { AccountAuthPrompt } from '@/components/account/AccountAuthPrompt'
import { formatAccountDateTime } from '@/components/account/account-utils'
import { useApp } from '@/components/providers/AppProvider'
import { backend, type BackendConsultingRequest } from '@/lib/backend'

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 statusTone(status: BackendConsultingRequest['status']) {
  if (status === 'completed') return 'bg-brand/10 text-brand'
  if (status === 'pending') return 'bg-bg text-muted'
  if (['assigned', 'communicating', 'planning', 'proposal_ready', 'pending_payment', 'in_service'].includes(status)) return 'bg-amber-50 text-amber-700'
  return 'bg-brand/10 text-brand'
}

export default function AccountConsultingPage() {
  const { user, token } = useApp()
  const [consultingRequests, setConsultingRequests] = useState<BackendConsultingRequest[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

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

  if (!user) return <AccountAuthPrompt message="登录后可查看规划咨询需求和处理进度。" />
  if (loading) return <div className="rounded-[4px] border border-line bg-white p-8 text-sm font-bold text-muted">正在加载咨询记录...</div>

  return (
    <div>
      {error && <div className="mb-4 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}
      <section>
        {consultingRequests.length === 0 ? (
          <AccountEmptyState title="还没有规划咨询需求" description="提交规划咨询需求后，顾问分配、沟通进度和方案记录会显示在这里。" actionLabel="提交规划咨询" actionHref="/consulting/apply" />
        ) : (
          <div className="overflow-hidden rounded-[4px] border border-line bg-white">
            {consultingRequests.map((request) => (
              <Link
                key={request.id}
                href={`/account/consulting/${request.requestNo || request.id}`}
                className="grid border-b border-line transition last:border-b-0 hover:bg-[#f8fbff] md:grid-cols-[1fr_104px]"
              >
                <div className="px-4 py-3">
                  <div className="text-[15px] font-extrabold leading-6 text-ink">{request.direction}</div>
                  <div className="mt-0.5 text-sm text-muted">{request.company}</div>

                  <div className="mt-3 grid gap-x-5 gap-y-1.5 text-sm md:grid-cols-3">
	                    <div>
	                      <div className="text-xs font-bold text-soft">提交编号</div>
	                      <div className="mt-0.5 break-all font-extrabold text-ink">{request.requestNo || request.id}</div>
	                    </div>
                    <div>
                      <div className="text-xs font-bold text-soft">提交时间</div>
                      <div className="mt-0.5 font-extrabold text-ink">{formatAccountDateTime(request.createdAt)}</div>
                    </div>
                    <div>
                      <div className="text-xs font-bold text-soft">受理部门</div>
                      <div className="mt-0.5 font-extrabold text-ink">{request.owner}</div>
                    </div>
                  </div>
                </div>

                <div className={`grid min-h-[44px] place-items-center border-t border-line px-3 text-center text-sm font-extrabold md:min-h-full md:border-l md:border-t-0 ${statusTone(request.status)}`}>
                  {statusLabel(request.status)}
                </div>
              </Link>
            ))}
          </div>
        )}
      </section>
    </div>
  )
}
