'use client'

import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation'
import { Suspense, useEffect, useMemo, useState } from 'react'
import { ArrowLeft } from 'lucide-react'
import { useApp } from '@/components/providers/AppProvider'
import { backend, type BackendConsultingOptionSet, type BackendSiteConsultingDirection } from '@/lib/backend'

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

function ConsultingApplyContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { hydrated, user, createConsultingRequest } = useApp()
  const [directions, setDirections] = useState<BackendSiteConsultingDirection[]>([])
  const [optionSets, setOptionSets] = useState<BackendConsultingOptionSet[]>([])
  const selectedDirection = useMemo(() => {
    const direction = searchParams.get('direction')
    return directions.find((item) => item.slug === direction || item.title === direction) ?? directions[0] ?? null
  }, [directions, searchParams])
  const applyRedirect = `/consulting/apply?direction=${selectedDirection?.slug ?? ''}`
  const loginRequiredHref = `/login-required?redirect=${encodeURIComponent(applyRedirect)}&action=consulting`
  const [step, setStep] = useState(0)
  const [form, setForm] = useState({
    company: '',
    contactName: '',
    contactPhone: '',
    email: '',
    direction: '',
    organizationType: '',
    industry: '',
    city: '',
    projectStage: '',
    urgency: '',
    budgetRange: '',
    expectedStart: '',
    currentSituation: '',
    requirement: '',
    goals: '',
    preferredContactTime: '',
  })
  const optionValues = useMemo(() => {
    const labels = (code: string, fallback: string[]) => {
      const set = optionSets.find((item) => item.code === code)
      const values = (set?.options || []).filter((item) => item.status !== 'disabled').map((item) => item.label)
      return values.length ? values : fallback
    }
    return {
      organizationTypes: labels('organization_type', organizationTypes),
      projectStages: labels('project_stage', projectStages),
      urgencyOptions: labels('urgency', urgencyOptions),
      budgetRanges: labels('budget_range', budgetRanges),
      expectedStarts: labels('expected_start', expectedStarts),
    }
  }, [optionSets])

  function updateField(field: keyof typeof form, value: string) {
    setForm((current) => ({ ...current, [field]: value }))
  }

  function goStep(nextStep: number) {
    setStep(nextStep)
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }

  async function submitConsultingRequest() {
    if (!user) {
      router.push(loginRequiredHref)
      return
    }

    const request = await createConsultingRequest({
      ...form,
      company: form.company || user.organization || '未填写机构',
      contactName: form.contactName || user.name || '平台用户',
      contactPhone: form.contactPhone || user.contactPhone || user.phone || '',
      email: form.email || user.email || '',
      industry: form.industry || user.industry || '',
      city: form.city || user.city || '',
    })
    if (!request) return
    router.push(`/consulting/apply/success?requestId=${request.id}`)
  }

  useEffect(() => {
    if (hydrated && !user) router.replace(loginRequiredHref)
  }, [hydrated, loginRequiredHref, router, user])

  useEffect(() => {
    void backend.siteConsulting()
      .then((site) => {
        setDirections(site.directions)
        setOptionSets(site.optionSets || [])
      })
      .catch(() => {
        setDirections([])
        setOptionSets([])
      })
  }, [])

  useEffect(() => {
    setForm((current) => ({
      ...current,
      organizationType: optionValues.organizationTypes.includes(current.organizationType) ? current.organizationType : optionValues.organizationTypes[0],
      projectStage: optionValues.projectStages.includes(current.projectStage) ? current.projectStage : optionValues.projectStages[0],
      urgency: optionValues.urgencyOptions.includes(current.urgency) ? current.urgency : optionValues.urgencyOptions[0],
      budgetRange: optionValues.budgetRanges.includes(current.budgetRange) ? current.budgetRange : optionValues.budgetRanges[0],
      expectedStart: optionValues.expectedStarts.includes(current.expectedStart) ? current.expectedStart : optionValues.expectedStarts[0],
    }))
  }, [optionValues])

  useEffect(() => {
    if (!directions.length) return
    setForm((current) => {
      if (current.direction && directions.some((item) => item.title === current.direction)) return current
      return { ...current, direction: selectedDirection?.title || directions[0].title }
    })
  }, [directions, selectedDirection])

  if (!hydrated || !user) {
    return (
      <section className="grid min-h-[calc(100vh-70px)] place-items-center bg-bg px-6 md:min-h-[calc(100vh-106px)]">
        <div className="text-sm font-bold text-muted">正在打开登录提醒...</div>
      </section>
    )
  }

  const steps = ['单位与联系人', '咨询方向', '背景与目标']
  const defaultCompany = user.organization || ''
  const defaultContactName = user.name || '平台用户'
  const defaultContactPhone = user.contactPhone || user.phone || ''
  const defaultEmail = user.email || ''
  const defaultCity = user.city || ''
  const defaultIndustry = user.industry || ''

  return (
    <section className="overflow-hidden bg-white">
      <div className="grid h-[calc(100dvh-71px)] min-h-0 md:h-[calc(100dvh-107px)] lg:grid-cols-[minmax(0,1fr)_520px]">
        <div className="relative hidden min-h-full overflow-hidden border-r border-line bg-[#f5f7fb] lg:block">
          <div className="grid h-full place-items-center px-12">
            <div className="w-full max-w-[380px]">
              <Link href="/consulting" className="inline-flex items-center gap-2 text-sm font-extrabold text-muted hover:text-brand">
                <ArrowLeft className="h-4 w-4" />
                规划咨询
              </Link>
              <div className="mt-8 text-xs font-extrabold tracking-[0.18em] text-soft">SERVICE REQUEST</div>
              <div className="mt-4 text-4xl font-extrabold leading-tight text-ink">提交咨询需求</div>
              <p className="mt-5 text-sm leading-7 text-muted">先说明方向、阶段和背景，顾问沟通后再进入方案、报价和服务执行。</p>
              <div className="mt-8 grid gap-2 text-sm font-bold text-muted">
                {steps.map((item, index) => (
                  <button key={item} type="button" onClick={() => goStep(index)} className={`border-l-2 px-4 py-3 text-left ${step === index ? 'border-brand bg-white text-ink' : 'border-line-dark bg-white/70 hover:border-brand hover:text-brand'}`}>
                    {String(index + 1).padStart(2, '0')} · {item}
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div className="flex min-h-0 flex-col border-l border-line bg-white">
          <div className="border-b border-line px-6 py-6 sm:px-8 lg:px-10">
            <div className="mb-4 lg:hidden">
              <Link href="/consulting" className="inline-flex items-center gap-2 text-sm font-extrabold text-muted hover:text-brand">
                <ArrowLeft className="h-4 w-4" />
                规划咨询
              </Link>
            </div>
            <h1 className="text-2xl font-extrabold leading-tight text-ink lg:text-3xl">提交咨询需求</h1>
            <p className="mt-3 text-sm leading-7 text-muted">第 {step + 1} / {steps.length} 步 · {steps[step]}</p>
            <div className="mt-5 flex items-center gap-2">
              {steps.map((item, index) => (
                <button
                  key={item}
                  type="button"
                  onClick={() => goStep(index)}
                  className={`h-2 rounded-full transition-all ${step === index ? 'w-10 bg-brand' : 'w-3 bg-line-dark hover:bg-muted'}`}
                  aria-label={`跳转到${item}`}
                />
              ))}
            </div>
          </div>

          <div className="min-h-0 flex-1 overflow-y-auto px-6 py-7 sm:px-8 lg:px-10">
            {step === 0 && (
              <div className="space-y-6">
                <div>
                  <h2 className="text-xl font-extrabold text-ink">单位与联系人</h2>
                  <p className="mt-2 text-sm leading-7 text-muted">用于确认需求来源和安排第一次沟通。</p>
                </div>
                <div className="grid gap-5 md:grid-cols-2">
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">单位名称</span>
                    <input required value={form.company || defaultCompany} onChange={(event) => updateField('company', event.target.value)} className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">组织类型</span>
                    <select value={form.organizationType} onChange={(event) => updateField('organizationType', event.target.value)} className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand">
                      {optionValues.organizationTypes.map((item) => <option key={item}>{item}</option>)}
                    </select>
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">联系人</span>
                    <input required value={form.contactName || defaultContactName} onChange={(event) => updateField('contactName', event.target.value)} className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">联系电话</span>
                    <input required value={form.contactPhone || defaultContactPhone} onChange={(event) => updateField('contactPhone', event.target.value)} className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">邮箱</span>
                    <input value={form.email || defaultEmail} onChange={(event) => updateField('email', event.target.value)} placeholder="用于接收资料或会议邀请" className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">所在城市</span>
                    <input value={form.city || defaultCity} onChange={(event) => updateField('city', event.target.value)} className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
                  </label>
                </div>
              </div>
            )}

            {step === 1 && (
              <div className="space-y-6">
                <div>
                  <h2 className="text-xl font-extrabold text-ink">咨询方向</h2>
                  <p className="mt-2 text-sm leading-7 text-muted">帮助顾问判断服务类型、项目成熟度和启动节奏。</p>
                </div>
                <div className="grid gap-5 md:grid-cols-2">
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">咨询方向</span>
                    <select value={form.direction} onChange={(event) => updateField('direction', event.target.value)} className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand">
                      {directions.map((item) => <option key={item.id}>{item.title}</option>)}
                    </select>
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">所属行业</span>
                    <input value={form.industry || defaultIndustry} onChange={(event) => updateField('industry', event.target.value)} placeholder="如制造、港航、政务、金融等" className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">项目阶段</span>
                    <select value={form.projectStage} onChange={(event) => updateField('projectStage', event.target.value)} className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand">
                      {optionValues.projectStages.map((item) => <option key={item}>{item}</option>)}
                    </select>
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">沟通紧急度</span>
                    <select value={form.urgency} onChange={(event) => updateField('urgency', event.target.value)} className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand">
                      {optionValues.urgencyOptions.map((item) => <option key={item}>{item}</option>)}
                    </select>
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">预算范围</span>
                    <select value={form.budgetRange} onChange={(event) => updateField('budgetRange', event.target.value)} className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand">
                      {optionValues.budgetRanges.map((item) => <option key={item}>{item}</option>)}
                    </select>
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">期望启动时间</span>
                    <select value={form.expectedStart} onChange={(event) => updateField('expectedStart', event.target.value)} className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand">
                      {optionValues.expectedStarts.map((item) => <option key={item}>{item}</option>)}
                    </select>
                  </label>
                </div>
              </div>
            )}

            {step === 2 && (
              <div className="space-y-6">
                <div>
                  <h2 className="text-xl font-extrabold text-ink">背景与目标</h2>
                  <p className="mt-2 text-sm leading-7 text-muted">用几段话说明现状、问题和希望得到的成果。</p>
                </div>
                <div className="grid gap-5">
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">当前现状</span>
                    <textarea required value={form.currentSituation} onChange={(event) => updateField('currentSituation', event.target.value)} rows={5} placeholder="请描述当前业务、数据、系统或项目背景。" className="w-full rounded-[4px] border border-line p-3 text-sm leading-7 outline-none focus:border-brand" />
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">希望解决的问题</span>
                    <textarea required value={form.requirement} onChange={(event) => updateField('requirement', event.target.value)} rows={5} placeholder="请写清希望解决的问题、需要我们协助的事项和约束条件。" className="w-full rounded-[4px] border border-line p-3 text-sm leading-7 outline-none focus:border-brand" />
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">期望成果</span>
                    <textarea value={form.goals} onChange={(event) => updateField('goals', event.target.value)} rows={4} placeholder="可填写期望产出，例如诊断报告、路线图、项目清单、评审意见等。" className="w-full rounded-[4px] border border-line p-3 text-sm leading-7 outline-none focus:border-brand" />
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">方便联系时间</span>
                    <input value={form.preferredContactTime} onChange={(event) => updateField('preferredContactTime', event.target.value)} placeholder="如工作日 9:00-17:30 或指定时间段" className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
                  </label>
                </div>
              </div>
            )}
          </div>

          <div className="border-t border-line bg-white/95 px-6 py-4 backdrop-blur sm:px-8 lg:px-10">
            <div className="mx-auto flex w-full max-w-[460px] gap-3">
              {step > 0 && (
                <button type="button" onClick={() => goStep(Math.max(step - 1, 0))} className="h-12 w-28 rounded-[4px] border border-line bg-white text-sm font-extrabold text-muted hover:border-brand hover:text-brand">
                  上一步
                </button>
              )}
              <button
                type="button"
                onClick={step < steps.length - 1 ? () => goStep(Math.min(step + 1, steps.length - 1)) : submitConsultingRequest}
                className={`${step > 0 ? 'flex-1' : 'mx-auto w-[360px]'} h-12 rounded-[4px] bg-brand text-sm font-extrabold text-white hover:bg-brand-dark`}
              >
                {step < steps.length - 1 ? '下一步' : '提交咨询意向'}
              </button>
            </div>
          </div>
        </div>
      </div>
    </section>
  )
}

export default function ConsultingApplyPage() {
  return (
    <Suspense fallback={<div className="bg-bg py-16 text-center text-muted">正在加载咨询表单...</div>}>
      <ConsultingApplyContent />
    </Suspense>
  )
}
