"use client";

import { useState, useCallback, useRef, useEffect } from "react";
import { Lock } from "lucide-react";
import styles from "./signin.module.css";

export default function SignIn() {
  const forceAnim = process.env.NEXT_PUBLIC_FORCE_ANIMATIONS === "1";
  // Shared
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [info, setInfo] = useState("");

  const resetMessages = useCallback(() => {
    setError("");
    setInfo("");
  }, []);

  // OTP state
  const [code, setCode] = useState("");
  const [otpStep, setOtpStep] = useState<"email" | "code">("email");

  // OTP UI (6 inputs)
  const CODE_LENGTH = 6;
  const [codeDigits, setCodeDigits] = useState<string[]>(Array(CODE_LENGTH).fill(""));
  const inputsRef = useRef<Array<HTMLInputElement | null>>([]);
  // Focus OTP input on step change
  useEffect(() => {
    if (otpStep === "code") {
      setTimeout(() => {
        if (inputsRef.current[0]) {
          inputsRef.current[0].focus();
        }
      }, 100); // Laisse le temps au DOM de rendre
    }
  }, [otpStep]);

  function syncCodeFromDigits(next: string[]) {
    const joined = next.join("");
    setCode(joined);
  }

  function focusInput(idx: number) {
    const el = inputsRef.current[idx];
    if (el) el.focus();
  }

  function handleDigitChange(idx: number, value: string) {
    const v = (value || "").replace(/\D/g, "").slice(-1);
    const next = [...codeDigits];
    next[idx] = v;
    setCodeDigits(next);
    syncCodeFromDigits(next);
    if (v && idx < CODE_LENGTH - 1) {
      focusInput(idx + 1);
    }
  }

  function handleKeyDown(idx: number, e: React.KeyboardEvent<HTMLInputElement>) {
    const key = e.key;
    if (key === "Backspace") {
      if (codeDigits[idx]) {
        const next = [...codeDigits];
        next[idx] = "";
        setCodeDigits(next);
        syncCodeFromDigits(next);
      } else if (idx > 0) {
        focusInput(idx - 1);
      }
    } else if (key === "ArrowLeft" && idx > 0) {
      e.preventDefault();
      focusInput(idx - 1);
    } else if (key === "ArrowRight" && idx < CODE_LENGTH - 1) {
      e.preventDefault();
      focusInput(idx + 1);
    }
  }

  function handlePaste(e: React.ClipboardEvent<HTMLDivElement>) {
    e.preventDefault();
    const pasted = (e.clipboardData.getData("text") || "").replace(/\D/g, "");
    if (!pasted) return;
    const next = Array(CODE_LENGTH)
      .fill("")
      .map((_, i) => pasted[i] || "");
    setCodeDigits(next);
    syncCodeFromDigits(next);
    const lastIdx = Math.min(pasted.length, CODE_LENGTH) - 1;
    if (lastIdx >= 0) focusInput(lastIdx);
  }

  // Prevent double submission on auto-verify
  const hasSubmittedRef = useRef(false);

  async function verifyCode() {
    if (hasSubmittedRef.current) return;
    if (code.length !== CODE_LENGTH) return;

    hasSubmittedRef.current = true;
    setLoading(true);
    resetMessages();
    try {
      const res = await fetch("/api/auth/verify-code", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include", // pour déposer le cookie httpOnly
        body: JSON.stringify({ email, code }),
      });

      if (res.status === 403) {
        setError("Votre compte a été révoqué. Merci de contacter votre administrateur.");
        hasSubmittedRef.current = false;
        return;
      }

      if (!res.ok) {
        const txt = await res.text().catch(() => "");
        const low = (txt || "").toLowerCase();
        if (low.includes("banned") || low.includes("revoked")) {
          setError("Votre compte a été révoqué. Merci de contacter votre administrateur.");
        } else {
          setError(txt || "Code invalide ou expiré.");
        }
        hasSubmittedRef.current = false;
        return;
      }

      // Succès : le redirect démarre, on laisse le loader/overlay affiché.
      window.location.href = "/";
    } catch (err: any) {
      setError(err?.message || "Erreur inattendue");
      hasSubmittedRef.current = false;
    } finally {
      // Ne pas remettre loading à false ici pour garder le loader visible pendant la redirection.
    }
  }

  // ---------------- OTP FLOW ----------------
  async function handleEmailSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    resetMessages();
    try {
      const res = await fetch("/api/auth/send-code", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });

      if (res.status === 403) {
        setError("Votre compte a été révoqué. Merci de contacter votre administrateur.");
        return;
      }

      if (!res.ok) {
        const txt = await res.text().catch(() => "");
        const low = (txt || "").toLowerCase();
        if (low.includes("banned") || low.includes("revoked")) {
          setError("Votre compte a été révoqué. Merci de contacter votre administrateur.");
        } else {
          setError(txt || "Impossible d'envoyer le code. Réessayez.");
        }
        return;
      }

      setOtpStep("code");
      setCode("");
      setCodeDigits(Array(CODE_LENGTH).fill(""));
      setInfo("Un code vous a été envoyé par e-mail.");
    } catch (err: any) {
      setError(err?.message || "Erreur inattendue");
    } finally {
      setLoading(false);
    }
  }

  async function handleCodeSubmit(e: React.FormEvent) {
    e.preventDefault();
    await verifyCode();
  }

  useEffect(() => {
    if (otpStep === "code" && code.length === CODE_LENGTH && !loading) {
      // Auto-submit as soon as the 6th digit is entered or pasted
      verifyCode();
    }
  }, [code, otpStep, loading]);

  async function resendCode() {
    if (!email || loading) return;
    setLoading(true);
    setError("");
    try {
      const res = await fetch("/api/auth/send-code", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      if (res.status === 403) {
        setError("Votre compte a été révoqué. Merci de contacter votre administrateur.");
        return;
      }
      if (!res.ok) {
        setError("Impossible de renvoyer le code.");
        return;
      }
      setInfo("Nouveau code envoyé.");
    } catch (_) {
      setError("Erreur réseau.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className={styles.meshRoot}>
      {/* Animated mesh background */}
      {/* Fixed, light multi-color gradient background */}
      <div className={styles.simpleBg} aria-hidden="true" />

      {/* Centered glassmorphism card */}
      <div className="relative z-10 min-h-screen flex items-center justify-center p-4">
        <div className="w-full max-w-md">
          <div className={`rounded-3xl p-6 sm:p-8 ${styles.glass} text-[#171424]`}>
            <div className="flex flex-col items-center text-center mb-6">
              <img
                src="/odentas-logo.png"
                alt="Logo Odentas"
                className="h-20 w-auto mb-3 drop-shadow-lg"
                style={{ maxWidth: "80%" }}
              />
              <div className="text-xs sm:text-sm text-[#171424]/70 flex items-center gap-1">
                <Lock size={16} strokeWidth={2.2} className="inline-block align-middle text-[#6366f1]" aria-label="Espace sécurisé" />
                Espace sécurisé
              </div>
            </div>

            <div className="mb-4">
              <h1 className="text-xl sm:text-2xl font-semibold tracking-tight text-[#171424]">
                Connexion à l'Espace Paie
              </h1>
            </div>

            <p className="text-sm text-[#171424]/70 mb-5">
              Saisissez votre e-mail, puis le code reçu pour vous connecter.
            </p>

            {otpStep === "email" && (
              <form onSubmit={handleEmailSubmit} className="space-y-3">
                <input
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="Votre adresse e-mail"
                  autoComplete="email"
                  className="w-full px-4 py-3 rounded-2xl border-2 border-[#6366f1]/40 bg-white/30 text-[#171424] placeholder-[#171424]/60 focus:outline-none focus:ring-2 focus:ring-[#6366f1]/40 shadow-md transition"
                  style={{ fontSize: "1.15rem", fontWeight: 500 }}
                />
                {error && <div className="text-sm text-rose-300">{error}</div>}
                {info && <div className="text-sm text-emerald-300">{info}</div>}
                <button
                  type="submit"
                  disabled={loading}
                  className="w-full py-2.5 rounded-xl bg-[var(--brand)] text-slate-900 font-semibold disabled:opacity-60 transition active:scale-[0.99]"
                >
                  {loading ? "Envoi en cours…" : "Recevoir un code"}
                </button>
              </form>
            )}

            {otpStep === "code" && (
              <form onSubmit={handleCodeSubmit} className="space-y-4">
                <div
                  className="flex justify-between gap-2"
                  onPaste={handlePaste}
                  aria-label="Saisissez le code à 6 chiffres"
                >
                  {Array.from({ length: CODE_LENGTH }).map((_, i) => (
                    <input
                      key={i}
                      ref={(el) => { inputsRef.current[i] = el; }}
                      type="text"
                      inputMode="numeric"
                      autoComplete="one-time-code"
                      pattern="[0-9]*"
                      maxLength={1}
                      value={codeDigits[i] || ""}
                      onChange={(e) => handleDigitChange(i, e.target.value)}
                      onKeyDown={(e) => handleKeyDown(i, e)}
                      className="w-14 h-16 text-center text-3xl rounded-2xl bg-white/70 border-2 border-[#6366f1]/40 text-[#171424] placeholder-[#171424]/40 focus:outline-none focus:ring-2 focus:ring-[#6366f1]/40 shadow-lg transition"
                      style={{ fontWeight: 700, letterSpacing: "0.1em" }}
                      aria-label={`Chiffre ${i + 1}`}
                    />
                  ))}
                </div>

                {error && <div className="text-sm text-rose-300">{error}</div>}
                {info && <div className="text-sm text-emerald-300">{info}</div>}

                <div className="flex items-center justify-between gap-3">
                  <button
                    type="button"
                    onClick={() => {
                      setOtpStep("email");
                      setCode("");
                      setCodeDigits(Array(CODE_LENGTH).fill(""));
                      hasSubmittedRef.current = false;
                      resetMessages();
                    }}
                    className="px-3 py-2 rounded-xl border border-[#171424]/20 text-sm text-[#171424]/80 hover:text-[#171424] hover:border-[#171424]/30 transition"
                    disabled={loading}
                  >
                    Modifier l'e-mail
                  </button>
                  <button
                    type="button"
                    onClick={resendCode}
                    className="text-sm text-[#171424]/80 hover:text-[#171424] underline-offset-4 hover:underline"
                    disabled={loading}
                  >
                    Renvoyer le code
                  </button>
                </div>

                <input type="hidden" value={code} readOnly />

                <button
                  type="submit"
                  disabled={loading || code.length !== CODE_LENGTH}
                  className="w-full py-2.5 rounded-xl bg-[var(--brand)] text-slate-900 font-semibold disabled:opacity-60 transition active:scale-[0.99]"
                >
                  {loading ? "Vérification…" : "Se connecter"}
                </button>
              </form>
            )}
          </div>
        </div>
      </div>

      {otpStep === "code" && loading && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm"
          role="dialog"
          aria-modal="true"
          aria-label="Connexion en cours"
        >
          <div className="flex flex-col items-center gap-4 rounded-2xl bg-white/10 border border-white/20 backdrop-blur-xl px-6 py-8 shadow-2xl text-white">
            <div className="w-10 h-10 rounded-full border-4 border-white/30 border-t-[var(--brand)] animate-spin" />
            <div className="text-white/90 font-medium">
              Connexion en cours…
            </div>
            <div className="text-xs text-white/70">
              Vous allez être redirigé vers votre Espace Paie Employeur.
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
