"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/Navigation";
import {
  Avatar,
  Input,
  Textarea,
  Button,
  Alert,
  Card,
  BackgroundSection,
  SectionTitle,
} from "@/components/ui";
import { CHARACTER_CLASSES } from "@/lib/character-classes";

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 />
      <BackgroundSection backgroundImage="/got-2.jpg" className="pt-24">
        {/* Register Form */}
        <div className="w-full max-w-4xl mx-auto px-8">
          <Card variant="dark" className="p-8">
            <SectionTitle
              variant="gradient"
              size="lg"
              className="mb-2 text-center"
            >
              INSCRIPTION
            </SectionTitle>
            <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 && <Alert variant="error">{error}</Alert>}

                <Input
                  id="email"
                  name="email"
                  type="email"
                  label="Email"
                  value={formData.email}
                  onChange={handleChange}
                  required
                  placeholder="votre@email.com"
                />

                <Input
                  id="username"
                  name="username"
                  type="text"
                  label="Nom d'utilisateur"
                  value={formData.username}
                  onChange={handleChange}
                  required
                  placeholder="VotrePseudo"
                />

                <Input
                  id="password"
                  name="password"
                  type="password"
                  label="Mot de passe"
                  value={formData.password}
                  onChange={handleChange}
                  required
                  placeholder="••••••••"
                />

                <Input
                  id="confirmPassword"
                  name="confirmPassword"
                  type="password"
                  label="Confirmer le mot de passe"
                  value={formData.confirmPassword}
                  onChange={handleChange}
                  required
                  placeholder="••••••••"
                />

                <Button
                  type="submit"
                  variant="primary"
                  size="lg"
                  disabled={loading}
                  className="w-full"
                >
                  {loading ? "Création..." : "Suivant"}
                </Button>
              </form>
            ) : (
              <form onSubmit={handleStep2Submit} className="space-y-6">
                {error && <Alert variant="error">{error}</Alert>}

                {/* 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">
                        <Button
                          variant="primary"
                          size="md"
                          as="span"
                          className="cursor-pointer"
                        >
                          {uploadingAvatar
                            ? "Upload en cours..."
                            : "Upload un avatar custom"}
                        </Button>
                      </label>
                    </div>
                  </div>
                </div>

                <Input
                  id="username-step2"
                  name="username"
                  type="text"
                  label="Nom d'utilisateur"
                  value={formData.username}
                  onChange={handleChange}
                  required
                  placeholder="VotrePseudo"
                  minLength={3}
                  maxLength={20}
                />
                <p className="text-gray-500 text-xs mt-1">3-20 caractères</p>

                <Textarea
                  id="bio"
                  name="bio"
                  label="Bio (optionnel)"
                  value={formData.bio}
                  onChange={handleChange}
                  rows={4}
                  maxLength={500}
                  showCharCount
                  placeholder="Parlez-nous de vous..."
                />

                <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 md:grid-cols-3 gap-3">
                    {CHARACTER_CLASSES.map((cls) => (
                      <button
                        key={cls.value}
                        type="button"
                        onClick={() =>
                          setFormData({
                            ...formData,
                            characterClass:
                              formData.characterClass === cls.value
                                ? null
                                : cls.value,
                          })
                        }
                        className={`p-4 border-2 rounded-lg text-left transition-all ${
                          formData.characterClass === cls.value
                            ? "border-pixel-gold bg-pixel-gold/20 shadow-lg shadow-pixel-gold/30"
                            : "border-pixel-gold/30 bg-black/40 hover:border-pixel-gold/50 hover:bg-black/60"
                        }`}
                      >
                        <div className="flex items-center gap-2 mb-1">
                          <span className="text-2xl">{cls.icon}</span>
                          <span
                            className={`font-bold text-sm uppercase tracking-wider ${
                              formData.characterClass === cls.value
                                ? "text-pixel-gold"
                                : "text-white"
                            }`}
                          >
                            {cls.name}
                          </span>
                        </div>
                        <p className="text-xs text-gray-400 leading-tight">
                          {cls.desc}
                        </p>
                      </button>
                    ))}
                  </div>
                </div>

                <div className="flex gap-4">
                  <Button
                    type="button"
                    variant="secondary"
                    size="lg"
                    onClick={() => setStep(1)}
                    className="flex-1"
                  >
                    Retour
                  </Button>
                  <Button
                    type="submit"
                    variant="primary"
                    size="lg"
                    disabled={loading}
                    className="flex-1"
                  >
                    {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>
          </Card>
        </div>
      </BackgroundSection>
    </main>
  );
}
