import { Text, View } from '@tarojs/components'
import { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import Taro from '@tarojs/taro'
import { backend, fileAssetUrl, yuan, type BackendConsultingRequest } from '@/api/backend'
import { MetaRow, Page } from '@/components/ui'
import { ensureLoggedIn, getToken } from '@/stores/storage'

function statusLabel(status?: BackendConsultingRequest['status']) {
  if (status === 'completed') return '已完成'
  if (status === 'in_service') return '服务中'
  if (status === 'pending_payment') return '待支付'
  if (status === 'proposal_ready') return '待确认报价'
  if (status === 'planning') return '方案中'
  if (status === 'communicating') return '沟通中'
  if (status === 'assigned') 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' || status === 'pending_payment') return 3
  if (status === 'in_service') return 4
  if (status === 'completed') return 5
  return 0
}

function submitTime(value?: string) {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '-'
  return date.toLocaleString('zh-CN')
}

export default function ConsultingDetailPage() {
  const [item, setItem] = useState<BackendConsultingRequest | null>(null)
  useLoad((query) => {
    const id = String(query.id || '')
    const user = ensureLoggedIn(`/pages/account/consulting/detail/index?id=${encodeURIComponent(id)}`)
    const token = getToken()
    if (!user || !token || !id) return
    backend.accountConsultingRequests(token)
      .then((result) => setItem(result.items.find((request) => request.id === id || request.requestNo === id) || null))
      .catch((error) => Taro.showToast({ title: error instanceof Error ? error.message : '咨询加载失败', icon: 'none' }))
  })

  async function openFinalFile() {
    if (!item) return
    const url = item.finalFileUrl || (item.finalFileId ? fileAssetUrl(item.finalFileId) : '')
    if (!url) {
      Taro.showToast({ title: '最终附件暂未上传', icon: 'none' })
      return
    }
    try {
      const result = await Taro.downloadFile({ url })
      await Taro.openDocument({ filePath: result.tempFilePath, showMenu: true })
    } catch {
      await Taro.setClipboardData({ data: url })
      Taro.showToast({ title: '方案附件链接已复制', icon: 'none' })
    }
  }

  if (!item) {
    return (
      <Page title="咨询详情">
        <View className="flow-section">
          <Text className="row-sub">正在同步咨询信息。</Text>
        </View>
      </Page>
    )
  }
  const steps = ['提交需求', '顾问受理', '需求沟通', '方案/报价', '服务执行', '方案反馈']
  const current = stepIndex(item.status)
  const canPay = item.status === 'proposal_ready' || item.status === 'pending_payment'

  return (
    <Page title={item.company || item.direction} subtle={`提交于 ${submitTime(item.createdAt)} · ${statusLabel(item.status)}`}>
      <View className="booking-detail-hero">
        <Text className="status-pill">{statusLabel(item.status)}</Text>
        <Text className="booking-detail-title">{item.direction || '规划咨询'}</Text>
        <Text className="booking-detail-sub">{item.requestNo} · {statusLabel(item.status)}</Text>
        <View style={{ height: '20px' }} />
        <View className="tabs">
          {steps.map((label, index) => (
            <Text key={label} className={index <= current ? 'tab active' : 'tab'}>{label}</Text>
          ))}
        </View>
      </View>

      <View className="flow-section">
        <Text className="flow-section-title">需求信息</Text>
        <View style={{ height: '12px' }} />
        <MetaRow label="提交编号" value={item.requestNo} />
        <MetaRow label="单位名称" value={item.company} />
        <MetaRow label="联系人" value={item.contactName} />
        <MetaRow label="联系电话" value={item.contactPhone} />
        <MetaRow label="咨询方向" value={item.direction} />
        <MetaRow label="所在城市" value={item.city} />
        <MetaRow label="所属行业" value={item.industry} />
        <MetaRow label="项目阶段" value={item.projectStage} />
        <MetaRow label="沟通紧急度" value={item.urgency} />
        <MetaRow label="预算范围" value={item.budgetRange} />
        <View style={{ paddingTop: '22px' }}>
          <Text className="meta-label">当前现状</Text>
          <Text className="row-sub">{item.currentSituation || '-'}</Text>
        </View>
        <View style={{ paddingTop: '22px' }}>
          <Text className="meta-label">需求描述</Text>
          <Text className="row-sub">{item.requirement}</Text>
        </View>
        <View style={{ paddingTop: '22px' }}>
          <Text className="meta-label">期望成果</Text>
          <Text className="row-sub">{item.goals || '-'}</Text>
        </View>
        <View style={{ paddingTop: '22px' }}>
          <Text className="meta-label">顾问进度</Text>
          <Text className="row-sub">{item.progressNote || '顾问暂未更新进度'}</Text>
        </View>
        <View style={{ paddingTop: '22px' }}>
          <Text className="meta-label">方案摘要</Text>
          <Text className="row-sub">{item.solutionSummary || '暂未形成方案摘要'}</Text>
        </View>
      </View>

      {(item.chargeRequired || item.quotedTitle || item.quotedAmount) && (
        <View className="flow-section">
          <Text className="flow-section-title">咨询报价</Text>
          <View style={{ height: '12px' }} />
          <MetaRow label="报价标题" value={item.quotedTitle || '规划咨询服务报价'} />
          <MetaRow label="报价金额" value={item.quotedAmount ? `¥${yuan(item.quotedAmount).toLocaleString()}` : '待确认'} />
          <MetaRow label="确认时间" value={submitTime(item.confirmedAt || undefined)} />
          <MetaRow label="支付时间" value={submitTime(item.paidAt || undefined)} />
          <View style={{ paddingTop: '22px' }}>
            <Text className="meta-label">报价说明</Text>
            <Text className="row-sub">{item.quotedNote || '顾问会在这里说明服务内容、报价依据和交付方式。'}</Text>
          </View>
        </View>
      )}

      {(item.finalSummary || item.finalFileUrl) && (
        <View className="flow-section">
          <Text className="flow-section-title">最终方案反馈</Text>
          <View style={{ paddingTop: '18px' }}>
            <Text className="row-sub">{item.finalSummary || '最终附件已生成，请查看附件。'}</Text>
          </View>
          {(item.finalFileUrl || item.finalFileId) && <View className="ghost-btn" onClick={openFinalFile}>查看方案附件</View>}
        </View>
      )}

      <View className="staff-actions">
        {canPay ? (
          <View className="staff-action" onClick={() => Taro.navigateTo({ url: `/pages/checkout/index?consultingRequestId=${encodeURIComponent(item.id)}` })}>确认并支付</View>
        ) : (
          <View className="staff-action muted">{statusLabel(item.status)}</View>
        )}
      </View>
    </Page>
  )
}
