"use client"

import { FormEvent, useState } from "react"
import { Loader2 } from "lucide-react"

import { Button } from "@/components/ui/button"
import { Image } from "@/components/ui/image"
import { NAME_SAVED_EVENT } from "@/components/common/name-gate.component"

import { useVersionedRouter } from "@/hooks/use-versioned-router"
import { ApiEndpoint } from "@/lib/services/api.service"
import { apiCache } from "@/lib/services/cache.service"
import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"
import { cn } from "@/lib/utils"

const MAX = 40

/** «اسمت چیست؟»: one field after the first login; coaches, chats and the gallery show it. */
export default function WelcomeNameView() {
  const router = useVersionedRouter()
  const [name, setName] = useState("")
  const [error, setError] = useState<string | null>(null)
  const [{ loading }, save] = useApi({ url: ApiEndpoint("user", "update"), method: "PUT" })

  const clean = name.replace(/\s+/g, " ").trim()

  async function submit(e: FormEvent) {
    e.preventDefault()
    if (clean.length < 2) {
      setError("نامت را دست‌کم با دو حرف بنویس.")
      return
    }

    try {
      await save({ data: { name: clean } })
      apiCache.remove(ApiEndpoint("user", "me"))
      window.dispatchEvent(new CustomEvent(NAME_SAVED_EVENT))
      router.replace("/home")
    } catch (err) {
      setError(getApiErrorMessage(err))
    }
  }

  return (
    <form onSubmit={submit} noValidate 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-12 pb-6">
          <div className="flex justify-center mb-6">
            <Image src="/images/logo.png" alt="" width={56} height={56} />
          </div>
          <h1 className="text-title-1 font-extrabold text-ink">اسمت چیست؟</h1>
          <p className="text-body-sm text-ink-soft mt-1 mb-6 leading-7">
            مربی‌ها با این نام تو را می‌شناسند. در گالری فقط نام کوچک و حرف اول نام خانوادگی‌ات دیده می‌شود.
          </p>

          <label htmlFor="name" className="text-body-sm font-bold text-ink">نام و نام خانوادگی</label>
          <input
            id="name"
            autoFocus
            autoComplete="name"
            value={name}
            maxLength={MAX}
            onChange={(e) => { setName(e.target.value); setError(null) }}
            placeholder="مثلاً نگار احمدی"
            aria-invalid={!!error}
            aria-describedby="name-error"
            className={cn(
              "mt-2 w-full h-14 rounded-2xl border bg-canvas px-4 text-[1.0625rem] text-ink outline-none transition focus:ring-2",
              error ? "border-rose focus:ring-rose/20" : "border-line focus:border-sienna focus:ring-sienna/15",
            )}
          />
          <p id="name-error" role={error ? "alert" : undefined} className={cn("text-caption mt-2 min-h-5", error ? "text-rose" : "text-ink-soft")}>
            {error ?? "بعداً از «ویرایش حساب کاربری» هم می‌توانی عوضش کنی."}
          </p>
        </div>
      </div>

      <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" size="lg" className="w-full h-12 rounded-2xl" disabled={loading || clean.length < 2}>
          {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : "شروع کنیم"}
        </Button>
      </div>
    </form>
  )
}
