import { useEffect, useState, type FormEvent } from "react"
import { Link, useSearchParams } from "react-router-dom"
import { Card, Button, TextField, Label, Input } from "@heroui/react"
import { Check, X } from "lucide-react"
import { useAuth } from "../contexts/AuthContext"
import { sendRegisterCode, sendRegisterSmsCode } from "../api/auth"
import { SkeletonBlock, type SkeletonSpec } from "../utils/skeleton"
import { toast } from "../utils/toast"
import { verifyCaptcha } from "../utils/geetest"
import { getStoredAffiliateAttribution } from "../utils/affiliateAttribution"
import BrandLogo from "../components/BrandLogo"

type Mode = "email" | "sms"

const formSkeleton: SkeletonSpec[] = [
  { type: "stack", gap: 16, children: [
    { type: "stack", gap: 8, children: [
      { type: "rect", w: 64, h: 12 },
      { type: "rect", h: 40, rounded: 12 },
    ]},
    { type: "stack", gap: 8, children: [
      { type: "rect", w: 64, h: 12 },
      { type: "rect", h: 40, rounded: 12 },
    ]},
    { type: "stack", gap: 8, children: [
      { type: "rect", w: 64, h: 12 },
      { type: "rect", h: 40, rounded: 12 },
    ]},
    { type: "stack", gap: 8, children: [
      { type: "rect", w: 64, h: 12 },
      { type: "rect", h: 40, rounded: 12 },
    ]},
    { type: "rect", h: 44, rounded: 12 },
  ]},
]

const CN_PHONE = /^1[3-9]\d{9}$/

export default function Register() {
  const { register, registerBySms, isLoading: authLoading } = useAuth()
  const [searchParams] = useSearchParams()
  const inviteCode = searchParams.get("ref") || getStoredAffiliateAttribution()?.ref || undefined
  const [mode, setMode] = useState<Mode>("email")

  const [email, setEmail] = useState("")
  const [phone, setPhone] = useState("")
  const [username, setUsername] = useState("")
  const [code, setCode] = useState("")
  const [password, setPassword] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [mounting, setMounting] = useState(true)
  const [cooldown, setCooldown] = useState(0)
  const [sendingCode, setSendingCode] = useState(false)

  useEffect(() => {
    const t = setTimeout(() => setMounting(false), 350)
    return () => clearTimeout(t)
  }, [])

  useEffect(() => {
    if (cooldown <= 0) return
    const t = setInterval(() => setCooldown((c) => (c <= 1 ? 0 : c - 1)), 1000)
    return () => clearInterval(t)
  }, [cooldown])

  useEffect(() => {
    setCode("")
    setCooldown(0)
  }, [mode])

  const showSkeleton = authLoading || mounting

  const passwordChecks = [
    { label: "至少 8 个字符", valid: password.length >= 8 },
    { label: "包含字母", valid: /[a-zA-Z]/.test(password) },
    { label: "包含数字", valid: /\d/.test(password) },
  ]

  const handleSendCode = async () => {
    if (cooldown > 0 || sendingCode) return
    if (mode === "email") {
      if (!email) {
        toast.error("请先填写邮箱")
        return
      }
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        toast.error("邮箱格式不正确")
        return
      }
    } else {
      if (!phone) {
        toast.error("请先填写手机号")
        return
      }
      if (!CN_PHONE.test(phone)) {
        toast.error("手机号格式不正确")
        return
      }
    }
    setSendingCode(true)
    try {
      const captcha = await verifyCaptcha()
      const res = mode === "email"
        ? await sendRegisterCode(email, captcha)
        : await sendRegisterSmsCode(phone, captcha)
      setCooldown(res.data?.cooldown ?? 60)
      toast.success(mode === "email" ? "验证码已发送，请检查邮箱" : "验证码已发送，请查收短信")
    } catch (err: unknown) {
      const detail = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || (err instanceof Error ? err.message : "发送失败"))
    } finally {
      setSendingCode(false)
    }
  }

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault()
    if (password && password.length < 8) {
      toast.error("密码至少 8 位，或留空由系统生成")
      return
    }
    setIsLoading(true)
    try {
      const captcha = await verifyCaptcha()
      if (mode === "email") {
        await register(email, username, code, password || undefined, captcha, inviteCode)
      } else {
        await registerBySms(phone, username, code, password || undefined, captcha, inviteCode)
      }
      toast.success(password ? "注册成功" : "注册成功，可使用验证码登录")
    } catch (err: unknown) {
      const detail = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || (err instanceof Error ? err.message : "注册失败"))
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="qycw-page-enter flex flex-col gap-6">
      {/* Mobile logo */}
      <div className="flex lg:hidden mb-2">
        <BrandLogo className="h-24 object-contain" />
      </div>

      <div>
        {showSkeleton ? (
          <SkeletonBlock spec={[
            { type: "rect", w: 128, h: 24 },
            { type: "rect", w: 200, h: 12 },
          ]} />
        ) : (
          <div className="qycw-content-fade">
            <h2 className="text-xl font-bold text-gray-800">创建账户</h2>
            <p className="mt-1 text-sm text-gray-400">注册一个新账户开始使用</p>
          </div>
        )}
      </div>

      <Card.Root className="w-full border border-gray-100 bg-white/85 backdrop-blur-xl shadow-lg shadow-gray-200/60 rounded-2xl">
        <Card.Content className="p-6">
          {showSkeleton ? (
            <SkeletonBlock spec={formSkeleton} />
          ) : (
            <div className="qycw-content-fade flex flex-col gap-4">
              {/* Mode tabs */}
              <div className="relative grid grid-cols-2 rounded-xl bg-gray-100/80 p-1 text-sm">
                <button
                  type="button"
                  onClick={() => setMode("email")}
                  className={`qycw-auth-mode relative z-10 rounded-lg py-2 font-medium transition-colors duration-200 ${
                    mode === "email" ? "qycw-auth-text-primary" : "qycw-auth-text-muted"
                  }`}
                >
                  邮箱注册
                </button>
                <button
                  type="button"
                  onClick={() => setMode("sms")}
                  className={`qycw-auth-mode relative z-10 rounded-lg py-2 font-medium transition-colors duration-200 ${
                    mode === "sms" ? "qycw-auth-text-primary" : "qycw-auth-text-muted"
                  }`}
                >
                  手机注册
                </button>
                <span
                  aria-hidden
                  className="absolute top-1 bottom-1 left-1 w-[calc(50%-0.25rem)] rounded-lg bg-white shadow-sm transition-transform duration-300 ease-out"
                  style={{ transform: mode === "email" ? "translateX(0)" : "translateX(100%)" }}
                />
              </div>

              <form onSubmit={handleSubmit} className="flex flex-col gap-4">
                {mode === "email" ? (
                  <TextField.Root isRequired type="email" value={email} onChange={setEmail}>
                    <Label className="qycw-auth-text-muted text-xs font-medium">邮箱</Label>
                    <Input placeholder="you@example.com" className="mt-0.5" />
                  </TextField.Root>
                ) : (
                  <TextField.Root
                    isRequired
                    value={phone}
                    onChange={(v) => setPhone(v.replace(/\D/g, "").slice(0, 11))}
                  >
                    <Label className="qycw-auth-text-muted text-xs font-medium">手机号</Label>
                    <Input placeholder="11 位手机号" inputMode="numeric" maxLength={11} className="mt-0.5" />
                  </TextField.Root>
                )}

                <TextField.Root isRequired value={username} onChange={setUsername}>
                  <Label className="qycw-auth-text-muted text-xs font-medium">用户名</Label>
                  <Input placeholder="字母、数字、下划线" className="mt-0.5" />
                </TextField.Root>

                <div>
                  <Label className="qycw-auth-text-muted text-xs font-medium">
                    {mode === "email" ? "邮箱验证码" : "短信验证码"}
                  </Label>
                  <div className="mt-0.5 flex gap-2">
                    <TextField.Root
                      isRequired
                      value={code}
                      onChange={(v) => setCode(v.replace(/\D/g, "").slice(0, 6))}
                      aria-label={mode === "email" ? "邮箱验证码" : "短信验证码"}
                      className="min-w-0 flex-1"
                    >
                      <Input placeholder="6 位数字" inputMode="numeric" maxLength={6} />
                    </TextField.Root>
                    <Button
                      type="button"
                      onPress={handleSendCode}
                      isDisabled={cooldown > 0 || sendingCode}
                      className="qycw-auth-text-strong h-10 shrink-0 whitespace-nowrap rounded-xl bg-white px-3 text-xs font-medium shadow-sm shadow-gray-100/60 transition-all duration-200 ease-out hover:bg-gray-50 active:bg-gray-100 data-[disabled=true]:cursor-not-allowed data-[disabled=true]:opacity-60"
                    >
                      {sendingCode
                        ? "发送中..."
                        : cooldown > 0
                          ? `${cooldown}s 后重试`
                          : "获取验证码"}
                    </Button>
                  </div>
                </div>

                <div>
                  <TextField.Root type="password" value={password} onChange={setPassword}>
                    <Label className="qycw-auth-text-muted text-xs font-medium">
                      密码 <span className="text-gray-300 font-normal">（选填，留空则仅支持验证码登录）</span>
                    </Label>
                    <Input placeholder="留空则不设置密码" className="mt-0.5" />
                  </TextField.Root>
                  {password.length > 0 && (
                    <div className="mt-2 flex flex-wrap gap-x-4 gap-y-1">
                      {passwordChecks.map((check) => (
                        <div
                          key={check.label}
                          className={`flex items-center gap-1 text-xs ${
                            check.valid ? "text-sky-500" : "text-gray-300"
                          }`}
                        >
                          {check.valid ? <Check className="h-3 w-3" /> : <X className="h-3 w-3" />}
                          {check.label}
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                <Button
                  type="submit"
                  isDisabled={isLoading}
                  className="mt-1 w-full rounded-xl bg-sky-500 px-4 py-5 font-semibold !text-white shadow-md shadow-sky-200/70 transition-all duration-200 ease-out hover:-translate-y-0.5 hover:bg-sky-600 hover:shadow-lg hover:shadow-sky-300/70 active:translate-y-0 active:scale-[0.985] active:bg-sky-700 active:shadow-sm data-[disabled=true]:opacity-70 data-[disabled=true]:hover:translate-y-0 [&_*]:!text-white"
                >
                  {isLoading ? "注册中..." : "创建账户"}
                </Button>
              </form>
            </div>
          )}
        </Card.Content>
      </Card.Root>

      <p className="text-center text-sm text-gray-400">
        已有账户？{" "}
        <Link to="/login" className="font-medium text-sky-500 hover:text-sky-600 transition-colors">
          立即登录
        </Link>
      </p>
    </div>
  )
}
