'use client'

import { useRouter, useSearchParams } from 'next/navigation'
import { Suspense, useEffect, useState } from 'react'
import { useApp } from '@/components/providers/AppProvider'
import { navigateReliably, safeInternalHref } from '@/lib/navigation'

const inputClass = 'h-11 w-full rounded-[4px] border border-line bg-white px-3 text-sm font-bold text-ink outline-none transition-colors placeholder:font-medium placeholder:text-muted/70 focus:border-brand'

type DraftProfile = {
  name: string
  contactPhone: string
  email: string
  organization: string
  title: string
  city: string
  industry: string
  address: string
  invoiceTitle: string
  taxNumber: string
  invoiceEmail: string
}

const emptyDraft: DraftProfile = {
  name: '',
  contactPhone: '',
  email: '',
  organization: '',
  title: '',
  city: '',
  industry: '',
  address: '',
  invoiceTitle: '',
  taxNumber: '',
  invoiceEmail: '',
}

function OnboardingContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { user, updateUserProfile, accountSyncing } = useApp()
  const [step, setStep] = useState<0 | 1 | 2>(0)
  const [draft, setDraft] = useState<DraftProfile>(emptyDraft)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const redirect = safeInternalHref(searchParams.get('redirect') || '/', '/')
  const safeRedirect = redirect.startsWith('/onboarding') ? '/' : redirect

  useEffect(() => {
    if (accountSyncing) return
    if (!user) {
      router.replace(`/login?redirect=${encodeURIComponent(redirect)}`)
      return
    }
    if (user.onboardingCompleted) navigateReliably(safeRedirect, (href) => router.replace(href))
  }, [accountSyncing, redirect, router, safeRedirect, user])

  useEffect(() => {
    if (!user) return
    setDraft({
      name: user.name || '',
      contactPhone: user.contactPhone || '',
      email: user.email || '',
      organization: user.organization || '',
      title: user.title || '',
      city: user.city || '',
      industry: user.industry || '',
      address: user.address || '',
      invoiceTitle: user.invoiceTitle || '',
      taxNumber: user.taxNumber || '',
      invoiceEmail: user.invoiceEmail || '',
    })
  }, [user])

  if (accountSyncing || !user || user.onboardingCompleted) {
    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-extrabold text-muted">跳转中...</div>
      </section>
    )
  }

  function updateDraft(key: keyof DraftProfile, value: string) {
    setDraft((current) => ({ ...current, [key]: value }))
  }

  async function finish() {
    setSaving(true)
    setError('')
    try {
      await updateUserProfile({
        name: draft.name || '平台用户',
        phone: user?.phone || '',
        contactPhone: draft.contactPhone,
        email: draft.email,
        organization: draft.organization,
        title: draft.title,
        city: draft.city,
        industry: draft.industry,
        address: draft.address,
        invoiceTitle: draft.invoiceTitle,
        taxNumber: draft.taxNumber,
        invoiceEmail: draft.invoiceEmail,
        onboardingCompleted: true,
      })
      navigateReliably(safeRedirect, (href) => router.replace(href))
    } catch (err) {
      setError(err instanceof Error ? err.message : '资料保存失败，请稍后重试')
    } finally {
      setSaving(false)
    }
  }

  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)_460px]">
        <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-[360px]">
              <div className="text-xs font-extrabold tracking-[0.18em] text-soft">ACCOUNT SETUP</div>
              <div className="mt-4 text-4xl font-extrabold leading-tight text-ink">完善账户资料</div>
              <div className="mt-6 grid gap-2 text-sm font-bold text-muted">
                <div className="border-l-2 border-brand bg-white px-4 py-3">联系信息</div>
                <div className="border-l-2 border-line-dark bg-white px-4 py-3">机构身份</div>
                <div className="border-l-2 border-line-dark bg-white px-4 py-3">发票信息</div>
              </div>
            </div>
          </div>
        </div>

        <div className="flex min-h-0 flex-col items-center justify-center overflow-y-auto border-l border-line bg-white px-6 py-6 sm:px-8 lg:px-12">
          <div className="w-full max-w-[420px] lg:max-w-none">
            <div className="mb-8">
              <h1 className="text-2xl font-extrabold leading-tight text-ink lg:text-3xl">完善资料</h1>
              <p className="mt-3 text-sm leading-7 text-muted">这些信息会用于后续订单、预约、发票和服务联系。</p>
              {error && <div className="mt-4 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}
            </div>

            <div className="min-h-[356px]">
              {step === 0 && (
                <form
                  onSubmit={(event) => {
                    event.preventDefault()
                    setStep(1)
                  }}
                  className="space-y-4"
                >
                  <div>
                    <label className="mb-2 block text-sm font-bold text-ink">姓名</label>
                    <input value={draft.name} onChange={(event) => updateDraft('name', event.target.value)} required placeholder="请输入姓名" className={inputClass} />
                  </div>
                  <div>
                    <label className="mb-2 block text-sm font-bold text-ink">联系电话</label>
                    <input value={draft.contactPhone} onChange={(event) => updateDraft('contactPhone', event.target.value)} required placeholder="用于订单、预约和服务联系" className={inputClass} />
                  </div>
                  <div>
                    <label className="mb-2 block text-sm font-bold text-ink">邮箱（可选）</label>
                    <input value={draft.email} onChange={(event) => updateDraft('email', event.target.value)} type="email" placeholder="用于接收资料、发票和通知" className={inputClass} />
                  </div>
                  <button className="mt-4 h-11 w-full rounded-[4px] bg-brand text-sm font-extrabold text-white hover:bg-brand-dark">下一步</button>
                </form>
              )}

              {step === 1 && (
                <form
                  onSubmit={(event) => {
                    event.preventDefault()
                    setStep(2)
                  }}
                  className="space-y-4"
                >
                  <div>
                    <label className="mb-2 block text-sm font-bold text-ink">所属机构（可选）</label>
                    <input value={draft.organization} onChange={(event) => updateDraft('organization', event.target.value)} placeholder="企业、单位或组织名称" className={inputClass} />
                  </div>
                  <div>
                    <label className="mb-2 block text-sm font-bold text-ink">职务（可选）</label>
                    <input value={draft.title} onChange={(event) => updateDraft('title', event.target.value)} placeholder="例如：信息化负责人" className={inputClass} />
                  </div>
                  <div className="grid gap-4 sm:grid-cols-2">
                    <div>
                      <label className="mb-2 block text-sm font-bold text-ink">所在城市（可选）</label>
                      <input value={draft.city} onChange={(event) => updateDraft('city', event.target.value)} placeholder="辽宁大连" className={inputClass} />
                    </div>
                    <div>
                      <label className="mb-2 block text-sm font-bold text-ink">行业方向（可选）</label>
                      <input value={draft.industry} onChange={(event) => updateDraft('industry', event.target.value)} placeholder="数据治理" className={inputClass} />
                    </div>
                  </div>
                  <div>
                    <label className="mb-2 block text-sm font-bold text-ink">联系地址（可选）</label>
                    <input value={draft.address} onChange={(event) => updateDraft('address', event.target.value)} placeholder="用于线下活动、资料寄送或服务对接" className={inputClass} />
                  </div>
                  <div className="flex gap-3 pt-2">
                    <button type="button" onClick={() => setStep(0)} className="h-11 flex-1 rounded-[4px] border border-line bg-white text-sm font-bold text-muted hover:border-brand hover:text-brand">上一步</button>
                    <button className="h-11 flex-1 rounded-[4px] bg-brand text-sm font-extrabold text-white hover:bg-brand-dark">下一步</button>
                  </div>
                </form>
              )}

              {step === 2 && (
                <form
                  onSubmit={(event) => {
                    event.preventDefault()
                    finish()
                  }}
                  className="space-y-4"
                >
                  <div>
                    <label className="mb-2 block text-sm font-bold text-ink">发票抬头（可选）</label>
                    <input value={draft.invoiceTitle} onChange={(event) => updateDraft('invoiceTitle', event.target.value)} placeholder="单位名称或个人姓名" className={inputClass} />
                  </div>
                  <div>
                    <label className="mb-2 block text-sm font-bold text-ink">纳税人识别号（可选）</label>
                    <input value={draft.taxNumber} onChange={(event) => updateDraft('taxNumber', event.target.value)} placeholder="企业发票填写" className={inputClass} />
                  </div>
                  <div>
                    <label className="mb-2 block text-sm font-bold text-ink">接收邮箱（可选）</label>
                    <input value={draft.invoiceEmail} onChange={(event) => updateDraft('invoiceEmail', event.target.value)} type="email" placeholder="用于接收电子发票" className={inputClass} />
                  </div>
                  <div className="flex gap-3 pt-2">
                    <button type="button" onClick={() => setStep(1)} className="h-11 flex-1 rounded-[4px] border border-line bg-white text-sm font-bold text-muted hover:border-brand hover:text-brand">上一步</button>
                    <button disabled={saving} className="h-11 flex-1 rounded-[4px] bg-brand text-sm font-extrabold text-white hover:bg-brand-dark disabled:opacity-60">{saving ? '保存中...' : '完成'}</button>
                  </div>
                </form>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>
  )
}

export default function OnboardingPage() {
  return (
    <Suspense fallback={<section className="grid min-h-[calc(100vh-70px)] place-items-center bg-bg px-6"><div className="text-sm font-extrabold text-muted">正在加载资料页...</div></section>}>
      <OnboardingContent />
    </Suspense>
  )
}
