"use client"

import { useEffect, useRef, useState } from "react"
import { CountryCode } from "libphonenumber-js"
import { OTPInput, REGEXP_ONLY_DIGITS } from "input-otp"
import { ArrowRight, Pencil } from "lucide-react"

import { Button } from "@/components/ui/button"
import { Image } from "@/components/ui/image"
import PhoneField from "@/components/auth/phone-field.component"
import Link from "@/components/common/versioned-link"

import { useAuth } from "@/lib/provider/auth.provider"
import { useVersionedRouter } from "@/hooks/use-versioned-router"
import { AuthTokenType } from "@/lib/interfaces/auth/auth.interface"
import { ApiEndpoint } from "@/lib/services/api.service"
import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"
import { VerifyOtpResponseDto } from "@/lib/dto/auth.dto"
import { getDeviceName } from "@/lib/helpers/get-device-name.helper"
import { DEFAULT_COUNTRY, formatInternational, phoneError, toE164, toLatinDigits } from "@/lib/helpers/phone.helper"
import { faNumber } from "@/lib/helpers/format.helper"
import { clearReferral, pendingReferral } from "@/lib/services/referral.service"
import { cn } from "@/lib/utils"

const CODE_LENGTH = 6
const RESEND_SECONDS = 60

/** Sign in or sign up with a mobile number and an SMS code. */
export default function LoginView() {
  const { forceEnter, state: signedIn, loading: authLoading } = useAuth()
  const router = useVersionedRouter()

  const [step, setStep] = useState<"phone" | "code">("phone")
  const [country, setCountry] = useState<CountryCode>(DEFAULT_COUNTRY)
  const [national, setNational] = useState("")
  const [touched, setTouched] = useState(false)
  const [mobile, setMobile] = useState<string | null>(null)
  const [code, setCode] = useState("")
  const [error, setError] = useState<string | null>(null)
  const [secondsLeft, setSecondsLeft] = useState(RESEND_SECONDS)
  const [entering, setEntering] = useState(false)
  const deviceName = useRef("Unknown Device")

  // Already signed in (typed URL or the back button): replace, so going back skips the form.
  useEffect(() => {
    if (!authLoading && signedIn && !entering) router.replace("/home")
  }, [authLoading, signedIn, entering, router])

  const [{ loading: sending }, sendRequest] = useApi({ url: ApiEndpoint("auth", "otp-send"), method: "POST" })
  const [{ loading: verifying }, verifyRequest] = useApi<VerifyOtpResponseDto>({ url: ApiEndpoint("auth", "otp-verify"), method: "POST" })

  useEffect(() => {
    try {
      deviceName.current = getDeviceName()?.trim() || "Unknown Device"
    } catch {
      deviceName.current = "Unknown Device"
    }
  }, [])

  useEffect(() => {
    if (step !== "code" || secondsLeft <= 0) return
    const timer = setTimeout(() => setSecondsLeft((s) => s - 1), 1000)
    return () => clearTimeout(timer)
  }, [step, secondsLeft])

  const phoneProblem = phoneError(national, country)
  const shownPhoneError = touched ? phoneProblem : null

  async function sendCode(to: string) {
    setError(null)
    try {
      const { body } = await sendRequest({ data: { mobile: to, device_name: deviceName.current } })
      if (!body?.ok) {
        setError(body?.msg ?? "ارسال کد انجام نشد؛ دوباره تلاش کن.")
        return false
      }
      setMobile(to)
      setCode("")
      setSecondsLeft(RESEND_SECONDS)
      setStep("code")
      return true
    } catch (err) {
      setError(getApiErrorMessage(err))
      return false
    }
  }

  function submitPhone() {
    setTouched(true)
    const e164 = phoneProblem ? null : toE164(national, country)
    if (!e164 || sending) return
    void sendCode(e164)
  }

  async function verify(value: string) {
    if (!mobile || value.length !== CODE_LENGTH || verifying || entering) return
    setError(null)
    try {
      const { body } = await verifyRequest({
        data: { mobile, code: value, device_name: deviceName.current, ref: pendingReferral() },
      })
      if (!body?.ok) {
        setError(body?.msg ?? "کد درست نیست.")
        setCode("")
        return
      }
      setEntering(true)
      clearReferral()
      forceEnter!(body.data.id, mobile, [{ type: AuthTokenType.ACCESS, value: body.data.token }])
    } catch (err) {
      setError(getApiErrorMessage(err))
      setCode("")
    }
  }

  function changeNumber() {
    setStep("phone")
    setCode("")
    setError(null)
  }

  const busy = sending || verifying || entering

  return (
    <div className="flex flex-col h-[100dvh] bg-background text-right">
      <div className="flex-1 min-h-0 overflow-y-auto">
        <div className="w-full max-w-md mx-auto px-5 pt-10 pb-6 [@media(max-height:600px)]:pt-4">
          <div className="flex flex-col items-center mb-8 [@media(max-height:600px)]:hidden">
            <Image src="/images/logo.png" alt="" width={64} height={64} />
            <p className="font-brand text-display text-ink mt-4 leading-[1.8]">رنگوک</p>
            <p className="text-body-sm text-ink-soft font-bold">باشگاه تمرین هنر · هر روز کمی هنر</p>
          </div>

          {step === "phone" ? (
            <form id="login-form" noValidate onSubmit={(e) => { e.preventDefault(); submitPhone() }}>
              <h1 className="text-title-2 font-extrabold text-ink mb-1">ورود یا ثبت‌نام</h1>
              <p className="text-body-sm text-ink-soft mb-6">با شماره موبایلت وارد شو؛ اگر حساب نداری، همین‌جا ساخته می‌شود.</p>

              <PhoneField
                country={country}
                national={national}
                error={shownPhoneError ?? error}
                disabled={busy}
                onChange={(next) => { setCountry(next.country); setNational(next.national); setError(null) }}
                onBlur={() => national !== "" && setTouched(true)}
              />
            </form>
          ) : (
            <form id="login-form" noValidate onSubmit={(e) => { e.preventDefault(); void verify(code) }}>
              <button type="button" onClick={changeNumber} className="flex items-center gap-1 text-body-sm font-bold text-ink-soft mb-4">
                <ArrowRight className="w-4 h-4" aria-hidden="true" />
                بازگشت
              </button>

              <h1 className="text-title-2 font-extrabold text-ink mb-1">کد تأیید</h1>
              <p className="text-body-sm text-ink-soft mb-6 leading-7">
                کد {faNumber(CODE_LENGTH)} رقمی پیامک‌شده به{" "}
                <bdi dir="ltr" className="font-bold text-ink tabular-nums [unicode-bidi:isolate]">{mobile ? formatInternational(mobile) : ""}</bdi>{" "}
                را وارد کن.
                <button type="button" onClick={changeNumber} className="inline-flex items-center gap-1 text-sienna font-bold mr-2">
                  <Pencil className="w-3.5 h-3.5" aria-hidden="true" />
                  ویرایش
                </button>
              </p>

              <div dir="ltr" className="flex justify-center">
                <OTPInput
                  maxLength={CODE_LENGTH}
                  value={code}
                  onChange={(value) => { setError(null); setCode(toLatinDigits(value).replace(/\D/g, "")) }}
                  onComplete={(value: string) => void verify(toLatinDigits(value))}
                  pattern={REGEXP_ONLY_DIGITS}
                  inputMode="numeric"
                  autoComplete="one-time-code"
                  autoFocus
                  disabled={verifying || entering}
                  aria-label="کد تأیید"
                  containerClassName="flex gap-2"
                  render={({ slots }) => (
                    <>
                      {slots.map((slot, index) => (
                        <div
                          key={index}
                          className={cn(
                            "relative w-12 h-14 rounded-2xl border bg-canvas grid place-items-center text-title-3 font-bold text-ink tabular-nums transition",
                            error ? "border-rose" : slot.isActive ? "border-sienna ring-2 ring-sienna/15" : "border-line",
                          )}
                        >
                          {slot.char}
                          {slot.hasFakeCaret && <span className="absolute w-px h-6 bg-ink animate-caret-blink" aria-hidden="true" />}
                        </div>
                      ))}
                    </>
                  )}
                />
              </div>

              <p role={error ? "alert" : undefined} className={cn("text-caption text-center mt-3 min-h-5", error ? "text-rose" : "text-ink-soft")}>
                {error ?? (verifying || entering ? "در حال ورود…" : "")}
              </p>

              <div className="text-center text-body-sm text-ink-soft mt-4">
                {secondsLeft > 0 ? (
                  <span>ارسال دوباره‌ی کد تا {faNumber(secondsLeft)} ثانیه‌ی دیگر</span>
                ) : (
                  <button type="button" disabled={sending} onClick={() => mobile && void sendCode(mobile)} className="font-bold text-sienna disabled:opacity-50">
                    کد نرسید؟ دوباره بفرست
                  </button>
                )}
              </div>
            </form>
          )}
        </div>
      </div>

      {/* In the layout, not fixed: a fixed bar covered the code boxes when the keyboard was open. */}
      <div className="shrink-0 w-full max-w-md mx-auto px-5 pt-3 pb-[max(16px,env(safe-area-inset-bottom))] border-t border-line bg-background">
        <Button
          type="submit"
          form="login-form"
          size="lg"
          className="w-full h-12 rounded-2xl"
          disabled={busy || (step === "code" && code.length !== CODE_LENGTH)}
        >
          {step === "phone" ? (sending ? "در حال ارسال کد…" : "دریافت کد تأیید") : (verifying || entering ? "در حال ورود…" : "ورود")}
        </Button>
        {step === "phone" && (
          <p className="text-micro text-ink-soft text-center mt-2 leading-5">
            ورود یعنی پذیرش{" "}
            <Link href="/legal/terms" className="font-bold text-sienna">قوانین</Link>
            {" "}و{" "}
            <Link href="/legal/privacy" className="font-bold text-sienna">حریم خصوصی</Link>
            {" "}رنگوک.
          </p>
        )}
      </div>
    </div>
  )
}
