"use client"

import { useTranslations } from "next-intl"

import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import { Checkbox } from "@/shared/components/ui/checkbox"
import { cn } from "@/shared/lib/utils"
import { DEFAULT_CLASS_SUBJECTS } from "@/modules/classes/types"
import type { OnboardingStatus } from "@/modules/onboarding/types"
import { useOnboardingForm } from "@/modules/onboarding/hooks/use-onboarding-form"
import { ParentChildrenForm } from "@/modules/onboarding/components/parent-children-form"

interface OnboardingStepperProps {
  initialStatus: OnboardingStatus
}

/**
 * v3 i18n：所有文案通过 useTranslations 读取，支持 zh-CN / en 切换。
 *
 * P1-2 重构后结构：
 * - 状态与提交逻辑：useOnboardingForm Hook（hooks/use-onboarding-form.ts）
 * - 家长子女子表单：ParentChildrenForm（components/parent-children-form.tsx）
 * - 本文件：纯展示编排器，负责步骤切换、表单字段、按钮渲染
 */
export function OnboardingStepper({ initialStatus }: OnboardingStepperProps) {
  const t = useTranslations("onboarding")
  const tCommon = useTranslations("common.actions")

  const form = useOnboardingForm(initialStatus)
  const {
    step,
    isSubmitting,
    name,
    phone,
    address,
    classCodes,
    teacherSubjects,
    children,
    primaryRole,
    isStudent,
    isTeacher,
    isParent,
    stepKeys,
    currentStepId,
    maxStep,
    canSkip,
    setName,
    setPhone,
    setAddress,
    setClassCodes,
    toggleSubject,
    addChildRow,
    removeChildRow,
    updateChildRow,
    onNext,
    onBack,
    onSkip,
    onFinish,
  } = form

  // audit-P1-13：标题/描述/内容均按 currentStepId 渲染，不再依赖数字下标。
  const title = t(`steps.${currentStepId}`)
  const description =
    currentStepId === "roleConfirm"
      ? t("role.adminAssigned")
      : currentStepId === "basicInfo"
        ? t("form.name") + " · " + t("form.phone") + " · " + t("form.address")
        : currentStepId === "roleInfo"
          ? isParent
            ? t("parent.bindHint")
            : t("steps.roleInfo")
          : t("complete.readyHint")

  return (
    <div className="grid gap-6">
      <div className="grid gap-1.5">
        <h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
        <p className="text-sm text-muted-foreground">{description}</p>
      </div>

      <div
        className="flex items-center gap-2"
        role="progressbar"
        aria-label={t("progress.label")}
        aria-valuenow={step + 1}
        aria-valuemin={1}
        aria-valuemax={stepKeys.length}
      >
        {stepKeys.map((_, idx) => (
          <div
            key={idx}
            className={cn(
              "h-1 flex-1 rounded transition-colors",
              step >= idx ? "bg-primary" : "bg-muted"
            )}
          />
        ))}
      </div>

      {/* Step: 角色确认（只读） */}
      {currentStepId === "roleConfirm" ? (
        <div className="grid gap-2">
          <Label>{t("role.yourRole")}</Label>
          <div className="rounded-md border bg-muted/30 px-3 py-2.5 text-sm">
            <span className="font-medium">{t(`role.${primaryRole}`)}</span>
            {initialStatus.roles.all.length > 1 ? (
              <span className="ml-2 text-muted-foreground">
                ({t("role.allRoles", { roles: initialStatus.roles.all.join("、") })})
              </span>
            ) : null}
          </div>
          <p className="text-xs text-muted-foreground">{t("role.adminAssigned")}</p>
        </div>
      ) : null}

      {/* Step: 基础信息 */}
      {currentStepId === "basicInfo" ? (
        <div className="grid gap-4">
          <div className="grid gap-2">
            <Label htmlFor="onb_name">{t("form.name")} *</Label>
            <Input
              id="onb_name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              maxLength={50}
              required
            />
          </div>
          <div className="grid gap-2">
            <Label htmlFor="onb_phone">{t("form.phone")} *</Label>
            <Input
              id="onb_phone"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="11 位手机号"
              inputMode="tel"
              required
            />
          </div>
          <div className="grid gap-2">
            <Label htmlFor="onb_address">{t("form.address")}</Label>
            <Input
              id="onb_address"
              value={address}
              onChange={(e) => setAddress(e.target.value)}
              maxLength={200}
            />
          </div>
        </div>
      ) : null}

      {/* Step: 角色信息 */}
      {currentStepId === "roleInfo" ? (
        <div className="grid gap-4">
          {isTeacher ? (
            <>
              <div className="grid gap-2">
                <Label htmlFor="onb_codes_teacher">{t("teacher.classCodesOptional")}</Label>
                <Textarea
                  id="onb_codes_teacher"
                  value={classCodes}
                  onChange={(e) => setClassCodes(e.target.value)}
                  placeholder={t("teacher.classCodesPlaceholder")}
                />
                <p className="text-xs text-muted-foreground">{t("teacher.classCodesHint")}</p>
              </div>
              <div className="grid gap-2">
                <Label>{t("teacher.subjectsOptional")}</Label>
                <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
                  {DEFAULT_CLASS_SUBJECTS.map((s) => (
                    <label key={s} className="flex items-center gap-2 text-sm">
                      <Checkbox
                        checked={teacherSubjects.includes(s)}
                        onCheckedChange={() => toggleSubject(s)}
                      />
                      {s}
                    </label>
                  ))}
                </div>
                <p className="text-xs text-muted-foreground">{t("teacher.subjectsHint")}</p>
              </div>
            </>
          ) : null}

          {isStudent ? (
            <div className="grid gap-2">
              <Label htmlFor="onb_codes_student">{t("student.classCodesOptional")}</Label>
              <Textarea
                id="onb_codes_student"
                value={classCodes}
                onChange={(e) => setClassCodes(e.target.value)}
                placeholder={t("student.classCodesPlaceholder")}
              />
              <p className="text-xs text-muted-foreground">{t("student.classCodesHint")}</p>
            </div>
          ) : null}

          {isParent ? (
            <ParentChildrenForm
              childRows={children}
              isSubmitting={isSubmitting}
              onUpdate={updateChildRow}
              onAdd={addChildRow}
              onRemove={removeChildRow}
            />
          ) : null}
        </div>
      ) : null}

      {/* Step: 完成 */}
      {currentStepId === "complete" ? (
        <div className="rounded-md border bg-muted/30 px-4 py-4 text-sm">
          <div className="font-medium">{t("complete.ready")}</div>
          <div className="mt-1 text-muted-foreground">{t("complete.readyHint")}</div>
        </div>
      ) : null}

      {/* 底部按钮 */}
      <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-between">
        <div className="flex gap-2">
          <Button
            type="button"
            variant="outline"
            onClick={onBack}
            disabled={step === 0 || isSubmitting}
          >
            {tCommon("previous")}
          </Button>
          {canSkip ? (
            <Button
              type="button"
              variant="secondary"
              onClick={onSkip}
              disabled={isSubmitting}
            >
              {tCommon("skip")}
            </Button>
          ) : null}
        </div>

        <div className="flex justify-end gap-2">
          {step < maxStep ? (
            <Button type="button" onClick={onNext} disabled={isSubmitting}>
              {tCommon("next")}
            </Button>
          ) : (
            <Button type="button" onClick={onFinish} disabled={isSubmitting}>
              {isSubmitting ? tCommon("submitting") : tCommon("finish")}
            </Button>
          )}
        </div>
      </div>
    </div>
  )
}
