import { useEffect, useState } from "react";
import { toast } from "sonner";
import { IoIosLogIn } from "react-icons/io";
import { PiUserCirclePlus } from "react-icons/pi";

function Register() {
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [tab, setTab] = useState("login"); // 'login' or 'register'

    useEffect(() => {
        document.title = "Register | CDRM-Project";
    }, []);

    const validateUsername = (name) => /^[A-Za-z0-9_-]+$/.test(name);
    const validatePassword = (pass) => /^\S+$/.test(pass); // No spaces

    const handleSubmit = async (e) => {
        e.preventDefault();

        if (!validateUsername(username)) {
            toast.error("Invalid username. Use only letters, numbers, hyphens, or underscores.");
            return;
        }
        if (!validatePassword(password)) {
            toast.error("Invalid password. Spaces are not allowed.");
            return;
        }

        if (tab === "register") {
            if (password !== confirmPassword) {
                toast.error("Passwords do not match.");
                return;
            }
            try {
                const res = await fetch("/register", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({ username, password }),
                });
                const data = await res.json();
                if (data.message) {
                    toast.success(data.message);
                } else {
                    toast.error(data.error || "Unknown error");
                }
            } catch (err) {
                toast.error(`Register error: ${err.message}`);
            }
        } else {
            try {
                const res = await fetch("/login", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    credentials: "include",
                    body: JSON.stringify({ username, password }),
                });
                const data = await res.json();
                if (data.message) {
                    window.location.reload();
                } else {
                    toast.error(data.error || "Login failed");
                }
            } catch (err) {
                toast.error(`Login error: ${err.message}`);
            }
        }
    };

    return (
        <div className="mx-auto flex min-h-full w-full max-w-xl flex-col justify-center px-6 py-12 lg:px-8">
            <div className="mx-auto">
                {/* Tabs */}
                <div className="tabs tabs-box justify-center">
                    <button
                        className={`tab ${tab === "login" ? "tab-active" : ""}`}
                        onClick={() => setTab("login")}
                    >
                        <IoIosLogIn className="h-6 w-6 me-1"/>
                        Sign in
                    </button>
                    <button
                        className={`tab ${tab === "register" ? "tab-active" : ""}`}
                        onClick={() => setTab("register")}
                    >
                        <PiUserCirclePlus className="h-6 w-6 me-1" />
                        Register
                    </button>
                </div>
                <h2 className="mt-10 text-center text-2xl font-bold tracking-tight">
                    {tab === "login" ? "Sign in" : "Register"}
                </h2>
            </div>

            <div className="mx-auto mt-10 w-full max-w-xl">
                <form className="space-y-6" onSubmit={handleSubmit}>
                    <fieldset className="fieldset">
                        <legend className="fieldset-legend text-base">Username</legend>
                        <input
                            type="text"
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                            className="input w-full"
                            placeholder="Enter your username"
                            required
                        />
                    </fieldset>

                    <fieldset className="fieldset">
                        <legend className="fieldset-legend text-base">Password</legend>
                        <input
                            type="password"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            className="input w-full"
                            placeholder="Enter your password"
                            required
                        />
                    </fieldset>

                    {tab === "register" && (
                        <fieldset className="fieldset">
                            <legend className="fieldset-legend text-base">Confirm password</legend>
                            <input
                                type="password"
                                value={confirmPassword}
                                onChange={(e) => setConfirmPassword(e.target.value)}
                                className="input w-full"
                                placeholder="Confirm your password"
                                required
                            />
                        </fieldset>
                    )}

                    <button type="submit" className="btn btn-primary btn-block">
                        {tab === "login" ? "Sign in" : "Register"}
                    </button>
                </form>
            </div>
        </div>
    );
}

export default Register;
