import { useMemo } from "react"
import { Link, useNavigate } from "react-router-dom"
import { toast } from "sonner"

import { Button } from "../../components/ui/button"
import { Input } from "../../components/ui/input"
import { useAuthFlow } from "../../context/AuthFlowContext"
import { useTranslation } from "../../hooks/useTranslation"
import { AuthPanel } from "./AuthPanel"
import { formatCooldown } from "./utils"

export function SignupMobilePage() {
  const navigate = useNavigate()
  const { t, lang } = useTranslation()
  const { state, setMobile, markOtpSendPending, clearOtpDelivery } = useAuthFlow()
  const isRtl = lang === "fa"

  const alert = useMemo(() => {
    if (state.cooldowns.signupOtpSend <= 0) {
      return null
    }

    const formatted = formatCooldown(state.cooldowns.signupOtpSend, isRtl)
    return {
      title: t.login.throttle.title,
      description: t.login.throttle.otpSendMessage(formatted),
    }
  }, [isRtl, state.cooldowns.signupOtpSend, t.login.throttle])

  const cooldownLabel =
    state.cooldowns.signupOtpSend > 0
      ? t.login.throttle.countdownLabel(formatCooldown(state.cooldowns.signupOtpSend, isRtl))
      : null

  const handleContinue = async () => {
    if (!state.signup.mobile) {
      toast.error(t.login.toasts.enterMobile)
      return
    }

    clearOtpDelivery("signup")
    markOtpSendPending("signup")
    navigate("/auth/signup/verify")
  }

  return (
    <AuthPanel
      title={t.login.signupTitle}
      description={t.login.signupDescription}
      alert={alert}
    >
      <div className="grid gap-4">
        <Input
          id="signup-mobile"
          placeholder={t.login.mobilePlaceholder}
          type="tel"
          dir="ltr"
          maxLength={11}
          value={state.signup.mobile}
          onChange={(event) => setMobile("signup", event.target.value)}
          className={`h-11 ${isRtl ? "text-end" : "text-start"}`}
        />

        <Button
          onClick={handleContinue}
          disabled={state.cooldowns.signupOtpSend > 0}
          className="h-11 w-full"
        >
          {cooldownLabel || t.login.sendSignupCode}
        </Button>

        <div className="text-center text-sm text-slate-500 dark:text-slate-400">
          {t.login.haveAccount}{" "}
          <Link
            to="/auth/login"
            className="font-medium text-blue-600 transition-colors hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300"
          >
            {t.login.signIn}
          </Link>
        </div>
      </div>
    </AuthPanel>
  )
}
