"use client";

import { FormEvent, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  ArrowRight,
  Loader2,
  Lock,
  Mail,
  Phone,
  User,
} from "lucide-react";

export default function RegisterPage() {
  const router = useRouter();

  const [firstName, setFirstName] =
    useState("");

  const [lastName, setLastName] =
    useState("");

  const [email, setEmail] =
    useState("");

  const [phone, setPhone] =
    useState("");

  const [password, setPassword] =
    useState("");

  const [confirmPassword, setConfirmPassword] =
    useState("");

  const [loading, setLoading] =
    useState(false);

  const [error, setError] =
    useState("");

  async function handleSubmit(
    event: FormEvent<HTMLFormElement>
  ) {
    event.preventDefault();

    setError("");

    if (
      password !== confirmPassword
    ) {
      setError(
        "Les mots de passe ne correspondent pas."
      );

      return;
    }

    setLoading(true);

    try {
      const response = await fetch(
        "/api/auth/register",
        {
          method: "POST",
          headers: {
            "Content-Type":
              "application/json",
          },
          body: JSON.stringify({
            firstName,
            lastName,
            email,
            phone,
            password,
          }),
        }
      );

      const data =
        await response.json();

      if (!response.ok) {
        setError(
          data.message ||
            "Impossible de créer le compte."
        );

        return;
      }

      router.push("/login");
    } catch (error) {
      console.error(
        "Erreur inscription :",
        error
      );

      setError(
        "Une erreur est survenue. Veuillez réessayer."
      );
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="min-h-screen bg-hh-night-deep text-white">
      <div className="grid min-h-screen lg:grid-cols-2">
        {/* ================================================== */}
        {/* PARTIE VISUELLE */}
        {/* ================================================== */}

        <div className="relative hidden overflow-hidden lg:block">
          <div className="absolute inset-0 bg-[url('/images/3.jpg')] bg-cover bg-center" />

          <div className="absolute inset-0 bg-gradient-to-br from-black/80 via-hh-night/70 to-hh-night-deep/95" />

          <div className="relative z-10 flex h-full flex-col justify-between p-12 xl:p-16">
            <Link
              href="/"
              className="font-serif text-3xl font-semibold tracking-wide text-hh-gold"
            >
              Happy Hours
            </Link>

            <div className="max-w-lg">
              <div className="mb-6 h-px w-16 bg-hh-gold" />

              <h1 className="font-serif text-5xl leading-tight xl:text-6xl">
                Entrez dans
                <br />
                l'expérience
                <br />
                <span className="text-hh-gold">
                  Happy Hours.
                </span>
              </h1>

              <p className="mt-6 max-w-md text-sm leading-7 text-white/65">
                Créez votre compte et
                profitez pleinement de votre
                expérience : commandes,
                réservations et avantages
                exclusifs.
              </p>
            </div>

            <p className="text-xs tracking-wider text-white/35">
              © {new Date().getFullYear()} Happy Hours
            </p>
          </div>
        </div>

        {/* ================================================== */}
        {/* FORMULAIRE */}
        {/* ================================================== */}

        <div className="flex min-h-screen items-center justify-center overflow-y-auto bg-hh-cream px-5 py-12 text-foreground">
          <div className="w-full max-w-md">
            {/* Logo mobile */}

            <Link
              href="/"
              className="mb-10 block text-center font-serif text-3xl font-semibold text-hh-gold-dark lg:hidden"
            >
              Happy Hours
            </Link>

            <div className="mb-8">
              <span className="hh-badge px-4 py-2">
                Créer un compte
              </span>

              <h2 className="mt-6 font-serif text-4xl font-semibold text-hh-night">
                Rejoignez Happy Hours
              </h2>

              <p className="mt-3 text-sm leading-6 text-muted-foreground">
                Créez votre compte pour
                profiter de toute
                l'expérience Happy Hours.
              </p>
            </div>

            {error && (
              <div className="mb-6 rounded-xl border border-destructive/20 bg-destructive/5 px-4 py-3 text-sm text-destructive">
                {error}
              </div>
            )}

            <form
              onSubmit={handleSubmit}
              className="space-y-4"
            >
              {/* PRÉNOM / NOM */}

              <div className="grid gap-4 sm:grid-cols-2">
                <div>
                  <label
                    htmlFor="firstName"
                    className="mb-2 block text-sm font-medium"
                  >
                    Prénom
                  </label>

                  <div className="relative">
                    <User
                      size={17}
                      className="absolute left-4 top-1/2 -translate-y-1/2 text-muted-foreground"
                    />

                    <input
                      id="firstName"
                      type="text"
                      value={firstName}
                      onChange={(event) =>
                        setFirstName(
                          event.target.value
                        )
                      }
                      placeholder="Votre prénom"
                      autoComplete="given-name"
                      required
                      className="h-13 w-full rounded-xl border border-border bg-white pl-11 pr-4 text-sm outline-none transition focus:border-hh-gold focus:ring-2 focus:ring-hh-gold/20"
                    />
                  </div>
                </div>

                <div>
                  <label
                    htmlFor="lastName"
                    className="mb-2 block text-sm font-medium"
                  >
                    Nom
                  </label>

                  <input
                    id="lastName"
                    type="text"
                    value={lastName}
                    onChange={(event) =>
                      setLastName(
                        event.target.value
                      )
                    }
                    placeholder="Votre nom"
                    autoComplete="family-name"
                    required
                    className="h-13 w-full rounded-xl border border-border bg-white px-4 text-sm outline-none transition focus:border-hh-gold focus:ring-2 focus:ring-hh-gold/20"
                  />
                </div>
              </div>

              {/* EMAIL */}

              <div>
                <label
                  htmlFor="email"
                  className="mb-2 block text-sm font-medium"
                >
                  Adresse e-mail
                </label>

                <div className="relative">
                  <Mail
                    size={17}
                    className="absolute left-4 top-1/2 -translate-y-1/2 text-muted-foreground"
                  />

                  <input
                    id="email"
                    type="email"
                    value={email}
                    onChange={(event) =>
                      setEmail(
                        event.target.value
                      )
                    }
                    placeholder="votre@email.com"
                    autoComplete="email"
                    required
                    className="h-13 w-full rounded-xl border border-border bg-white pl-11 pr-4 text-sm outline-none transition focus:border-hh-gold focus:ring-2 focus:ring-hh-gold/20"
                  />
                </div>
              </div>

              {/* TÉLÉPHONE */}

              <div>
                <label
                  htmlFor="phone"
                  className="mb-2 block text-sm font-medium"
                >
                  Téléphone
                  <span className="ml-1 text-xs font-normal text-muted-foreground">
                    (facultatif)
                  </span>
                </label>

                <div className="relative">
                  <Phone
                    size={17}
                    className="absolute left-4 top-1/2 -translate-y-1/2 text-muted-foreground"
                  />

                  <input
                    id="phone"
                    type="tel"
                    value={phone}
                    onChange={(event) =>
                      setPhone(
                        event.target.value
                      )
                    }
                    placeholder="07 00 00 00 00"
                    autoComplete="tel"
                    className="h-13 w-full rounded-xl border border-border bg-white pl-11 pr-4 text-sm outline-none transition focus:border-hh-gold focus:ring-2 focus:ring-hh-gold/20"
                  />
                </div>
              </div>

              {/* MOT DE PASSE */}

              <div>
                <label
                  htmlFor="password"
                  className="mb-2 block text-sm font-medium"
                >
                  Mot de passe
                </label>

                <div className="relative">
                  <Lock
                    size={17}
                    className="absolute left-4 top-1/2 -translate-y-1/2 text-muted-foreground"
                  />

                  <input
                    id="password"
                    type="password"
                    value={password}
                    onChange={(event) =>
                      setPassword(
                        event.target.value
                      )
                    }
                    placeholder="Minimum 8 caractères"
                    autoComplete="new-password"
                    required
                    minLength={8}
                    className="h-13 w-full rounded-xl border border-border bg-white pl-11 pr-4 text-sm outline-none transition focus:border-hh-gold focus:ring-2 focus:ring-hh-gold/20"
                  />
                </div>
              </div>

              {/* CONFIRMATION */}

              <div>
                <label
                  htmlFor="confirmPassword"
                  className="mb-2 block text-sm font-medium"
                >
                  Confirmer le mot de passe
                </label>

                <div className="relative">
                  <Lock
                    size={17}
                    className="absolute left-4 top-1/2 -translate-y-1/2 text-muted-foreground"
                  />

                  <input
                    id="confirmPassword"
                    type="password"
                    value={confirmPassword}
                    onChange={(event) =>
                      setConfirmPassword(
                        event.target.value
                      )
                    }
                    placeholder="Confirmez votre mot de passe"
                    autoComplete="new-password"
                    required
                    minLength={8}
                    className="h-13 w-full rounded-xl border border-border bg-white pl-11 pr-4 text-sm outline-none transition focus:border-hh-gold focus:ring-2 focus:ring-hh-gold/20"
                  />
                </div>
              </div>

              {/* BOUTON */}

              <button
                type="submit"
                disabled={loading}
                className="hh-button mt-3 h-14 w-full disabled:cursor-not-allowed disabled:opacity-60"
              >
                {loading ? (
                  <>
                    <Loader2
                      size={18}
                      className="animate-spin"
                    />
                    Création du compte...
                  </>
                ) : (
                  <>
                    Créer mon compte
                    <ArrowRight
                      size={18}
                    />
                  </>
                )}
              </button>
            </form>

            {/* CONNEXION */}

            <p className="mt-7 text-center text-sm text-muted-foreground">
              Vous avez déjà un compte ?{" "}
              <Link
                href="/login"
                className="font-semibold text-hh-gold-dark transition hover:text-hh-gold"
              >
                Se connecter
              </Link>
            </p>

            <div className="mt-6 text-center">
              <Link
                href="/"
                className="text-xs text-muted-foreground transition hover:text-hh-gold-dark"
              >
                ← Retour au site
              </Link>
            </div>
          </div>
        </div>
      </div>
    </main>
  );
}