"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { X, User } from "lucide-react";
import { validateNickname, sanitizeNickname } from "@/lib/utils";

export function NicknameModal({
  open,
  initial,
  title = "Adın ne?",
  onSubmit,
  onClose,
}: {
  open: boolean;
  initial?: string;
  title?: string;
  onSubmit: (nickname: string) => void;
  onClose?: () => void;
}) {
  const [value, setValue] = useState(initial ?? "");
  const [error, setError] = useState<string | null>(null);

  const submit = () => {
    const clean = sanitizeNickname(value);
    const err = validateNickname(clean);
    if (err) {
      setError(err);
      return;
    }
    setError(null);
    try {
      localStorage.setItem("nickname", clean);
    } catch {
      /* noop */
    }
    onSubmit(clean);
  };

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 backdrop-blur-sm"
          onClick={onClose}
        >
          <motion.div
            initial={{ opacity: 0, scale: 0.95, y: 12 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.95, y: 12 }}
            transition={{ type: "spring", damping: 26, stiffness: 320 }}
            onClick={(e) => e.stopPropagation()}
            className="w-full max-w-sm rounded-2xl border border-white/10 bg-[#141417] p-6 shadow-2xl"
          >
            <div className="mb-1 flex items-center justify-between">
              <h2 className="text-lg font-semibold text-white">{title}</h2>
              {onClose && (
                <button
                  onClick={onClose}
                  aria-label="Kapat"
                  className="rounded-lg p-1.5 text-zinc-400 transition hover:bg-white/5 hover:text-white"
                >
                  <X className="h-4 w-4" />
                </button>
              )}
            </div>
            <p className="mb-5 text-sm text-zinc-400">
              Odada görünecek ismini yaz. 2-20 karakter.
            </p>
            <div className="relative">
              <User className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-500" />
              <input
                autoFocus
                value={value}
                onChange={(e) => setValue(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter") submit();
                }}
                maxLength={20}
                placeholder="örn. Selahattin"
                className="w-full rounded-xl border border-white/10 bg-black/40 py-3 pl-10 pr-4 text-[15px] text-white placeholder:text-zinc-600 outline-none transition focus:border-white/25"
              />
            </div>
            {error && <p className="mt-2 text-[13px] text-red-400">{error}</p>}
            <button
              onClick={submit}
              className="mt-4 w-full rounded-xl bg-white py-3 text-sm font-semibold text-black transition hover:bg-zinc-200 active:scale-[0.99]"
            >
              Devam Et
            </button>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}

export function getStoredNickname(): string {
  if (typeof window === "undefined") return "";
  try {
    return sanitizeNickname(localStorage.getItem("nickname") ?? "");
  } catch {
    return "";
  }
}
