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

const fallbackOrganizationTypes = ['政府机构', '国有企业', '民营企业', '事业单位', '产业园区', '其他组织']
const fallbackProjectStages = ['初步了解', '已有内部需求', '正在立项', '已有预算', '需要方案评审', '准备招采']
const fallbackUrgencyOptions = ['1周内沟通', '2周内沟通', '1个月内启动', '3个月内规划', '暂不紧急']
const fallbackBudgetRanges = ['暂不确定', '10万以下', '10万-30万', '30万-100万', '100万以上']
const fallbackExpectedStarts = ['越快越好', '1个月内', '本季度', '半年内', '仅先咨询评估']

const steps = [
  { title: '单位联系人', subtle: '确认顾问联系你的方式' },
  { title: '咨询方向', subtle: '选择方向和项目基本节奏' },
  { title: '背景目标', subtle: '说明现状、问题和期望成果' }
]

type FormState = {
  company: string
  contactName: string
  contactPhone: string
  email: string
  organizationType: string
  industry: string
  city: string
  projectStage: string
  urgency: string
  budgetRange: string
  expectedStart: string
  currentSituation: string
  requirement: string
  goals: string
  preferredContactTime: string
}

const defaults: FormState = {
  company: '',
  contactName: '',
  contactPhone: '',
  email: '',
  organizationType: '',
  industry: '',
  city: '',
  projectStage: '',
  urgency: '',
  budgetRange: '',
  expectedStart: '',
  currentSituation: '',
  requirement: '',
  goals: '',
  preferredContactTime: '工作日 9:00-17:30'
}

const aiDraftFields: Array<keyof FormState> = [
  'company',
  'contactName',
  'contactPhone',
  'email',
  'organizationType',
  'industry',
  'city',
  'projectStage',
  'urgency',
  'budgetRange',
  'expectedStart',
  'currentSituation',
  'requirement',
  'goals',
  'preferredContactTime'
]

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

function mergeAiDraft(current: FormState, payload: Record<string, unknown>): FormState {
  const next = { ...current }
  aiDraftFields.forEach((key) => {
    const value = draftText(payload[key])
    if (value && !next[key]) next[key] = value
  })
  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 labels(optionSets: BackendConsultingOptionSet[], code: string, fallback: string[]) {
  const values = (optionSets.find((item) => item.code === code)?.options || [])
    .filter((item) => item.status !== 'disabled')
    .sort((a, b) => a.sortOrder - b.sortOrder)
    .map((item) => item.label)
    .filter(Boolean)
  return values.length ? values : fallback
}

function PickerField({ label, value, options, onChange }: { label: string; value: string; options: string[]; onChange: (value: string) => void }) {
  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 ConsultingApplyPage() {
  const [directions, setDirections] = useState<ConsultingDirection[]>([])
  const [selectedSlug, setSelectedSlug] = useState('')
  const [optionSets, setOptionSets] = useState<BackendConsultingOptionSet[]>([])
  const [step, setStep] = useState(0)
  const [submitting, setSubmitting] = useState(false)
  const [form, setForm] = useState<FormState>(defaults)

  const optionValues = useMemo(() => ({
    organizationTypes: labels(optionSets, 'organization_type', fallbackOrganizationTypes),
    projectStages: labels(optionSets, 'project_stage', fallbackProjectStages),
    urgencyOptions: labels(optionSets, 'urgency', fallbackUrgencyOptions),
    budgetRanges: labels(optionSets, 'budget_range', fallbackBudgetRanges),
    expectedStarts: labels(optionSets, 'expected_start', fallbackExpectedStarts)
  }), [optionSets])

  useLoad((query) => {
    const initialDirection = String(query.direction || '')
    const aiDraftKey = String(query.aiDraftKey || '')
    const redirect = `/pages/consulting/apply/index${queryString({ direction: initialDirection, aiDraftKey })}`
    const user = ensureLoggedIn(redirect)
    if (!user) return
    patchFromUser(user)
    const draft = getAiLeadDraft(aiDraftKey)
    const draftPayload = draft?.type === 'consulting' && draft.payload ? draft.payload : null
    if (draftPayload) setForm((current) => mergeAiDraft(current, draftPayload))
    const draftDirection = draftText(draftPayload?.direction)
    backend.siteConsulting()
      .then((site) => {
        const draftMatch = draftDirection
          ? site.directions.find((item) => item.slug === draftDirection || item.title === draftDirection)
          : null
        setDirections(site.directions)
        setOptionSets(site.optionSets || [])
        setSelectedSlug(initialDirection || draftMatch?.slug || site.directions[0]?.slug || '')
        setForm((current) => ({
          ...current,
          organizationType: current.organizationType || labels(site.optionSets || [], 'organization_type', fallbackOrganizationTypes)[0],
          projectStage: current.projectStage || labels(site.optionSets || [], 'project_stage', fallbackProjectStages)[0],
          urgency: current.urgency || labels(site.optionSets || [], 'urgency', fallbackUrgencyOptions)[0],
          budgetRange: current.budgetRange || labels(site.optionSets || [], 'budget_range', fallbackBudgetRanges)[0],
          expectedStart: current.expectedStart || labels(site.optionSets || [], 'expected_start', fallbackExpectedStarts)[0]
        }))
      })
      .catch((error) => toast(error instanceof Error ? error.message : '咨询方向加载失败'))
  })

  function patchFromUser(user: UserProfile) {
    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 || '',
      industry: current.industry || user.industry || '',
      city: current.city || user.city || ''
    }))
  }

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

  function validateCurrentStep() {
    if (step === 0 && (!form.company || !form.contactName || !form.contactPhone)) {
      toast('请补充单位、联系人和联系电话')
      return false
    }
    if (step === 1 && !selectedSlug) {
      toast('请选择咨询方向')
      return false
    }
    if (step === 2 && (!form.currentSituation || !form.requirement)) {
      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 = ensureLoggedIn(`/pages/consulting/apply/index${selectedSlug ? `?direction=${encodeURIComponent(selectedSlug)}` : ''}`)
    const token = getToken()
    if (!user || !token) return
    if (!validateCurrentStep()) return
    const selected = directions.find((item) => item.slug === selectedSlug) || directions[0]
    if (!selected) {
      toast('请先选择咨询方向')
      return
    }
    setSubmitting(true)
    try {
      const request = await backend.createConsultingRequest(token, {
        ...form,
        direction: selected.title,
        expectedStart: form.expectedStart || '仅先咨询评估',
        organizationType: form.organizationType || '其他组织'
      })
      toast('咨询需求已提交')
      Taro.redirectTo({ url: `/pages/account/consulting/detail/index?id=${encodeURIComponent(request.id)}` })
    } catch (error) {
      toast(error instanceof Error ? error.message : '咨询提交失败')
    } finally {
      setSubmitting(false)
    }
  }

  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)} />
                  <PickerField label="组织类型" value={form.organizationType} options={optionValues.organizationTypes} 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.industry} placeholder="如政务、制造、园区服务" onChange={(value) => patch('industry', value)} />
                  <TextInput label="所在城市" value={form.city} placeholder="如大连" onChange={(value) => patch('city', value)} />
                </>
              )}

              {step === 1 && (
                <>
                  <Text className="flow-label standalone">咨询方向</Text>
                  <ScrollView scrollX className="flow-chip-scroll" enhanced showScrollbar={false}>
                    {directions.map((item) => (
                      <Text key={item.id} className={item.slug === selectedSlug ? 'flow-chip active' : 'flow-chip'} onClick={() => setSelectedSlug(item.slug)}>{item.title}</Text>
                    ))}
                  </ScrollView>
                  <PickerField label="项目阶段" value={form.projectStage} options={optionValues.projectStages} onChange={(value) => patch('projectStage', value)} />
                  <PickerField label="沟通紧急度" value={form.urgency} options={optionValues.urgencyOptions} onChange={(value) => patch('urgency', value)} />
                  <PickerField label="预算范围" value={form.budgetRange} options={optionValues.budgetRanges} onChange={(value) => patch('budgetRange', value)} />
                  <PickerField label="期望启动时间" value={form.expectedStart} options={optionValues.expectedStarts} onChange={(value) => patch('expectedStart', value)} />
                  <TextInput label="方便联系时间" value={form.preferredContactTime} onChange={(value) => patch('preferredContactTime', value)} />
                </>
              )}

              {step === 2 && (
                <>
                  <TextArea label="当前现状" value={form.currentSituation} placeholder="目前遇到的问题、已有基础、内部推进阶段" onChange={(value) => patch('currentSituation', value)} />
                  <TextArea label="希望解决的问题" value={form.requirement} placeholder="希望顾问重点诊断、规划或产出的内容" onChange={(value) => patch('requirement', value)} />
                  <TextArea label="期望成果" value={form.goals} placeholder="方案、路线图、评估报告、培训沟通等" onChange={(value) => patch('goals', 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>
  )
}
