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

function statusLabel(status?: BackendDataServiceRequest['status']) {
  if (status === 'pending_contact') return '等待联系'
  if (status === 'contacting') return '沟通中'
  if (status === 'quoted') return '待付款'
  if (status === 'pending_payment') return '待支付'
  if (status === 'in_service') return '服务进行中'
  if (status === 'completed') return '服务已完成'
  if (status === 'cancelled') return '已取消'
  return '处理中'
}

function stepIndex(status?: BackendDataServiceRequest['status']) {
  if (status === 'pending_contact' || status === 'contacting') return 1
  if (status === 'quoted' || status === 'pending_payment') return 2
  if (status === 'in_service') return 3
  if (status === 'completed') return 4
  return 0
}

export default function ReportDetailPage() {
  const [service, setService] = useState<BackendDataServiceRequest | null | undefined>(undefined)
  const [report, setReport] = useState<BackendDataProduct | null>(null)

  useLoad((query) => {
    const id = String(query.id || '')
    const user = ensureLoggedIn(`/pages/account/reports/detail/index?id=${encodeURIComponent(id)}`)
    const token = getToken()
    if (!user || !token || !id) return
    backend.accountDataServiceRequest(token, id)
      .then((result) => {
        setService(result)
        setReport(null)
      })
      .catch(() => {
        setService(null)
        backend.accountDataProducts(token)
          .then((result) => setReport(result.items.find((item) => item.id === id || item.slug === id) || null))
          .catch((error) => Taro.showToast({ title: error instanceof Error ? error.message : '数据服务加载失败', icon: 'none' }))
      })
  })

  async function download(url?: string, fileName = '数据服务交付文件') {
    if (!url) {
      Taro.showToast({ title: '文件暂未上传', icon: 'none' })
      return
    }
    tapMedium()
    try {
      const result = await Taro.downloadFile({ url })
      await Taro.openDocument({ filePath: result.tempFilePath, showMenu: true })
    } catch {
      await Taro.setClipboardData({ data: url })
      Taro.showToast({ title: `${fileName}链接已复制`, icon: 'none' })
    }
  }

  if (service === undefined) {
    return (
      <Page title="数据服务">
        <View className="flow-section"><Text className="row-sub">正在加载服务进度...</Text></View>
      </Page>
    )
  }

  if (service) {
    const current = stepIndex(service.status)
    const steps = ['提交申请', '等待联系', '付款', '服务进行中', '完成下载']
    const canPay = service.status === 'quoted' || service.status === 'pending_payment'
    const deliverableIds = service.deliverableFileIds?.length ? service.deliverableFileIds : service.deliverableFileId ? [service.deliverableFileId] : []
    const deliverables = deliverableIds.map((id, index) => ({
      id,
      url: fileAssetUrl(id),
      name: index === 0 ? service.deliverableFileName || '数据服务交付文件' : `交付附件 ${index + 1}`,
    }))
    const canDownload = service.status === 'completed' && (Boolean(service.deliverableFileUrl) || deliverables.length > 0)
    return (
      <Page title="数据服务详情" subtle={statusLabel(service.status)}>
        <View className="booking-detail-hero">
          <Text className="status-pill">{statusLabel(service.status)}</Text>
          <Text className="booking-detail-title">{service.dataTopic || service.quotedTitle || '数据服务申请'}</Text>
          <Text className="booking-detail-sub">{service.requestNo} · {service.serviceType || '数据服务'}</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>
          <MetaRow label="单位名称" value={service.company || '-'} />
          <MetaRow label="组织类型" value={service.organizationType || '-'} />
          <MetaRow label="联系人" value={service.contactName || '-'} />
          <MetaRow label="手机号" value={service.contactPhone || service.userPhone || '-'} />
          <MetaRow label="邮箱" value={service.email || '-'} />
          <MetaRow label="城市" value={service.city || '-'} />
        </View>

        <View className="flow-section">
          <Text className="flow-section-title">数据需求</Text>
          <MetaRow label="地区范围" value={service.regionScope || '-'} />
          <MetaRow label="时间范围" value={service.timeRange || '-'} />
          <MetaRow label="行业/场景" value={service.industryScene || '-'} />
          <MetaRow label="期望格式" value={service.expectedFormat || '-'} />
          <MetaRow label="数据量级" value={service.dataVolume || '-'} />
          <View className="staff-text-block">
            <Text className="staff-text-label">需求描述</Text>
            <Text className="staff-text-value">{service.requirement || '-'}</Text>
          </View>
          <View className="staff-text-block">
            <Text className="staff-text-label">期望成果</Text>
            <Text className="staff-text-value">{service.expectedResult || '-'}</Text>
          </View>
        </View>

        <View className="flow-section">
          <Text className="flow-section-title">报价与进度</Text>
          <MetaRow label="当前状态" value={statusLabel(service.status)} />
          <MetaRow label="负责人" value={service.assigneeName || '待分配'} />
          <MetaRow label="报价标题" value={service.quotedTitle || '-'} />
          <MetaRow label="报价金额" value={service.quotedAmount ? `¥${yuan(service.quotedAmount).toLocaleString()}` : '待沟通'} />
          <View className="staff-text-block">
            <Text className="staff-text-label">业务员说明</Text>
            <Text className="staff-text-value">{service.quotedNote || service.progressNote || service.contactNote || '业务员联系后会在这里更新说明。'}</Text>
          </View>
          {service.resultSummary && (
            <View className="staff-text-block">
              <Text className="staff-text-label">交付说明</Text>
              <Text className="staff-text-value">{service.resultSummary}</Text>
            </View>
          )}
        </View>

        <View className="staff-actions">
          {canPay && <View className="staff-action" onClick={() => Taro.navigateTo({ url: `/pages/checkout/index?dataServiceRequestId=${encodeURIComponent(service.id)}` })}>去付款</View>}
          {canDownload && (deliverables.length ? deliverables.map((file) => (
            <View key={file.id} className="staff-action" onClick={() => download(file.url, file.name)}>下载{file.name}</View>
          )) : <View className="staff-action" onClick={() => download(service.deliverableFileUrl, service.deliverableFileName || '数据服务交付文件')}>下载交付文件</View>)}
          {!canPay && !canDownload && <View className="staff-action muted">{statusLabel(service.status)}</View>}
        </View>
      </Page>
    )
  }

  if (!report) {
    return (
      <Page title="数据服务">
        <View className="flow-section">
          <Text className="row-sub">未找到数据服务或历史报告，请返回列表刷新。</Text>
        </View>
      </Page>
    )
  }

  return (
    <Page title={report.title}>
      <View className="flow-section">
        <View style={{ display: 'flex', gap: '26px' }}>
          <ProductImage className="report-cover" src={report.coverUrl || 'data'} style={{ width: '230px', height: '330px', flex: 'none' }} />
          <View style={{ flex: 1 }}>
            <Text className="row-title">{report.title}</Text>
            <Text className="row-sub">{report.summary}</Text>
          </View>
        </View>
        <View style={{ height: '26px' }} />
        <MetaRow label="类别" value={report.category || '-'} />
        <MetaRow label="文件格式" value={report.fileFormat || '-'} />
        <MetaRow label="文件名称" value={report.fileName || '文件暂未上传'} />
        <View style={{ height: '26px' }} />
        <View className={report.fileUrl ? 'primary-btn' : 'ghost-btn'} onClick={() => download(report.fileUrl, report.fileName || '历史报告')}>{report.fileUrl ? '下载报告' : '文件暂未上传'}</View>
      </View>
    </Page>
  )
}
