"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { signIn } from "next-auth/react";
import DragonEye from "@/components/DragonEye";

export default function AuthPage() {
    const [tab, setTab] = useState<"login" | "register">("login");

    // Login state
    const [loginEmail, setLoginEmail] = useState("");
    const [loginPassword, setLoginPassword] = useState("");
    const [loginError, setLoginError] = useState("");
    const [loginLoading, setLoginLoading] = useState(false);

    // Register state
    const [regName, setRegName] = useState("");
    const [regEmail, setRegEmail] = useState("");
    const [regPassword, setRegPassword] = useState("");
    const [regConfirm, setRegConfirm] = useState("");
    const [regError, setRegError] = useState("");
    const [regSuccess, setRegSuccess] = useState("");
    const [regLoading, setRegLoading] = useState(false);

    const router = useRouter();

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoginLoading(true);
        setLoginError("");

        const result = await signIn("credentials", {
            email: loginEmail,
            password: loginPassword,
            redirect: false,
        });

        if (result?.ok) {
            window.location.href = "/dashboard";
        } else {
            setLoginError("Email ou mot de passe incorrect.");
            setLoginLoading(false);
        }
    };

    const handleRegister = async (e: React.FormEvent) => {
        e.preventDefault();
        setRegError("");
        setRegSuccess("");

        if (regPassword !== regConfirm) {
            setRegError("Les mots de passe ne correspondent pas.");
            return;
        }

        setRegLoading(true);

        const res = await fetch("/api/auth/register", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ email: regEmail, password: regPassword, name: regName }),
        });

        const data = await res.json();

        if (!res.ok) {
            setRegError(data.error || "Erreur lors de l'inscription.");
            setRegLoading(false);
            return;
        }

        setRegSuccess("Compte créé ! Connexion en cours...");
        const result = await signIn("credentials", {
            email: regEmail,
            password: regPassword,
            redirect: false,
        });

        if (result?.ok) {
            router.push("/dashboard");
        } else {
            setRegError("Compte créé mais connexion échouée. Veuillez vous connecter.");
            setRegLoading(false);
        }
    };

    const inputClass = (hasError: boolean) =>
        `w-full bg-wy-surface border px-4 py-3 text-sm font-mono text-wy-text-primary placeholder-wy-text-secondary outline-none rounded-md transition-all duration-200 ${
            hasError ? "border-red-500/60" : "border-wy-border focus:border-acid-green/60"
        }`;

    return (
        <main className="min-h-screen bg-wy-dark flex flex-col items-center justify-center relative overflow-hidden">
            <div
                className="absolute inset-0 opacity-20 pointer-events-none"
                style={{
                    backgroundImage: `linear-gradient(rgba(74,255,140,0.05) 1px, transparent 1px), linear-gradient(90deg, rgba(74,255,140,0.05) 1px, transparent 1px)`,
                    backgroundSize: "40px 40px",
                }}
            />
            <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] rounded-full bg-acid-green/[0.02] blur-3xl pointer-events-none" />

            <div className="relative z-10 flex flex-col items-center gap-8 w-full max-w-sm px-6">
                {/* Header */}
                <div className="flex flex-col items-center gap-5">
                    <DragonEye size={80} />
                    <div className="text-center">
                        <div className="text-[9px] tracking-[0.45em] text-acid-green/70 uppercase mb-2 font-mono">
                            Analytics Dashboard
                        </div>
                        <h1 className="text-4xl font-black tracking-[0.15em] uppercase text-wy-text-primary">
                            WYVIEW
                        </h1>
                    </div>
                </div>

                {/* Tabs */}
                <div className="w-full flex border border-wy-border rounded-md overflow-hidden">
                    <button
                        onClick={() => { setTab("login"); setLoginError(""); }}
                        className={`flex-1 py-2 text-[10px] font-mono tracking-[0.3em] uppercase transition-all duration-200 ${
                            tab === "login"
                                ? "bg-acid-green/10 text-acid-green border-r border-wy-border"
                                : "text-wy-text-secondary hover:text-acid-green/80 border-r border-wy-border"
                        }`}
                    >
                        CONNEXION
                    </button>
                    <button
                        onClick={() => { setTab("register"); setRegError(""); setRegSuccess(""); }}
                        className={`flex-1 py-2 text-[10px] font-mono tracking-[0.3em] uppercase transition-all duration-200 ${
                            tab === "register"
                                ? "bg-acid-green/10 text-acid-green"
                                : "text-wy-text-secondary hover:text-acid-green/80"
                        }`}
                    >
                        INSCRIPTION
                    </button>
                </div>

                {/* Login Form */}
                {tab === "login" && (
                    <form onSubmit={handleLogin} className="w-full flex flex-col gap-3">
                        <input
                            type="email"
                            placeholder="Adresse email"
                            value={loginEmail}
                            autoComplete="email"
                            onChange={(e) => { setLoginEmail(e.target.value); setLoginError(""); }}
                            className={inputClass(!!loginError)}
                        />
                        <input
                            type="password"
                            placeholder="Mot de passe"
                            value={loginPassword}
                            autoComplete="current-password"
                            onChange={(e) => { setLoginPassword(e.target.value); setLoginError(""); }}
                            className={inputClass(!!loginError)}
                        />
                        {loginError && (
                            <p className="text-red-400/80 text-[11px] font-mono tracking-widest">— {loginError}</p>
                        )}
                        <button
                            type="submit"
                            disabled={loginLoading || !loginEmail || !loginPassword}
                            className="w-full py-3 text-[11px] font-mono tracking-[0.3em] uppercase font-bold border border-acid-green text-acid-green hover:bg-acid-green/10 transition-all duration-200 rounded-md disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            {loginLoading ? "CONNEXION..." : "ACCÉDER"}
                        </button>
                    </form>
                )}

                {/* Register Form */}
                {tab === "register" && (
                    <form onSubmit={handleRegister} className="w-full flex flex-col gap-3">
                        <input
                            type="text"
                            placeholder="Nom (optionnel)"
                            value={regName}
                            autoComplete="name"
                            onChange={(e) => { setRegName(e.target.value); setRegError(""); }}
                            className={inputClass(false)}
                        />
                        <input
                            type="email"
                            placeholder="Adresse email"
                            value={regEmail}
                            autoComplete="email"
                            onChange={(e) => { setRegEmail(e.target.value); setRegError(""); }}
                            className={inputClass(!!regError)}
                        />
                        <input
                            type="password"
                            placeholder="Mot de passe"
                            value={regPassword}
                            autoComplete="new-password"
                            onChange={(e) => { setRegPassword(e.target.value); setRegError(""); }}
                            className={inputClass(!!regError)}
                        />
                        <input
                            type="password"
                            placeholder="Confirmer le mot de passe"
                            value={regConfirm}
                            autoComplete="new-password"
                            onChange={(e) => { setRegConfirm(e.target.value); setRegError(""); }}
                            className={inputClass(!!regError && regPassword !== regConfirm)}
                        />
                        {regError && (
                            <p className="text-red-400/80 text-[11px] font-mono tracking-widest">— {regError}</p>
                        )}
                        {regSuccess && (
                            <p className="text-acid-green/80 text-[11px] font-mono tracking-widest">✓ {regSuccess}</p>
                        )}
                        <button
                            type="submit"
                            disabled={regLoading || !regEmail || !regPassword || !regConfirm}
                            className="w-full py-3 text-[11px] font-mono tracking-[0.3em] uppercase font-bold border border-acid-green text-acid-green hover:bg-acid-green/10 transition-all duration-200 rounded-md disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            {regLoading ? "CRÉATION..." : "CRÉER UN COMPTE"}
                        </button>
                    </form>
                )}

                <div className="text-[9px] font-mono text-wy-text-secondary/50 tracking-[0.3em]">
                    WYVIEW v1.0 /// CROWMATE
                </div>
            </div>
        </main>
    );
}