"use client"

import * as React from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import { toast } from "sonner"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Checkbox } from "@/shared/components/ui/checkbox"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import { cn } from "@/shared/lib/utils"
import { Loader2 } from "lucide-react"
import type { ActionState } from "@/shared/types/action-state"
import type { RegisterResult } from "@/modules/auth/types"

const ADULT_AGE = 18

function calcAge(birth: string): number | null {
  if (!birth) return null
  const birthDate = new Date(birth)
  if (Number.isNaN(birthDate.getTime())) return null
  const now = new Date()
  let age = now.getFullYear() - birthDate.getFullYear()
  const monthDiff = now.getMonth() - birthDate.getMonth()
  if (monthDiff < 0 || (monthDiff === 0 && now.getDate() < birthDate.getDate())) {
    age -= 1
  }
  return age >= 0 ? age : null
}

type RegisterFormProps = React.HTMLAttributes<HTMLDivElement> & {
  registerAction: (formData: FormData) => Promise<ActionState<RegisterResult>>
}

export function RegisterForm({ className, registerAction, ...props }: RegisterFormProps) {
  const t = useTranslations("auth.register")
  const [isLoading, setIsLoading] = React.useState<boolean>(false)
  const [birthDate, setBirthDate] = React.useState<string>("")
  const [agreedTerms, setAgreedTerms] = React.useState<boolean>(false)
  const [agreedGuardian, setAgreedGuardian] = React.useState<boolean>(false)
  const [guardianRelation, setGuardianRelation] = React.useState<string>("")
  const router = useRouter()

  const age = React.useMemo(() => calcAge(birthDate), [birthDate])
  const isMinor = age !== null && age < ADULT_AGE

  async function onSubmit(event: React.SyntheticEvent) {
    event.preventDefault()

    if (!agreedTerms) {
      toast.error(t("toast.needAgreeTerms"))
      return
    }
    if (isMinor && !agreedGuardian) {
      toast.error(t("toast.needGuardianConsent"))
      return
    }
    if (isMinor && !guardianRelation) {
      toast.error(t("toast.needGuardianRelation"))
      return
    }

    setIsLoading(true)
    try {
      const form = event.currentTarget as HTMLFormElement
      const formData = new FormData(form)
      const res = await registerAction(formData)

      if (res.success) {
        toast.success(res.message || t("toast.createSuccess"))
        router.push("/login")
        router.refresh()
      } else {
        toast.error(res.message || t("toast.createFailed"))
      }
    } catch {
      toast.error(t("toast.createFailed"))
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className={cn("grid gap-6", className)} {...props}>
      <div className="flex flex-col space-y-2 text-center">
        <h1 className="text-2xl font-semibold tracking-tight">{t("createAccount")}</h1>
        <p className="text-sm text-muted-foreground">
          {t("subtitleAlt")}
        </p>
      </div>
      <form onSubmit={onSubmit}>
        <div className="grid gap-4">
          <div className="grid gap-2">
            <Label htmlFor="name">{t("name")}</Label>
            <Input
              id="name"
              name="name"
              placeholder={t("namePlaceholder")}
              type="text"
              autoCapitalize="words"
              autoComplete="name"
              autoCorrect="off"
              disabled={isLoading}
            />
          </div>
          <div className="grid gap-2">
            <Label htmlFor="email">{t("email")}</Label>
            <Input
              id="email"
              name="email"
              placeholder="name@example.com"
              type="email"
              autoCapitalize="none"
              autoComplete="email"
              autoCorrect="off"
              disabled={isLoading}
            />
          </div>
          <div className="grid gap-2">
            <Label htmlFor="password">{t("password")}</Label>
            <Input
              id="password"
              name="password"
              type="password"
              autoComplete="new-password"
              disabled={isLoading}
            />
          </div>
          <div className="grid gap-2">
            <Label htmlFor="birthDate">{t("birthDate")}</Label>
            <Input
              id="birthDate"
              name="birthDate"
              type="date"
              disabled={isLoading}
              value={birthDate}
              onChange={(e) => setBirthDate(e.target.value)}
            />
            {age !== null && (
              <p className="text-xs text-muted-foreground">{t("currentAge", { age })}</p>
            )}
          </div>

          {/* audit-P2-3: 邀请码（可选，提供时覆盖默认 student 角色） */}
          <div className="grid gap-2">
            <Label htmlFor="invitationCode">{t("invitationCodeLabel")}</Label>
            <Input
              id="invitationCode"
              name="invitationCode"
              type="text"
              placeholder={t("invitationCodePlaceholder")}
              autoCapitalize="characters"
              autoCorrect="off"
              disabled={isLoading}
              maxLength={64}
            />
          </div>

          {isMinor && (
            <div className="grid gap-4 rounded-md border border-amber-200 bg-amber-50 p-4 dark:border-amber-900/50 dark:bg-amber-950/30">
              <p className="text-sm font-medium text-amber-900 dark:text-amber-200">
                {t("guardianSectionTitle")}
              </p>
              <div className="grid gap-2">
                <Label htmlFor="guardianName">{t("guardianName")}</Label>
                <Input
                  id="guardianName"
                  name="guardianName"
                  placeholder={t("guardianNamePlaceholder")}
                  type="text"
                  disabled={isLoading}
                  required={isMinor}
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="guardianPhone">{t("guardianPhone")}</Label>
                <Input
                  id="guardianPhone"
                  name="guardianPhone"
                  placeholder={t("guardianPhonePlaceholder")}
                  type="tel"
                  disabled={isLoading}
                  required={isMinor}
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="guardianRelation">{t("guardianRelation")}</Label>
                <Select value={guardianRelation} onValueChange={setGuardianRelation}>
                  <SelectTrigger id="guardianRelation">
                    <SelectValue placeholder={t("guardianRelationPlaceholder")} />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="父亲">{t("guardianRelationFather")}</SelectItem>
                    <SelectItem value="母亲">{t("guardianRelationMother")}</SelectItem>
                    <SelectItem value="其他法定监护人">{t("guardianRelationOther")}</SelectItem>
                  </SelectContent>
                </Select>
                <input
                  type="hidden"
                  name="guardianRelation"
                  value={guardianRelation}
                />
              </div>
            </div>
          )}

          <div className="flex items-start gap-2">
            <Checkbox
              id="agreeTerms"
              checked={agreedTerms}
              onCheckedChange={(v) => setAgreedTerms(v === true)}
              disabled={isLoading}
            />
            <input type="hidden" name="agreedTerms" value={agreedTerms ? "true" : "false"} />
            <Label htmlFor="agreeTerms" className="text-sm leading-relaxed font-normal">
              {t.rich("agreeTermsRich", {
                privacy: (chunks) => (
                  <Link
                    href="/privacy"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="mx-1 text-primary underline underline-offset-4 hover:opacity-80"
                  >
                    {chunks}
                  </Link>
                ),
                terms: (chunks) => (
                  <Link
                    href="/terms"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="mx-1 text-primary underline underline-offset-4 hover:opacity-80"
                  >
                    {chunks}
                  </Link>
                ),
              })}
            </Label>
          </div>

          {isMinor && (
            <div className="flex items-start gap-2">
              <Checkbox
                id="agreeGuardian"
                checked={agreedGuardian}
                onCheckedChange={(v) => setAgreedGuardian(v === true)}
                disabled={isLoading}
              />
              <input type="hidden" name="agreedGuardian" value={agreedGuardian ? "true" : "false"} />
              <Label htmlFor="agreeGuardian" className="text-sm leading-relaxed font-normal">
                {t("agreeGuardianLabel")}
              </Label>
            </div>
          )}

          <Button disabled={isLoading}>
            {isLoading && (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            )}
            {t("createAccount")}
          </Button>
        </div>
      </form>
      <p className="px-8 text-center text-sm text-muted-foreground">
        {t("alreadyHaveAccount")}{" "}
        <Link
          href="/login"
          className="underline underline-offset-4 hover:text-primary"
        >
          {t("loginNow")}
        </Link>
      </p>
    </div>
  )
}
