"use client";

import { useState, useRef, type ChangeEvent, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Navigation from "@/components/Navigation";
import Avatar from "@/components/Avatar";

export default function RegisterPage() {
  const router = useRouter();
  const [formData, setFormData] = useState({
    email: "",
    username: "",
    password: "",
    confirmPassword: "",
    bio: "",
    characterClass: null as string | null,
    avatar: null as string | null,
  });
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [uploadingAvatar, setUploadingAvatar] = useState(false);
  const [step, setStep] = useState(1);
  const [userId, setUserId] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleChange = (
    e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };

  const handleAvatarUpload = async (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadingAvatar(true);
    setError("");

    try {
      const formDataUpload = new FormData();
      formDataUpload.append("file", file);

      const response = await fetch("/api/register/avatar", {
        method: "POST",
        body: formDataUpload,
      });

      if (response.ok) {
        const data = await response.json();
        setFormData({
          ...formData,
          avatar: data.url,
        });
      } else {
        const errorData = await response.json();
        setError(errorData.error || "Erreur lors de l'upload de l'avatar");
      }
    } catch (err) {
      console.error("Error uploading avatar:", err);
      setError("Erreur lors de l'upload de l'avatar");
    } finally {
      setUploadingAvatar(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };

  const handleStep1Submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");

    if (formData.password !== formData.confirmPassword) {
      setError("Les mots de passe ne correspondent pas");
      return;
    }

    if (formData.password.length < 6) {
      setError("Le mot de passe doit contenir au moins 6 caractères");
      return;
    }

    setLoading(true);

    try {
      const response = await fetch("/api/register", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email: formData.email,
          username: formData.username,
          password: formData.password,
          bio: null,
          characterClass: null,
          avatar: null,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        setError(data.error || "Une erreur est survenue");
        return;
      }

      setUserId(data.userId);
      setStep(2);
    } catch {
      setError("Une erreur est survenue");
    } finally {
      setLoading(false);
    }
  };

  const handleStep2Submit = async (e: FormEvent) => {
    e.preventDefault();
    setError("");

    if (!userId) {
      setError("Erreur: ID utilisateur manquant");
      return;
    }

    setLoading(true);

    try {
      const response = await fetch("/api/register/complete", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId,
          username: formData.username,
          bio: formData.bio && formData.bio.trim() ? formData.bio.trim() : null,
          characterClass: formData.characterClass || null,
          avatar: formData.avatar || null,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        setError(errorData.error || "Une erreur est survenue");
        return;
      }

      router.push("/login?registered=true");
    } catch (err) {
      console.error("Registration completion error:", err);
      setError(err instanceof Error ? err.message : "Une erreur est survenue");
    } finally {
      setLoading(false);
    }
  };

  return (
    <main className="min-h-screen bg-black relative">
      <Navigation />
      <section className="relative w-full min-h-screen flex flex-col items-center justify-center overflow-hidden pt-24">
        {/* Background Image */}
        <div
          className="absolute inset-0 bg-cover bg-center bg-no-repeat"
          style={{
            backgroundImage: `url('/got-2.jpg')`,
          }}
        >
          <div className="absolute inset-0 bg-gradient-to-b from-black/70 via-black/60 to-black/80"></div>
        </div>

        {/* Register Form */}
        <div className="relative z-10 w-full max-w-md mx-auto px-8">
          <div className="bg-black/80 border border-pixel-gold/30 rounded-lg p-8 backdrop-blur-sm">
            <h1 className="text-4xl font-gaming font-black mb-2 text-center">
              <span className="bg-gradient-to-r from-pixel-gold via-orange-400 to-pixel-gold bg-clip-text text-transparent">
                INSCRIPTION
              </span>
            </h1>
            <p className="text-gray-400 text-sm text-center mb-4">
              {step === 1
                ? "Créez votre compte pour commencer"
                : "Personnalisez votre profil"}
            </p>

            {/* Step Indicator */}
            <div className="flex items-center justify-center gap-2 mb-8">
              <div
                className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition ${
                  step >= 1
                    ? "bg-pixel-gold text-black"
                    : "bg-gray-700 text-gray-400"
                }`}
              >
                1
              </div>
              <div
                className={`h-px w-12 transition ${
                  step >= 2 ? "bg-pixel-gold" : "bg-gray-700"
                }`}
              />
              <div
                className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition ${
                  step >= 2
                    ? "bg-pixel-gold text-black"
                    : "bg-gray-700 text-gray-400"
                }`}
              >
                2
              </div>
            </div>

            {step === 1 ? (
              <form onSubmit={handleStep1Submit} className="space-y-6">
                {error && (
                  <div className="bg-red-900/50 border border-red-500/50 text-red-400 px-4 py-3 rounded text-sm">
                    {error}
                  </div>
                )}

                <div>
                  <label
                    htmlFor="email"
                    className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
                  >
                    Email
                  </label>
                  <input
                    id="email"
                    name="email"
                    type="email"
                    value={formData.email}
                    onChange={handleChange}
                    required
                    className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
                    placeholder="votre@email.com"
                  />
                </div>

                <div>
                  <label
                    htmlFor="username"
                    className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
                  >
                    Nom d&apos;utilisateur
                  </label>
                  <input
                    id="username"
                    name="username"
                    type="text"
                    value={formData.username}
                    onChange={handleChange}
                    required
                    className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
                    placeholder="VotrePseudo"
                  />
                </div>

                <div>
                  <label
                    htmlFor="password"
                    className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
                  >
                    Mot de passe
                  </label>
                  <input
                    id="password"
                    name="password"
                    type="password"
                    value={formData.password}
                    onChange={handleChange}
                    required
                    className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
                    placeholder="••••••••"
                  />
                </div>

                <div>
                  <label
                    htmlFor="confirmPassword"
                    className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
                  >
                    Confirmer le mot de passe
                  </label>
                  <input
                    id="confirmPassword"
                    name="confirmPassword"
                    type="password"
                    value={formData.confirmPassword}
                    onChange={handleChange}
                    required
                    className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
                    placeholder="••••••••"
                  />
                </div>

                <button
                  type="submit"
                  disabled={loading}
                  className="w-full px-6 py-3 border border-pixel-gold/50 bg-black/60 text-white uppercase text-sm tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {loading ? "Création..." : "Suivant"}
                </button>
              </form>
            ) : (
              <form onSubmit={handleStep2Submit} className="space-y-6">
                {error && (
                  <div className="bg-red-900/50 border border-red-500/50 text-red-400 px-4 py-3 rounded text-sm">
                    {error}
                  </div>
                )}

                {/* Avatar Selection */}
                <div>
                  <label className="block text-sm font-semibold text-gray-300 mb-3 uppercase tracking-wider">
                    Avatar (optionnel)
                  </label>
                  <div className="flex flex-col items-center gap-4">
                    {/* Preview */}
                    <div className="relative">
                      <Avatar
                        src={formData.avatar}
                        username={formData.username || "User"}
                        size="xl"
                        borderClassName="border-4 border-pixel-gold/50"
                        fallbackText={formData.username ? undefined : "?"}
                      />
                      {uploadingAvatar && (
                        <div className="absolute inset-0 bg-black/60 flex items-center justify-center rounded-full">
                          <div className="text-pixel-gold text-xs">
                            Upload...
                          </div>
                        </div>
                      )}
                    </div>

                    {/* Default Avatars */}
                    <div className="flex flex-col items-center gap-2 w-full">
                      <label className="text-pixel-gold text-xs uppercase tracking-widest">
                        Avatars par défaut
                      </label>
                      <div className="flex flex-wrap gap-2 justify-center">
                        {[
                          "/avatar-1.jpg",
                          "/avatar-2.jpg",
                          "/avatar-3.jpg",
                          "/avatar-4.jpg",
                          "/avatar-5.jpg",
                          "/avatar-6.jpg",
                        ].map((defaultAvatar) => (
                          <button
                            key={defaultAvatar}
                            type="button"
                            onClick={() =>
                              setFormData({
                                ...formData,
                                avatar: defaultAvatar,
                              })
                            }
                            className={`w-16 h-16 rounded-full border-2 overflow-hidden transition ${
                              formData.avatar === defaultAvatar
                                ? "border-pixel-gold scale-110"
                                : "border-pixel-gold/30 hover:border-pixel-gold/50"
                            }`}
                          >
                            <img
                              src={defaultAvatar}
                              alt="Avatar par défaut"
                              className="w-full h-full object-cover"
                            />
                          </button>
                        ))}
                      </div>
                    </div>

                    {/* Custom Upload */}
                    <div>
                      <input
                        ref={fileInputRef}
                        type="file"
                        accept="image/*"
                        onChange={handleAvatarUpload}
                        className="hidden"
                        id="avatar-upload"
                      />
                      <label
                        htmlFor="avatar-upload"
                        className="px-4 py-2 border border-pixel-gold/50 bg-black/40 text-white uppercase text-xs tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition cursor-pointer inline-block"
                      >
                        {uploadingAvatar
                          ? "Upload en cours..."
                          : "Upload un avatar custom"}
                      </label>
                    </div>
                  </div>
                </div>

                <div>
                  <label
                    htmlFor="username-step2"
                    className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
                  >
                    Nom d&apos;utilisateur
                  </label>
                  <input
                    id="username-step2"
                    name="username"
                    type="text"
                    value={formData.username}
                    onChange={handleChange}
                    required
                    className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
                    placeholder="VotrePseudo"
                    minLength={3}
                    maxLength={20}
                  />
                  <p className="text-gray-500 text-xs mt-1">3-20 caractères</p>
                </div>

                <div>
                  <label
                    htmlFor="bio"
                    className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
                  >
                    Bio (optionnel)
                  </label>
                  <textarea
                    id="bio"
                    name="bio"
                    value={formData.bio}
                    onChange={handleChange}
                    className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition resize-none"
                    rows={4}
                    maxLength={500}
                    placeholder="Parlez-nous de vous..."
                  />
                  <p className="text-gray-500 text-xs mt-1">
                    {formData.bio.length}/500 caractères
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-semibold text-gray-300 mb-3 uppercase tracking-wider">
                    Classe de Personnage (optionnel)
                  </label>
                  <div className="grid grid-cols-2 gap-2">
                    {[
                      { value: "WARRIOR", name: "Guerrier", icon: "⚔️" },
                      { value: "MAGE", name: "Mage", icon: "🔮" },
                      { value: "ROGUE", name: "Voleur", icon: "🗡️" },
                      { value: "RANGER", name: "Rôdeur", icon: "🏹" },
                      { value: "PALADIN", name: "Paladin", icon: "🛡️" },
                      { value: "ENGINEER", name: "Ingénieur", icon: "⚙️" },
                      { value: "MERCHANT", name: "Marchand", icon: "💰" },
                      { value: "SCHOLAR", name: "Érudit", icon: "📚" },
                      { value: "BERSERKER", name: "Berserker", icon: "🔥" },
                      {
                        value: "NECROMANCER",
                        name: "Nécromancien",
                        icon: "💀",
                      },
                    ].map((cls) => (
                      <button
                        key={cls.value}
                        type="button"
                        onClick={() =>
                          setFormData({
                            ...formData,
                            characterClass:
                              formData.characterClass === cls.value
                                ? null
                                : cls.value,
                          })
                        }
                        className={`p-3 border-2 rounded-lg text-left transition-all ${
                          formData.characterClass === cls.value
                            ? "border-pixel-gold bg-pixel-gold/20"
                            : "border-pixel-gold/30 bg-black/40 hover:border-pixel-gold/50"
                        }`}
                      >
                        <div className="flex items-center gap-2">
                          <span className="text-xl">{cls.icon}</span>
                          <span
                            className={`font-bold text-xs uppercase tracking-wider ${
                              formData.characterClass === cls.value
                                ? "text-pixel-gold"
                                : "text-white"
                            }`}
                          >
                            {cls.name}
                          </span>
                        </div>
                      </button>
                    ))}
                  </div>
                </div>

                <div className="flex gap-4">
                  <button
                    type="button"
                    onClick={() => setStep(1)}
                    className="flex-1 px-6 py-3 border border-gray-600/50 bg-black/40 text-gray-400 uppercase text-sm tracking-widest rounded hover:bg-gray-900/40 hover:border-gray-500 transition"
                  >
                    Retour
                  </button>
                  <button
                    type="submit"
                    disabled={loading}
                    className="flex-1 px-6 py-3 border border-pixel-gold/50 bg-black/60 text-white uppercase text-sm tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {loading ? "Finalisation..." : "Terminer"}
                  </button>
                </div>
              </form>
            )}

            <div className="mt-6 text-center">
              <p className="text-gray-400 text-sm">
                Déjà un compte ?{" "}
                <Link
                  href="/login"
                  className="text-pixel-gold hover:text-orange-400 transition"
                >
                  Se connecter
                </Link>
              </p>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}
