"use client";

import { useEffect, useState, useRef } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Check, X, Loader2 } from "lucide-react";
import { USERNAME_RE, SITE_NAME } from "@/lib/constants";
import { claimUsername } from "./actions";

export default function ClaimForm({ suggested }: { suggested: string }) {
  const router = useRouter();
  const [username, setUsername] = useState(suggested || "");
  const [status, setStatus] = useState<"idle" | "checking" | "free" | "taken" | "invalid" | "rate_limited" | "error">("idle");
  const cacheRef = useRef<Map<string, boolean>>(new Map());
  const [acceptedTerms, setAcceptedTerms] = useState(false);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const clean = username.trim().toLowerCase();
    if (!clean) return setStatus("idle");
    if (!USERNAME_RE.test(clean)) return setStatus("invalid");
    if (cacheRef.current.has(clean)) {
      setStatus(cacheRef.current.get(clean) ? "free" : "taken");
      return;
    }
    let active = true;
    setStatus("checking");
    const t = setTimeout(async () => {
      try {
        const response = await fetch(`/api/sys/id/check?username=${encodeURIComponent(clean)}&_t=${Date.now()}`, { cache: "no-store" });
        const result = await response.json();
        if (active) {
          if (result?.username && result.username !== clean) {
            return;
          }
          if (response.status === 429 || result?.rateLimited) {
            setStatus("rate_limited");
          } else if (!response.ok || !result?.ok) {
            setStatus("error");
          } else {
            cacheRef.current.set(clean, Boolean(result.available));
            setStatus(result.available ? "free" : "taken");
          }
        }
      } catch {
        if (active) setStatus("error");
      }
    }, 350);
    return () => { active = false; clearTimeout(t); };
  }, [username]);

  const claim = async () => {
    setError("");
    if (!USERNAME_RE.test(username)) return setError("1–20 lowercase letters, numbers, or _");
    if (status !== "free") return setError(status === "rate_limited" ? "You are checking handles too fast. Please wait a moment." : status === "error" ? "Could not check this name. Try again." : "Wait for the name availability check to finish.");
    if (!acceptedTerms) return setError("You must accept the Terms of Service to claim a username.");
    setLoading(true);
    try {
      const result = await claimUsername(username, true);
      if (result.error) return setError(result.error);
      router.push("/dashboard");
      router.refresh();
    } catch {
      setError("Could not claim this name. Check your connection and try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <main style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", padding: 24,
                   background: "radial-gradient(circle at 50% -10%, rgba(255, 255, 255, .12), var(--auth-shell, #08090b) 60%)",
                   fontFamily: "Outfit, Arial, sans-serif" }}>
      <div style={{ width: "min(400px,100%)", background: "var(--auth-card, linear-gradient(140deg, #101217, #0c0d10))", border: "1px solid var(--auth-card-border, rgba(0, 0, 0, .08))", borderRadius: 16, padding: 28, boxShadow: "0 20px 50px rgba(0,0,0,.15)" }}>
        <div style={{ display: "flex", justifyContent: "center", marginBottom: 20 }}>
          <Link href="/" aria-label={`${SITE_NAME} home`} style={{ display: "inline-flex", alignItems: "center", gap: 9, textDecoration: "none", color: "var(--auth-text, #000)", fontWeight: 600, fontSize: 20 }}>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src="/addons/logo.svg" alt="" width={26} height={26} />
            <span>{SITE_NAME}</span>
          </Link>
        </div>
        <h1 style={{ fontFamily: "Unbounded, sans-serif", fontSize: 20, fontWeight: 500, letterSpacing: "-0.5px", margin: "0 0 6px", color: "var(--auth-text, #000)" }}>
          Pick your name
        </h1>
        <p style={{ color: "var(--auth-dim, #240808)", fontSize: 13, margin: "0 0 20px" }}>Choose carefully; this becomes your public address.</p>

        <label className="lbl">Username</label>
        <div style={{ position: "relative" }}>
          <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--auth-muted, #1a0a0a)", fontSize: 13, pointerEvents: "none" }}>
            {SITE_NAME}/
          </span>
          <input className="field" style={{ paddingLeft: 76 }} value={username} autoFocus
                 onChange={(e) => { setError(""); setUsername(e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, "")); }} placeholder="pluto" />
          <span style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", display: "flex" }}>
            {status === "checking" && <Loader2 size={16} className="spin" style={{ color: "var(--auth-muted, #1a0a0a)" }} />}
            {status === "free" && <Check size={16} style={{ color: "var(--auth-good, #de8383)" }} />}
            {(status === "taken" || status === "invalid" || status === "rate_limited") && <X size={16} style={{ color: "var(--auth-bad, #f8d6d6)" }} />}
          </span>
        </div>
        <div style={{ minHeight: 18, fontSize: 12, marginTop: 5, color: status === "free" ? "var(--auth-good, #de8383)" : "var(--auth-bad, #f8d6d6)" }}>
          {status === "free" && "Available ✓"}
          {status === "taken" && "Already claimed"}
          {status === "invalid" && "1–20 lowercase letters, numbers, or _"}
          {status === "rate_limited" && "Checking too fast. Please wait a moment."}
          {status === "error" && "Could not check availability. Try again."}
        </div>

        {error && <p style={{ color: "var(--auth-bad, #f8d6d6)", fontSize: 13, marginTop: 6 }}>{error}</p>}

        <label
          style={{
            display: "flex",
            alignItems: "flex-start",
            gap: 10,
            marginTop: 16,
            cursor: "pointer",
            userSelect: "none",
            fontSize: 13,
            color: "var(--auth-sub, #3a0606)",
            lineHeight: 1.45,
          }}
        >
          <input
            type="checkbox"
            checked={acceptedTerms}
            onChange={(e) => {
              setAcceptedTerms(e.target.checked);
              if (error && error.toLowerCase().includes("terms")) setError("");
            }}
            style={{
              marginTop: 2,
              width: 16,
              height: 16,
              accentColor: "var(--auth-accent, #ffffff)",
              borderRadius: 4,
              cursor: "pointer",
              flexShrink: 0,
            }}
          />
          <span>
            I agree to the{" "}
            <Link
              href="/terms"
              target="_blank"
              rel="noopener noreferrer"
              style={{
                color: "var(--auth-accent, #ffffff)",
                textDecoration: "underline",
                textUnderlineOffset: 2,
              }}
              onClick={(e) => e.stopPropagation()}
            >
              Terms of Service
            </Link>{" "}
            and{" "}
            <Link
              href="/privacy"
              target="_blank"
              rel="noopener noreferrer"
              style={{
                color: "var(--auth-accent, #ffffff)",
                textDecoration: "underline",
                textUnderlineOffset: 2,
              }}
              onClick={(e) => e.stopPropagation()}
            >
              Privacy Policy
            </Link>
          </span>
        </label>

        <button
          className="btn"
          onClick={claim}
          disabled={loading || status !== "free" || !acceptedTerms}
          style={{
            background: "var(--lp-blue, #ffffff)",
            color: "#604a4a",
            border: "1px solid #ffffff",
            width: "100%",
            marginTop: 14,
            opacity: loading || status !== "free" || !acceptedTerms ? 0.6 : 1,
            cursor: loading || status !== "free" || !acceptedTerms ? "not-allowed" : "pointer",
          }}
        >
          {loading ? "Claiming…" : "Claim it"}
        </button>
        <style>{`.spin{animation:spin 1s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}`}</style>
      </div>
    </main>
  );
}
