"use client"

import * as React from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { useSession } from "next-auth/react"
import { useTranslations } from "next-intl"
import { toast } from "sonner"

import { type ClassSubject } from "@/modules/classes/types"
import { completeOnboardingAction } from "@/modules/onboarding/actions"
import {
  EMPTY_CHILD_ROW,
  type ChildRow,
  type OnboardingStatus,
  type OnboardingStepConfig,
  getOnboardingStepsForRole,
} from "@/modules/onboarding/types"

function clampStep(value: number, max: number): number {
  if (!Number.isFinite(value)) return 0
  return Math.max(0, Math.min(max, Math.floor(value)))
}

/**
 * Onboarding 表单状态与处理逻辑 Hook（P1-2 拆分时从 onboarding-stepper.tsx 提取）。
 *
 * 设计目标：
 * - 将所有 React state / 导航 / 提交逻辑集中在此处
 * - onboarding-stepper.tsx 仅负责 UI 渲染，状态由本 Hook 提供
 * - URL query 参数 `?step=` 持久化当前步骤（支持刷新保持）
 */
export function useOnboardingForm(initialStatus: OnboardingStatus) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { update } = useSession()
  const t = useTranslations("onboarding")

  const [isSubmitting, setIsSubmitting] = React.useState(false)

  const [name, setName] = React.useState(initialStatus.name ?? "")
  const [phone, setPhone] = React.useState("")
  const [address, setAddress] = React.useState("")
  const [classCodes, setClassCodes] = React.useState("")
  const [teacherSubjects, setTeacherSubjects] = React.useState<ClassSubject[]>([])
  const [children, setChildren] = React.useState<ChildRow[]>([{ ...EMPTY_CHILD_ROW }])

  const primaryRole = initialStatus.roles.primary
  const isAdmin = primaryRole === "admin"
  const isStudent = primaryRole === "student"
  const isTeacher = primaryRole === "teacher"
  const isParent = primaryRole === "parent"

  // audit-P1-13：步骤列表由配置驱动，根据角色过滤。
  // admin 与 grade_head/teaching_head 跳过 roleInfo 步骤（无需填写内容）。
  const stepConfigs = getOnboardingStepsForRole(primaryRole)
  const stepKeys = stepConfigs.map((c) => c.id)
  const maxStep = stepKeys.length - 1

  // P1-1：URL query 参数持久化当前步骤（clamp 范围与角色适用的步骤数一致）
  const initialStep = clampStep(Number(searchParams.get("step") ?? "0"), maxStep)
  const [step, setStep] = React.useState(initialStep)

  // audit-P1-13：以步骤 id（而非数字下标）判断当前步骤，避免角色过滤导致下标偏移。
  const currentStepId = stepConfigs[step]?.id
  const currentStepConfig: OnboardingStepConfig | undefined = stepConfigs[step]

  const canNext = React.useMemo(() => {
    if (currentStepId === "basicInfo") {
      return name.trim().length > 0 && phone.trim().length > 0
    }
    if (currentStepId === "roleInfo" && isParent) {
      const validChildren = children.filter(
        (c) => c.childEmail.trim() && c.childBirthDate.trim() && c.childPhoneSuffix.trim(),
      )
      return validChildren.length > 0
    }
    return true
  }, [currentStepId, name, phone, isParent, children])

  const toggleSubject = (subject: ClassSubject) => {
    setTeacherSubjects((prev) =>
      prev.includes(subject) ? prev.filter((s) => s !== subject) : [...prev, subject],
    )
  }

  const goToStep = React.useCallback(
    (next: number) => {
      const clamped = Math.max(0, Math.min(maxStep, next))
      const params = new URLSearchParams(searchParams.toString())
      params.set("step", String(clamped))
      router.replace(`/onboarding?${params.toString()}`, { scroll: false })
      setStep(clamped)
    },
    [maxStep, router, searchParams],
  )

  const onNext = () => {
    if (currentStepId === "basicInfo" && !canNext) {
      toast.error(t("validation.needNamePhone"))
      return
    }
    if (currentStepId === "roleInfo" && isParent && !canNext) {
      toast.error(t("validation.needOneChild"))
      return
    }
    goToStep(step + 1)
  }

  const onBack = () => {
    goToStep(step - 1)
  }

  // audit-P1-13：跳过按钮可见性由配置驱动（OnboardingStepConfig.canSkip）。
  // parent 的 roleInfo 步骤 canSkip 返回 false，故不显示跳过按钮。
  const canSkip = currentStepConfig?.canSkip?.(primaryRole) ?? false
  const onSkip = () => {
    goToStep(maxStep)
  }

  const addChildRow = () => {
    setChildren((prev) => [...prev, { ...EMPTY_CHILD_ROW }])
  }
  const removeChildRow = (idx: number) => {
    setChildren((prev) => (prev.length === 1 ? prev : prev.filter((_, i) => i !== idx)))
  }
  const updateChildRow = (idx: number, patch: Partial<ChildRow>) => {
    setChildren((prev) => prev.map((row, i) => (i === idx ? { ...row, ...patch } : row)))
  }

  const onFinish = async () => {
    if (isParent) {
      const validChildren = children.filter(
        (c) => c.childEmail.trim() && c.childBirthDate.trim() && c.childPhoneSuffix.trim(),
      )
      if (validChildren.length === 0) {
        toast.error(t("validation.needOneChild"))
        return
      }
    }

    setIsSubmitting(true)
    try {
      const formData = new FormData()
      formData.set("name", name.trim())
      formData.set("phone", phone.trim())
      formData.set("address", address.trim())
      // v3：邀请码统一大写化后提交
      formData.set("classCodes", classCodes.trim().toUpperCase())
      formData.set("teacherSubjects", JSON.stringify(teacherSubjects))
      const validChildren = children.filter(
        (c) => c.childEmail.trim() && c.childBirthDate.trim() && c.childPhoneSuffix.trim(),
      )
      formData.set("children", JSON.stringify(validChildren))

      const result = await completeOnboardingAction(null, formData)
      if (!result.success) {
        toast.error(result.message ?? t("toast.submitFailed"))
        return
      }

      if (result.message && result.message.includes("绑定失败")) {
        toast.warning(result.message)
      } else {
        toast.success(t("toast.completeSuccess"))
      }

      await update?.()
      const target = result.data?.defaultPath ?? "/dashboard"
      router.push(target)
      router.refresh()
    } catch (e) {
      const msg = e instanceof Error ? e.message : t("toast.submitFailed")
      toast.error(msg)
    } finally {
      setIsSubmitting(false)
    }
  }

  return {
    // state
    step,
    isSubmitting,
    name,
    phone,
    address,
    classCodes,
    teacherSubjects,
    children,
    // derived
    primaryRole,
    isAdmin,
    isStudent,
    isTeacher,
    isParent,
    // audit-P1-13：暴露 stepConfigs + currentStepId，组件按配置渲染而非数字下标
    stepConfigs,
    stepKeys,
    currentStepId,
    maxStep,
    canNext,
    canSkip,
    // setters
    setName,
    setPhone,
    setAddress,
    setClassCodes,
    toggleSubject,
    // children handlers
    addChildRow,
    removeChildRow,
    updateChildRow,
    // navigation
    onNext,
    onBack,
    onSkip,
    onFinish,
  }
}

export type UseOnboardingFormReturn = ReturnType<typeof useOnboardingForm>
