import { Checkbox, Input, Picker, ScrollView, Text, Textarea, View } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { backend, type BackendConsultingOptionSet, type BackendDataServiceRequest } from '@/api/backend'
import { MetaRow, Page } from '@/components/ui'
import { ensureLoggedIn, getAiLeadDraft, getToken, getUser } from '@/stores/storage'
import { tapLight, tapMedium } from '@/utils/feedback'
import { toast } from '@/utils/nav'

const defaults = {
  company: '',
  organizationType: '',
  contactName: '',
  contactPhone: '',
  email: '',
  city: '',
  dataTopic: '',
  serviceType: '',
  regionScope: '',
  timeRange: '',
  industryScene: '',
  expectedFormat: '',
  dataVolume: '',
  usagePurpose: '',
  requirement: '',
  expectedResult: '',
  deadline: '',
  budgetRange: '',
  sensitiveData: false,
  preferredContactTime: '',
  extraNote: ''
}

type FormState = typeof defaults
type TextKey = Exclude<keyof FormState, 'sensitiveData'>

const aiDraftTextFields: TextKey[] = [
  'company',
  'organizationType',
  'contactName',
  'contactPhone',
  'email',
  'city',
  'dataTopic',
  'serviceType',
  'regionScope',
  'timeRange',
  'industryScene',
  'expectedFormat',
  'dataVolume',
  'usagePurpose',
  'requirement',
  'expectedResult',
  'deadline',
  'budgetRange',
  'preferredContactTime',
  'extraNote'
]

const steps = [
  { title: '单位联系人', subtle: '先确认业务沟通的基本信息' },
  { title: '数据需求', subtle: '说明需要的数据范围、口径和用途' },
  { title: '交付沟通', subtle: '补充交付成果、预算和联系偏好' }
]

function optionLabels(optionSets: BackendConsultingOptionSet[], code: string) {
  return (optionSets.find((set) => set.code === code)?.options || [])
    .filter((option) => option.status !== 'disabled')
    .sort((a, b) => a.sortOrder - b.sortOrder)
    .map((option) => option.label)
    .filter(Boolean)
}

function draftText(value: unknown) {
  return typeof value === 'string' ? value.trim() : ''
}

function draftBoolean(value: unknown) {
  if (typeof value === 'boolean') return value
  if (value === 'true') return true
  if (value === 'false') return false
  return null
}

function mergeAiDraft(current: FormState, payload: Record<string, unknown>): FormState {
  const next = { ...current }
  aiDraftTextFields.forEach((key) => {
    const value = draftText(payload[key])
    if (value && !next[key]) next[key] = value
  })
  const sensitiveData = draftBoolean(payload.sensitiveData)
  if (sensitiveData !== null) next.sensitiveData = sensitiveData
  return next
}

function queryString(params: Record<string, string>) {
  const query = Object.entries(params)
    .filter(([, value]) => value)
    .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
    .join('&')
  return query ? `?${query}` : ''
}

function PickerField({ label, value, options, onChange }: { label: string; value: string; options: string[]; onChange: (value: string) => void }) {
  if (!options.length) return null
  const currentIndex = Math.max(options.indexOf(value), 0)
  return (
    <View className="flow-field">
      <Text className="flow-label">{label}</Text>
      <Picker mode="selector" range={options} value={currentIndex} onChange={(event) => onChange(options[Number(event.detail.value)] || options[0] || '')}>
        <View className={value ? 'flow-picker' : 'flow-picker muted'}>{value || `请选择${label}`}</View>
      </Picker>
    </View>
  )
}

function TextInput({ label, value, placeholder, onChange }: { label: string; value: string; placeholder?: string; onChange: (value: string) => void }) {
  return (
    <View className="flow-field">
      <Text className="flow-label">{label}</Text>
      <Input className="flow-input" value={value} placeholder={placeholder || label} onInput={(event) => onChange(String(event.detail.value))} />
    </View>
  )
}

function TextArea({ label, value, placeholder, onChange }: { label: string; value: string; placeholder?: string; onChange: (value: string) => void }) {
  return (
    <View className="flow-field">
      <Text className="flow-label">{label}</Text>
      <Textarea className="flow-textarea" value={value} placeholder={placeholder || label} onInput={(event) => onChange(String(event.detail.value))} />
    </View>
  )
}

export default function DataServiceApplyPage() {
  const [form, setForm] = useState<FormState>(defaults)
  const [step, setStep] = useState(0)
  const [submitted, setSubmitted] = useState<BackendDataServiceRequest | null>(null)
  const [submitting, setSubmitting] = useState(false)
  const [optionSets, setOptionSets] = useState<BackendConsultingOptionSet[]>([])

  useLoad((query) => {
    const productId = String(query.productId || '')
    const aiDraftKey = String(query.aiDraftKey || '')
    const redirect = `/pages/data-service/apply/index${queryString({ productId, aiDraftKey })}`
    const user = ensureLoggedIn(redirect)
    if (!user) return
    setForm((current) => ({
      ...current,
      company: current.company || user.organization || '',
      contactName: current.contactName || user.name || '',
      contactPhone: current.contactPhone || user.contactPhone || user.phone || '',
      email: current.email || user.email || '',
      city: current.city || user.city || ''
    }))
    const draft = getAiLeadDraft(aiDraftKey)
    if (draft?.type === 'data_service' && draft.payload) {
      setForm((current) => mergeAiDraft(current, draft.payload || {}))
    }
    void backend.dataServiceOptions()
      .then((result) => {
        const sets = result.optionSets || []
        setOptionSets(sets)
        setForm((current) => ({
          ...current,
          organizationType: current.organizationType || optionLabels(sets, 'data_service_organization_type')[0] || '',
          serviceType: current.serviceType || optionLabels(sets, 'data_service_service_type')[0] || '',
          expectedFormat: current.expectedFormat || optionLabels(sets, 'data_service_delivery_format')[0] || '',
          dataVolume: current.dataVolume || optionLabels(sets, 'data_service_data_volume')[0] || '',
          budgetRange: current.budgetRange || optionLabels(sets, 'data_service_budget_range')[0] || '',
          preferredContactTime: current.preferredContactTime || optionLabels(sets, 'data_service_contact_time')[0] || ''
        }))
      })
      .catch(() => setOptionSets([]))
    if (productId) {
      void backend.dataProduct(productId)
        .then((product) => setForm((current) => ({
          ...current,
          dataTopic: current.dataTopic || product.title,
          serviceType: product.category || current.serviceType,
          expectedFormat: product.fileFormat || current.expectedFormat,
          requirement: current.requirement || `想找与“${product.title}”类似的数据服务。`,
          expectedResult: current.expectedResult || '希望获得可验收、可分析的数据服务成果和字段说明。'
        })))
        .catch(() => undefined)
    }
  })

  function patch(key: TextKey, value: string) {
    setForm((current) => ({ ...current, [key]: value }))
  }

  const organizationTypes = optionLabels(optionSets, 'data_service_organization_type')
  const serviceTypes = optionLabels(optionSets, 'data_service_service_type')
  const industryScenes = optionLabels(optionSets, 'data_service_industry_scene')
  const formatOptions = optionLabels(optionSets, 'data_service_delivery_format')
  const dataVolumes = optionLabels(optionSets, 'data_service_data_volume')
  const budgetRanges = optionLabels(optionSets, 'data_service_budget_range')
  const contactTimes = optionLabels(optionSets, 'data_service_contact_time')

  function validateCurrentStep() {
    if (step === 0 && (!form.company || !form.contactName || !form.contactPhone)) {
      toast('请补充单位、联系人和电话')
      return false
    }
    if (step === 1 && (!form.dataTopic || !form.serviceType || !form.requirement)) {
      toast('请补充数据主题、服务类型和需求描述')
      return false
    }
    if (step === 2 && !form.expectedResult) {
      toast('请填写期望成果')
      return false
    }
    return true
  }

  function next() {
    if (!validateCurrentStep()) return
    tapLight()
    setStep((current) => Math.min(current + 1, steps.length - 1))
  }

  async function submit() {
    const user = getUser()
    const token = getToken()
    if (!user || !token) {
      ensureLoggedIn('/pages/data-service/apply/index')
      return
    }
    if (!validateCurrentStep()) return
    setSubmitting(true)
    try {
      const result = await backend.createDataServiceRequest(token, form)
      tapMedium()
      setSubmitted(result)
    } catch (error) {
      toast(error instanceof Error ? error.message : '数据服务申请提交失败')
    } finally {
      setSubmitting(false)
    }
  }

  if (submitted) {
    return (
      <Page title="等待联系" subtle="业务员会根据需求沟通口径、范围和报价">
        <View className="flow-success">
          <Text className="flow-success-mark">✓</Text>
          <Text className="flow-success-title">申请已提交</Text>
          <Text className="flow-success-copy">后续报价、付款和交付进度都会同步到我的数据服务。</Text>
        </View>
        <View className="flow-section">
          <MetaRow label="申请编号" value={submitted.requestNo} />
          <MetaRow label="数据主题" value={submitted.dataTopic} />
          <MetaRow label="当前状态" value="等待联系" />
        </View>
        <View className="bottom-bar">
          <View className="primary-btn" onClick={() => Taro.redirectTo({ url: `/pages/account/reports/detail/index?id=${encodeURIComponent(submitted.id)}` })}>查看服务进度</View>
        </View>
      </Page>
    )
  }

  return (
    <Page>
      <View className="auth-shell auth-flow-shell onboarding-shell service-flow-shell">
        <View className="auth-flow-head onboarding-head service-flow-head">
          <Text className="auth-flow-title">我要找数据</Text>
          <Text className="auth-flow-subtitle">{steps[step].title} · {steps[step].subtle}</Text>
        </View>

        <View className="service-flow-card">
          <ScrollView scrollY enhanced showScrollbar={false} className="service-flow-scroll">
            <View key={step} className="form-group onboarding-form-step service-flow-form">
              {step === 0 && (
                <>
                  <TextInput label="单位名称" value={form.company} onChange={(value) => patch('company', value)} />
                  {organizationTypes.length ? <PickerField label="组织类型" value={form.organizationType} options={organizationTypes} onChange={(value) => patch('organizationType', value)} /> : <TextInput label="组织类型" value={form.organizationType} placeholder="政府部门/企业/高校" onChange={(value) => patch('organizationType', value)} />}
                  <TextInput label="联系人" value={form.contactName} onChange={(value) => patch('contactName', value)} />
                  <TextInput label="手机号" value={form.contactPhone} onChange={(value) => patch('contactPhone', value)} />
                  <TextInput label="邮箱" value={form.email} placeholder="选填" onChange={(value) => patch('email', value)} />
                  <TextInput label="城市" value={form.city} placeholder="如大连" onChange={(value) => patch('city', value)} />
                </>
              )}

              {step === 1 && (
                <>
                  <TextInput label="数据主题" value={form.dataTopic} placeholder="企业名录/产业指标/政策库" onChange={(value) => patch('dataTopic', value)} />
                  {serviceTypes.length ? <PickerField label="服务类型" value={form.serviceType} options={serviceTypes} onChange={(value) => patch('serviceType', value)} /> : <TextInput label="服务类型" value={form.serviceType} onChange={(value) => patch('serviceType', value)} />}
                  <TextInput label="地区范围" value={form.regionScope} placeholder="全国/辽宁/大连/指定区域" onChange={(value) => patch('regionScope', value)} />
                  <TextInput label="时间范围" value={form.timeRange} placeholder="近三年/2024-2026" onChange={(value) => patch('timeRange', value)} />
                  {industryScenes.length ? <PickerField label="行业场景" value={form.industryScene} options={industryScenes} onChange={(value) => patch('industryScene', value)} /> : <TextInput label="行业场景" value={form.industryScene} onChange={(value) => patch('industryScene', value)} />}
                  <TextArea label="需求描述" value={form.requirement} placeholder="需要哪些字段、口径、来源或筛选条件" onChange={(value) => patch('requirement', value)} />
                </>
              )}

              {step === 2 && (
                <>
                  {formatOptions.length ? <PickerField label="期望格式" value={form.expectedFormat} options={formatOptions} onChange={(value) => patch('expectedFormat', value)} /> : <TextInput label="期望格式" value={form.expectedFormat} placeholder="Excel/CSV/ZIP" onChange={(value) => patch('expectedFormat', value)} />}
                  {dataVolumes.length ? <PickerField label="数据量级" value={form.dataVolume} options={dataVolumes} onChange={(value) => patch('dataVolume', value)} /> : <TextInput label="数据量级" value={form.dataVolume} onChange={(value) => patch('dataVolume', value)} />}
                  <TextInput label="使用目的" value={form.usagePurpose} placeholder="内部研究/项目申报/业务分析" onChange={(value) => patch('usagePurpose', value)} />
                  <TextArea label="期望成果" value={form.expectedResult} placeholder="希望最终拿到什么数据、说明或分析材料" onChange={(value) => patch('expectedResult', value)} />
                  <TextInput label="截止时间" value={form.deadline} placeholder="选填" onChange={(value) => patch('deadline', value)} />
                  {budgetRanges.length ? <PickerField label="预算范围" value={form.budgetRange} options={budgetRanges} onChange={(value) => patch('budgetRange', value)} /> : <TextInput label="预算范围" value={form.budgetRange} onChange={(value) => patch('budgetRange', value)} />}
                  <View className="flow-check" onClick={() => { tapLight(); setForm((current) => ({ ...current, sensitiveData: !current.sensitiveData })) }}>
                    <Checkbox checked={form.sensitiveData} value="sensitive" />
                    <Text>涉及敏感数据或需特别合规处理</Text>
                  </View>
                  {contactTimes.length ? <PickerField label="方便联系时间" value={form.preferredContactTime} options={contactTimes} onChange={(value) => patch('preferredContactTime', value)} /> : <TextInput label="方便联系时间" value={form.preferredContactTime} onChange={(value) => patch('preferredContactTime', value)} />}
                  <TextArea label="补充说明" value={form.extraNote} placeholder="其他口径、样例或沟通偏好" onChange={(value) => patch('extraNote', value)} />
                </>
              )}
            </View>
          </ScrollView>
        </View>

        <View className="auth-fixed-actions onboarding-fixed-actions service-flow-actions">
          <View className={step > 0 ? 'auth-action-row' : ''}>
            {step > 0 && <View className="auth-flow-secondary" onClick={() => setStep((current) => Math.max(current - 1, 0))}>上一步</View>}
            <View className={step > 0 ? 'auth-flow-primary flex' : 'auth-flow-primary'} onClick={step === steps.length - 1 ? submit : next}>
              {submitting ? '提交中...' : step === steps.length - 1 ? '提交申请' : '下一步'}
            </View>
          </View>
        </View>
      </View>
    </Page>
  )
}
