import { Input, Text, Textarea, View } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { backend, yuan, type BackendDataServiceRequest } from '@/api/backend'
import { MetaRow, Page } from '@/components/ui'
import { ensureStaffLoggedIn } from '@/stores/storage'
import { dataServiceStatusLabel, formatDateTime } from '../shared'

type UploadedFile = {
  id: string
  url: string
  fileName: string
  fileSize: number
}

export default function StaffDataServiceDetailPage() {
  const [id, setId] = useState('')
  const [item, setItem] = useState<BackendDataServiceRequest | null>(null)
  const [contactNote, setContactNote] = useState('')
  const [progressNote, setProgressNote] = useState('')
  const [quotedTitle, setQuotedTitle] = useState('')
  const [quotedAmount, setQuotedAmount] = useState('')
  const [quotedNote, setQuotedNote] = useState('')
  const [resultSummary, setResultSummary] = useState('')
  const [uploaded, setUploaded] = useState<UploadedFile | null>(null)

  function syncForm(next: BackendDataServiceRequest) {
    setItem(next)
    setContactNote(next.contactNote || '')
    setProgressNote(next.progressNote || '')
    setQuotedTitle(next.quotedTitle || next.dataTopic || '')
    setQuotedAmount(next.quotedAmount ? String(yuan(next.quotedAmount)) : '')
    setQuotedNote(next.quotedNote || '')
    setResultSummary(next.resultSummary || '')
    setUploaded(next.deliverableFileId ? {
      id: next.deliverableFileId,
      url: next.deliverableFileUrl,
      fileName: next.deliverableFileName || '数据服务交付文件',
      fileSize: next.deliverableFileSize || 0
    } : null)
  }

  async function loadRequest(nextId = id) {
    const token = ensureStaffLoggedIn('/pages/staff/data-services/index')
    if (!token) {
      return
    }
    if (!nextId) return
    try {
      syncForm(await backend.staffDataServiceRequest(token, nextId))
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '数据服务详情加载失败', icon: 'none' })
    }
  }

  async function updateRequest(payload: Record<string, unknown>, message: string) {
    const token = ensureStaffLoggedIn('/pages/staff/data-services/index')
    if (!token || !item) return
    try {
      syncForm(await backend.updateStaffDataServiceRequest(token, item.id, payload))
      Taro.showToast({ title: message, icon: 'success' })
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '操作失败', icon: 'none' })
    }
  }

  function callUser() {
    const phoneNumber = item?.contactPhone || item?.userPhone || ''
    if (!phoneNumber) {
      Taro.showToast({ title: '暂无联系电话', icon: 'none' })
      return
    }
    void Taro.makePhoneCall({ phoneNumber })
  }

  async function quote() {
    const amount = Math.round(Number(quotedAmount) * 100)
    if (!quotedTitle || !amount || amount <= 0) {
      Taro.showToast({ title: '请填写报价标题和金额', icon: 'none' })
      return
    }
    await updateRequest({
      status: 'quoted',
      contactNote,
      progressNote,
      quotedTitle,
      quotedAmount: amount,
      quotedNote: quotedNote || '已根据沟通结果生成数据服务报价。'
    }, '报价已保存')
  }

  async function chooseAndUpload() {
    const token = ensureStaffLoggedIn('/pages/staff/data-services/index')
    if (!token) return
    const chooser = (Taro as unknown as {
      chooseMessageFile?: (options: { count: number; type: string }) => Promise<{ tempFiles: Array<{ path: string; name?: string }> }>
    }).chooseMessageFile
    if (!chooser) {
      Taro.showToast({ title: '当前端不支持选择文件', icon: 'none' })
      return
    }
    try {
      const result = await chooser({ count: 1, type: 'file' })
      const file = result.tempFiles[0]
      if (!file?.path) return
      const uploadedFile = await backend.uploadStaffFile(token, file.path, file.name || '数据服务交付文件')
      setUploaded(uploadedFile)
      Taro.showToast({ title: '文件已上传', icon: 'success' })
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '上传失败', icon: 'none' })
    }
  }

  async function completeService() {
    const fileId = uploaded?.id || item?.deliverableFileId
    if (!fileId) {
      Taro.showToast({ title: '请先上传交付文件', icon: 'none' })
      return
    }
    await updateRequest({
      status: 'completed',
      progressNote,
      deliverableFileId: fileId,
      resultSummary: resultSummary || '数据服务成果已整理完成，可在用户端下载。'
    }, '服务已完成')
  }

  useLoad((query) => {
    const nextId = String(query.id || '')
    setId(nextId)
    void loadRequest(nextId)
  })

  const canCancel = item ? ['pending_contact', 'contacting', 'quoted', 'pending_payment'].includes(item.status) && !item.paidAt : false

  return (
    <Page title="数据服务详情" subtle={dataServiceStatusLabel(item?.status)}>
      <View className="staff-detail-card">
        <Text className="staff-section-title">单位与联系人</Text>
        <MetaRow label="申请编号" value={item?.requestNo || '-'} />
        <MetaRow label="单位名称" value={item?.company || '-'} />
        <MetaRow label="组织类型" value={item?.organizationType || '-'} />
        <MetaRow label="联系人" value={item?.contactName || '-'} />
        <MetaRow label="联系电话" value={item?.contactPhone || item?.userPhone || '-'} />
        <MetaRow label="邮箱" value={item?.email || '-'} />
        <MetaRow label="城市" value={item?.city || '-'} />
      </View>

      <View className="staff-detail-card">
        <Text className="staff-section-title">数据需求</Text>
        <MetaRow label="数据主题" value={item?.dataTopic || '-'} />
        <MetaRow label="服务类型" value={item?.serviceType || '-'} />
        <MetaRow label="地区范围" value={item?.regionScope || '-'} />
        <MetaRow label="时间范围" value={item?.timeRange || '-'} />
        <MetaRow label="行业/场景" value={item?.industryScene || '-'} />
        <MetaRow label="期望格式" value={item?.expectedFormat || '-'} />
        <MetaRow label="数据量级" value={item?.dataVolume || '-'} />
        <MetaRow label="使用目的" value={item?.usagePurpose || '-'} />
        <View className="staff-text-block">
          <Text className="staff-text-label">需求描述</Text>
          <Text className="staff-text-value">{item?.requirement || '-'}</Text>
        </View>
        <View className="staff-text-block">
          <Text className="staff-text-label">期望成果</Text>
          <Text className="staff-text-value">{item?.expectedResult || '-'}</Text>
        </View>
      </View>

      <View className="staff-detail-card">
        <Text className="staff-section-title">交付与沟通</Text>
        <MetaRow label="截止时间" value={item?.deadline || '-'} />
        <MetaRow label="预算范围" value={item?.budgetRange || '-'} />
        <MetaRow label="敏感数据" value={item?.sensitiveData ? '涉及' : '不涉及/未说明'} />
        <MetaRow label="方便联系" value={item?.preferredContactTime || '-'} />
        <View className="staff-text-block">
          <Text className="staff-text-label">补充说明</Text>
          <Text className="staff-text-value">{item?.extraNote || '-'}</Text>
        </View>
      </View>

      <View className="staff-detail-card">
        <Text className="staff-section-title">处理记录</Text>
        <MetaRow label="当前状态" value={dataServiceStatusLabel(item?.status)} />
        <MetaRow label="负责人" value={item?.assigneeName || '-'} />
        <MetaRow label="订单号" value={item?.orderNo || '-'} />
        <MetaRow label="报价时间" value={formatDateTime(item?.quotedAt)} />
        <MetaRow label="付款时间" value={formatDateTime(item?.paidAt)} />
        <MetaRow label="完成时间" value={formatDateTime(item?.completedAt)} />
        <Textarea className="form-textarea staff-textarea" value={contactNote} onInput={(event) => setContactNote(String(event.detail.value))} placeholder="联系记录" />
        <Textarea className="form-textarea staff-textarea" value={progressNote} onInput={(event) => setProgressNote(String(event.detail.value))} placeholder="写给用户看的进度说明" />
      </View>

      <View className="staff-detail-card">
        <Text className="staff-section-title">报价</Text>
        <Input className="form-input" value={quotedTitle} onInput={(event) => setQuotedTitle(String(event.detail.value))} placeholder="报价标题" />
        <View style={{ height: '14px' }} />
        <Input className="form-input" type="digit" value={quotedAmount} onInput={(event) => setQuotedAmount(String(event.detail.value))} placeholder="报价金额（元）" />
        <Textarea className="form-textarea staff-textarea" value={quotedNote} onInput={(event) => setQuotedNote(String(event.detail.value))} placeholder="报价说明" />
      </View>

      <View className="staff-detail-card">
        <Text className="staff-section-title">交付文件</Text>
        <MetaRow label="已上传文件" value={uploaded?.fileName || item?.deliverableFileName || '暂未上传'} />
        <Textarea className="form-textarea staff-textarea" value={resultSummary} onInput={(event) => setResultSummary(String(event.detail.value))} placeholder="完成说明" />
      </View>

      <View className="staff-actions">
        <View className="staff-action" onClick={callUser}>拨打电话</View>
        {item?.status === 'pending_contact' && (
          <View className="staff-action" onClick={() => updateRequest({ accept: true, contactNote: contactNote || '业务员已接单，准备联系用户。' }, '已接单')}>接单联系</View>
        )}
        {item?.status === 'contacting' && (
          <>
            <View className="staff-action" onClick={() => updateRequest({ status: 'contacting', contactNote, progressNote }, '联系记录已保存')}>保存记录</View>
            <View className="staff-action" onClick={quote}>保存报价</View>
          </>
        )}
        {(item?.status === 'quoted' || item?.status === 'pending_payment') && (
          <View className="staff-action" onClick={() => updateRequest({ contactNote, progressNote, quotedNote }, '说明已保存')}>更新说明</View>
        )}
        {item?.status === 'in_service' && (
          <>
            <View className="staff-action" onClick={chooseAndUpload}>上传交付文件</View>
            <View className="staff-action" onClick={completeService}>完成服务</View>
          </>
        )}
        {canCancel && (
          <View className="staff-action danger" onClick={() => updateRequest({ status: 'cancelled', progressNote }, '已取消服务')}>取消服务</View>
        )}
      </View>
    </Page>
  )
}
