import { useState, useEffect, useContext } from "react";
import { useLocation, useNavigate, Link } from "react-router-dom";
import axios from "axios";
import { AuthContext } from "../../context/AuthContext";
import loginSideBanner from "../../assets/images/login_side_banner.jpg";

function LoginPage() {
    const location = useLocation();
    const navigate = useNavigate();
    const { login } = useContext(AuthContext);

    const API_URL = import.meta.env.VITE_API_URL;

    const [activeTab, setActiveTab] = useState("login"); // "login" or "signup"
    const [loginMode, setLoginMode] = useState("email"); // "email" or "phone"
    const [formMode, setFormMode] = useState("main"); // "main" or "forgot"

    const [loginData, setLoginData] = useState({ email: "", password: "" });
    const [signupData, setSignupData] = useState({
        userName: "",
        email: "",
        password: "",
    });

    const [resetEmail, setResetEmail] = useState("");

    const [phoneNumber, setPhoneNumber] = useState("");
    const [otp, setOtp] = useState("");
    const [otpSent, setOtpSent] = useState(false);

    const [showPassword, setShowPassword] = useState(false);
    const [message, setMessage] = useState({ type: "", text: "" });

    // Sync tab with URL
    useEffect(() => {
        if (location.pathname.includes("signup")) setActiveTab("signup");
        else setActiveTab("login");
        resetForm();
    }, [location.pathname]);

    const resetForm = () => {
        setLoginData({ email: "", password: "" });
        setSignupData({ userName: "", email: "", password: "" });
        setPhoneNumber("");
        setOtp("");
        setOtpSent(false);
        setFormMode("main");
        setMessage({ type: "", text: "" });
    };

    // ------------------ EVENT HANDLERS ------------------
    const handleLoginChange = (e) =>
        setLoginData({ ...loginData, [e.target.name]: e.target.value });

    const handleSignupChange = (e) =>
        setSignupData({ ...signupData, [e.target.name]: e.target.value });

    // Email login
    const handleEmailLogin = async (e) => {
        e.preventDefault();
        try {
            const res = await axios.post(`${API_URL}/api/userlogin`, loginData, {
                withCredentials: true,
            });
            if (res.data.success) {
                login(res.data);
                navigate("/");
            } else {
                setMessage({ type: "error", text: res.data.message });
            }
        } catch (err) {
            setMessage({
                type: "error",
                text: err.response?.data?.message || "Login failed",
            });
        }
    };

    // Email signup
    const handleEmailSignup = async (e) => {
        e.preventDefault();
        try {
            const res = await axios.post(`${API_URL}/api/usersignup`, signupData, {
                withCredentials: true,
            });
            if (res.data.success) {
                login(res.data);
                navigate("/");
            } else {
                setMessage({ type: "error", text: res.data.message });
            }
        } catch (err) {
            setMessage({
                type: "error",
                text: err.response?.data?.message || "Signup failed",
            });
        }
    };

    // Send OTP
    const handleSendOtp = async (e) => {
        e.preventDefault();
        try {
            const res = await axios.post(`${API_URL}/api/sendotp`, {
                phoneNumber,
                mode: activeTab,
            });
            if (res.data.success) {
                setOtpSent(true);
                setMessage({ type: "success", text: "OTP sent successfully" });
            } else {
                setMessage({ type: "error", text: res.data.message });
            }
        } catch (err) {
            setMessage({
                type: "error",
                text: err.response?.data?.message || "Failed to send OTP",
            });
        }
    };

    // Verify OTP
    const handleVerifyOtp = async (e) => {
        e.preventDefault();
        try {
            const res = await axios.post(`${API_URL}/api/verifyotp`, {
                phoneNumber,
                otp,
                mode: activeTab,
            });
            if (res.data.success) {
                login(res.data);
                navigate("/");
            } else {
                setMessage({ type: "error", text: res.data.message });
            }
        } catch (err) {
            setMessage({
                type: "error",
                text: err.response?.data?.message || "OTP verification failed",
            });
        }
    };

    // Forgot password
    const handleForgotPassword = async (e) => {
        e.preventDefault();
        try {
            const res = await axios.post(`${API_URL}/api/forgotpassword`, {
                email: resetEmail,
            });
            if (res.data.success) {
                setMessage({ type: "success", text: "Password reset link sent" });
                setFormMode("main");
            } else {
                setMessage({ type: "error", text: res.data.message });
            }
        } catch (err) {
            setMessage({
                type: "error",
                text: err.response?.data?.message || "Failed to send reset link",
            });
        }
    };

    // ------------------ RENDER ------------------
    return (
        <div className="min-h-screen flex items-center justify-center bg-gray-100 p-4">
            <div className="flex flex-col md:flex-row w-full max-w-5xl bg-white rounded-xl shadow-xl overflow-hidden">
                {/* Left Image */}
                <div className="hidden md:flex md:w-1/2">
                    <img
                        src={loginSideBanner}
                        alt="Login Illustration"
                        className="w-full h-full object-cover"
                    />
                </div>

                {/* Right Form */}
                <div className="w-full md:w-1/2 p-8 flex items-center justify-center">
                    <div className="w-full max-w-md">
                        {/* Tabs: Login / Signup */}
                        {formMode === "main" && (
                            <>
                                <div className="flex justify-center mb-6 space-x-6">
                                    <button
                                        onClick={() => {
                                            setActiveTab("login");
                                            navigate("/userlogin");
                                        }}
                                        className={`font-semibold ${activeTab === "login"
                                                ? "text-orange-600 border-b-2 border-orange-600"
                                                : "text-gray-500"
                                            }`}
                                    >
                                        Login
                                    </button>
                                    <button
                                        onClick={() => {
                                            setActiveTab("signup");
                                            navigate("/usersignup");
                                        }}
                                        className={`font-semibold ${activeTab === "signup"
                                                ? "text-orange-600 border-b-2 border-orange-600"
                                                : "text-gray-500"
                                            }`}
                                    >
                                        Sign Up
                                    </button>
                                </div>

                                {/* Toggle Email / Phone */}
                                <div className="flex justify-center mb-6 space-x-4">
                                    <button
                                        onClick={() => {
                                            setLoginMode("email");
                                            resetForm();
                                        }}
                                        className={`px-3 py-2 rounded-md text-sm font-medium ${loginMode === "email"
                                                ? "bg-orange-600 text-white"
                                                : "bg-gray-200"
                                            }`}
                                    >
                                        Email
                                    </button>
                                    <button
                                        onClick={() => {
                                            setLoginMode("phone");
                                            resetForm();
                                        }}
                                        className={`px-3 py-2 rounded-md text-sm font-medium ${loginMode === "phone"
                                                ? "bg-orange-600 text-white"
                                                : "bg-gray-200"
                                            }`}
                                    >
                                        Phone
                                    </button>
                                </div>
                            </>
                        )}

                        {/* Message */}
                        {message.text && (
                            <p
                                className={`text-center mb-3 text-sm ${message.type === "error"
                                        ? "text-red-500"
                                        : "text-green-500"
                                    }`}
                            >
                                {message.text}
                            </p>
                        )}

                        {/* Email Login / Signup */}
                        {formMode === "main" && loginMode === "email" && (
                            <form
                                onSubmit={
                                    activeTab === "login" ? handleEmailLogin : handleEmailSignup
                                }
                                className="space-y-4"
                            >
                                {activeTab === "signup" && (
                                    <input
                                        type="text"
                                        name="userName"
                                        placeholder="User Name"
                                        value={signupData.userName}
                                        onChange={handleSignupChange}
                                        className="w-full border p-3 rounded-md"
                                        required
                                    />
                                )}
                                <input
                                    type="email"
                                    name="email"
                                    placeholder="Email"
                                    value={
                                        activeTab === "login"
                                            ? loginData.email
                                            : signupData.email
                                    }
                                    onChange={
                                        activeTab === "login"
                                            ? handleLoginChange
                                            : handleSignupChange
                                    }
                                    className="w-full border p-3 rounded-md"
                                    required
                                />
                                <div className="relative">
                                    <input
                                        type={showPassword ? "text" : "password"}
                                        name="password"
                                        placeholder="Password"
                                        value={
                                            activeTab === "login"
                                                ? loginData.password
                                                : signupData.password
                                        }
                                        onChange={
                                            activeTab === "login"
                                                ? handleLoginChange
                                                : handleSignupChange
                                        }
                                        className="w-full border p-3 rounded-md"
                                        required
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowPassword(!showPassword)}
                                        className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 text-sm"
                                    >
                                        {showPassword ? "Hide" : "Show"}
                                    </button>
                                </div>

                                {activeTab === "login" && (
                                    <p
                                        className="text-right text-sm text-blue-600 cursor-pointer hover:underline"
                                        onClick={() => setFormMode("forgot")}
                                    >
                                        Forgot Password?
                                    </p>
                                )}

                                <button
                                    type="submit"
                                    className="w-full bg-orange-600 text-white py-3 rounded-md font-semibold hover:bg-orange-500 transition"
                                >
                                    {activeTab === "login" ? "Login" : "Sign Up"}
                                </button>
                            </form>
                        )}

                        {/* Phone OTP */}
                        {formMode === "main" && loginMode === "phone" && (
                            <form
                                onSubmit={otpSent ? handleVerifyOtp : handleSendOtp}
                                className="space-y-4"
                            >
                                <input
                                    type="tel"
                                    placeholder="Enter phone number"
                                    value={phoneNumber}
                                    onChange={(e) => setPhoneNumber(e.target.value)}
                                    className="w-full border p-3 rounded-md"
                                    required
                                />
                                {otpSent && (
                                    <input
                                        type="text"
                                        placeholder="Enter OTP"
                                        value={otp}
                                        onChange={(e) => setOtp(e.target.value)}
                                        className="w-full border p-3 rounded-md"
                                        required
                                    />
                                )}
                                <button
                                    type="submit"
                                    className="w-full bg-orange-600 text-white py-3 rounded-md font-semibold hover:bg-orange-500 transition"
                                >
                                    {otpSent ? "Verify OTP" : "Send OTP"}
                                </button>
                            </form>
                        )}

                        {/* Forgot Password */}
                        {formMode === "forgot" && (
                            <form onSubmit={handleForgotPassword} className="space-y-4">
                                <h2 className="text-lg font-semibold text-center mb-2">
                                    Reset Password
                                </h2>
                                <input
                                    type="email"
                                    placeholder="Enter your email"
                                    value={resetEmail}
                                    onChange={(e) => setResetEmail(e.target.value)}
                                    className="w-full border p-3 rounded-md"
                                    required
                                />
                                <button
                                    type="submit"
                                    className="w-full bg-orange-600 text-white py-3 rounded-md font-semibold hover:bg-orange-500 transition"
                                >
                                    Send Reset Link
                                </button>
                                <p
                                    onClick={() => setFormMode("main")}
                                    className="text-center text-sm text-gray-600 cursor-pointer hover:underline"
                                >
                                    Back to Login
                                </p>
                            </form>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
}

export default LoginPage;
