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

export default function StaffConsultingDetailPage() {
  const [id, setId] = useState('')
  const [item, setItem] = useState<BackendConsultingRequest | null>(null)
  const [progressNote, setProgressNote] = useState('')
  const [solutionSummary, setSolutionSummary] = useState('')
  const [quotedTitle, setQuotedTitle] = useState('')
  const [quotedAmount, setQuotedAmount] = useState('')
  const [quotedNote, setQuotedNote] = useState('')

  async function loadRequest(nextId = id) {
    const token = ensureStaffLoggedIn('/pages/staff/consulting/index')
    if (!token) {
      return
    }
    if (!nextId) return
    try {
      const result = await backend.staffConsultingRequest(token, nextId)
      setItem(result)
      setProgressNote(result.progressNote || '')
      setSolutionSummary(result.finalSummary || result.solutionSummary || '')
      setQuotedTitle(result.quotedTitle || `${result.direction || '规划咨询'}服务报价`)
      setQuotedAmount(result.quotedAmount ? String(Math.round(result.quotedAmount / 100)) : '')
      setQuotedNote(result.quotedNote || result.solutionSummary || '')
    } 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/consulting/index')
    if (!token || !item) return
    try {
      const result = await backend.updateStaffConsultingRequest(token, item.id, payload)
      setItem(result)
      setProgressNote(result.progressNote || '')
      setSolutionSummary(result.finalSummary || result.solutionSummary || '')
      setQuotedTitle(result.quotedTitle || `${result.direction || '规划咨询'}服务报价`)
      setQuotedAmount(result.quotedAmount ? String(Math.round(result.quotedAmount / 100)) : '')
      setQuotedNote(result.quotedNote || result.solutionSummary || '')
      Taro.showToast({ title: message, icon: 'success' })
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '操作失败', icon: 'none' })
    }
  }

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

  return (
    <Page title="咨询服务详情" subtle={consultingStatusLabel(item?.status)}>
      <View className="staff-detail-card">
        <Text className="staff-section-title">单位与联系人</Text>
        <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?.direction || '-'} />
        <MetaRow label="所属行业" value={item?.industry || '-'} />
        <MetaRow label="项目阶段" value={item?.projectStage || '-'} />
        <MetaRow label="紧急度" value={item?.urgency || '-'} />
        <MetaRow label="预算范围" value={item?.budgetRange || '-'} />
        <MetaRow label="启动时间" value={item?.expectedStart || '-'} />
      </View>

      <View className="staff-detail-card">
        <Text className="staff-section-title">背景与目标</Text>
        <View className="staff-text-block">
          <Text className="staff-text-label">当前现状</Text>
          <Text className="staff-text-value">{item?.currentSituation || '-'}</Text>
        </View>
        <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?.goals || '-'}</Text>
        </View>
        <MetaRow label="联系时间" value={item?.preferredContactTime || '-'} />
      </View>

      <View className="staff-detail-card">
        <Text className="staff-section-title">处理记录</Text>
        <MetaRow label="咨询编号" value={item?.requestNo || '-'} />
        <MetaRow label="当前状态" value={consultingStatusLabel(item?.status)} />
        <MetaRow label="负责人" value={item?.assigneeName || item?.owner || '-'} />
        <MetaRow label="受理时间" value={formatDateTime(item?.acceptedAt)} />
        <MetaRow label="完成时间" value={formatDateTime(item?.completedAt)} />
        <Textarea className="form-textarea staff-textarea" value={progressNote} onInput={(event) => setProgressNote(String(event.detail.value))} placeholder="沟通记录或当前进度" />
        <Textarea className="form-textarea staff-textarea" value={solutionSummary} onInput={(event) => setSolutionSummary(String(event.detail.value))} placeholder="最终方案反馈/方案摘要" />
      </View>

      <View className="staff-detail-card">
        <Text className="staff-section-title">收费报价</Text>
        <MetaRow label="已报价金额" value={item?.quotedAmount ? `¥${Math.round(item.quotedAmount / 100).toLocaleString()}` : '未报价'} />
        <Input className="form-input" value={quotedTitle} onInput={(event) => setQuotedTitle(String(event.detail.value))} placeholder="报价标题" />
        <Input className="form-input" type="number" 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-actions">
        {item?.status === 'pending' && (
          <View className="staff-action" onClick={() => updateRequest({ accept: true, progressNote: progressNote || '顾问已接单，准备沟通需求' }, '已接单')}>接单</View>
        )}
        {item?.status === 'assigned' && (
          <View className="staff-action" onClick={() => updateRequest({ status: 'communicating', progressNote: progressNote || '已开始需求沟通' }, '已开始沟通')}>开始沟通</View>
        )}
        {item?.status === 'communicating' && (
          <>
            <View className="staff-action" onClick={() => updateRequest({ status: 'communicating', progressNote }, '沟通记录已保存')}>记录沟通</View>
            <View className="staff-action" onClick={() => updateRequest({ status: 'planning', progressNote }, '已进入方案制定')}>方案制定中</View>
          </>
        )}
        {item?.status === 'planning' && (
          <>
            <View className="staff-action" onClick={() => updateRequest({ status: 'planning', progressNote, solutionSummary }, '方案摘要已保存')}>提交方案摘要</View>
            <View className="staff-action" onClick={() => updateRequest({ status: 'proposal_ready', chargeRequired: true, quotedTitle, quotedAmount: Math.round(Number(quotedAmount || 0) * 100), quotedNote, progressNote, solutionSummary: solutionSummary || quotedNote }, '收费报价已发送')}>发送收费报价</View>
            <View className="staff-action" onClick={() => updateRequest({ status: 'completed', chargeRequired: false, progressNote, solutionSummary, finalSummary: solutionSummary || '咨询服务已完成' }, '已免费完成')}>免费完成</View>
          </>
        )}
        {(item?.status === 'proposal_ready' || item?.status === 'pending_payment') && (
          <>
            <View className="staff-action" onClick={() => updateRequest({ status: item.status, progressNote, solutionSummary, quotedTitle, quotedAmount: Math.round(Number(quotedAmount || 0) * 100), quotedNote }, '报价与进度已保存')}>保存报价/进度</View>
          </>
        )}
        {item?.status === 'in_service' && (
          <>
            <View className="staff-action" onClick={() => updateRequest({ status: 'in_service', progressNote, solutionSummary }, '服务进度已保存')}>保存服务进度</View>
            <View className="staff-action" onClick={() => updateRequest({ status: 'completed', progressNote, solutionSummary, finalSummary: solutionSummary || '咨询服务已完成' }, '已完成服务')}>完成并反馈</View>
          </>
        )}
        {item && item.status !== 'completed' && item.status !== 'cancelled' && (
          <View className="staff-action danger" onClick={() => updateRequest({ status: 'cancelled', progressNote }, '已取消服务')}>取消服务</View>
        )}
      </View>
    </Page>
  )
}
