import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { motion, AnimatePresence } from "framer-motion";
import login_side_banner from "../../assets/images/login_side_banner.jpg";

export default function AdminLoginPage() {
    const navigate = useNavigate();

    const API_URL = import.meta.env.VITE_API_URL;


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

    // Email forms
    const [loginData, setLoginData] = useState({ email: "", password: "" });
    const [signupData, setSignupData] = useState({ adminName: "", email: "", password: "" });
    const [resetEmail, setResetEmail] = useState("");

    // Phone OTP
    const [phoneNumber, setPhoneNumber] = useState("");
    const [otpValues, setOtpValues] = useState(["", "", "", "", "", ""]);
    const [otpSent, setOtpSent] = useState(false);
    const [timer, setTimer] = useState(0); // seconds
    const otpRefs = useRef([]);

    // UI
    const [showPassword, setShowPassword] = useState(false);
    const [toast, setToast] = useState(null); // { type: "success"|"error", text: "" }

    // Animations
    const panelVariant = { hidden: { opacity: 0, y: 8 }, visible: { opacity: 1, y: 0 } };

    // OTP timer
    useEffect(() => {
        if (timer <= 0) return;
        const id = setInterval(() => setTimer((t) => t - 1), 1000);
        return () => clearInterval(id);
    }, [timer]);

    // Toast auto-dismiss
    useEffect(() => {
        if (!toast) return;
        const id = setTimeout(() => setToast(null), 3500);
        return () => clearTimeout(id);
    }, [toast]);

    const formatTimer = (s) =>
        `${Math.floor(s / 60).toString().padStart(2, "0")}:${(s % 60).toString().padStart(2, "0")}`;

    const resetAll = () => {
        setLoginData({ email: "", password: "" });
        setSignupData({ adminName: "", email: "", password: "" });
        setPhoneNumber("");
        setOtpValues(["", "", "", "", "", ""]);
        setOtpSent(false);
        setTimer(0);
        setFormMode("main");
        setToast(null);
        setShowPassword(false);
    };

    // OTP handlers
    const handleOtpChange = (idx, val) => {
        if (!/^\d*$/.test(val)) return;
        const copy = [...otpValues];
        copy[idx] = val.slice(-1);
        setOtpValues(copy);
        if (val && idx < 5) otpRefs.current[idx + 1]?.focus();
        if (!val && idx > 0) otpRefs.current[idx - 1]?.focus();
    };

    const handleOtpPaste = (e) => {
        e.preventDefault();
        const paste = e.clipboardData.getData("text").replace(/\D/g, "").slice(0, 6).split("");
        const next = ["", "", "", "", "", ""];
        paste.forEach((d, i) => (next[i] = d));
        setOtpValues(next);
        const last = paste.length - 1;
        if (last >= 0) otpRefs.current[last]?.focus();
    };

    const showToast = (type, text) => setToast({ type, text });

    // ---------------- BACKEND CALLS ----------------
    const handleEmailLogin = async (e) => {
        e.preventDefault();
        try {
            const res = await fetch(`${API_URL}/api/adminlogin`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(loginData),
                credentials: "include",
            });
            const data = await res.json();
            if (data.success) {
                showToast("success", data.message || "Logged in — redirecting...");
                setTimeout(() => navigate("/admin/dashboard"), 600);
            } else {
                showToast("error", data.message || "Login failed");
            }
        } catch {
            showToast("error", "Login failed");
        }
    };

    const handleEmailSignup = async (e) => {
        e.preventDefault();
        try {
            const res = await fetch(`${API_URL}/api/adminsignup`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(signupData),
                credentials: "include",
            });
            const data = await res.json();
            if (data.success) {
                showToast("success", data.message || "Signup successful — redirecting...");
                setTimeout(() => navigate("/admin/dashboard"), 600);
            } else {
                showToast("error", data.message || "Signup failed");
            }
        } catch {
            showToast("error", "Signup failed");
        }
    };

    const handleForgotPassword = async (e) => {
        e.preventDefault();
        try {
            const res = await fetch(`${API_URL}/api/adminforgotpassword`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ email: resetEmail }),
            });
            const data = await res.json();
            if (data.success) {
                showToast("success", data.message || "Reset link sent to email");
                setTimeout(() => setFormMode("main"), 1200);
            } else showToast("error", data.message || "Failed to send reset link");
        } catch {
            showToast("error", "Failed to send reset link");
        }
    };

    const handleSendOtp = async (e) => {
        e.preventDefault();
        try {
            const res = await fetch(`${API_URL}/api/adminsendotp`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ phoneNumber, mode: activeTab }),
            });
            const data = await res.json();
            if (data.success) {
                setOtpSent(true);
                setOtpValues(["", "", "", "", "", ""]);
                setTimer(300); // 5 min
                showToast("success", "OTP sent to your phone");
                setTimeout(() => otpRefs.current[0]?.focus(), 50);
            } else showToast("error", data.message || "Failed to send OTP");
        } catch {
            showToast("error", "Failed to send OTP");
        }
    };

    const handleVerifyOtp = async (e) => {
        e.preventDefault();
        const otp = otpValues.join("");
        try {
            const res = await fetch(`${API_URL}/api/adminverifyotp`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ phoneNumber, otp, mode: activeTab }),
            });
            const data = await res.json();
            if (data.success) {
                showToast("success", data.message || "OTP verified — redirecting...");
                setTimeout(() => navigate("/admin/dashboard"), 600);
            } else {
                showToast("error", data.message || "Invalid OTP");
                setOtpValues(["", "", "", "", "", ""]);
                setTimeout(() => otpRefs.current[0]?.focus(), 50);
            }
        } catch {
            showToast("error", "OTP verification failed");
        }
    };

    const handleResendOtp = async () => {
        if (timer > 0) return;
        try {
            const res = await fetch(`${API_URL}/api/adminsendotp`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ phoneNumber, mode: activeTab, resend: true }),
            });
            const data = await res.json();
            if (data.success) {
                setOtpValues(["", "", "", "", "", ""]);
                setTimer(300);
                showToast("success", "OTP resent");
                setTimeout(() => otpRefs.current[0]?.focus(), 50);
            } else showToast("error", data.message || "Resend failed");
        } catch {
            showToast("error", "Resend failed");
        }
    };

    // ---------------- UI ----------------
    return (
        <div className="min-h-screen flex items-center justify-center bg-gray-100 p-4">
            {/* Toast */}
            <AnimatePresence>
                {toast && (
                    <motion.div
                        initial={{ opacity: 0, y: -12 }}
                        animate={{ opacity: 1, y: 0 }}
                        exit={{ opacity: 0, y: -12 }}
                        className={`fixed left-1/2 top-6 z-50 -translate-x-1/2 rounded-md px-4 py-2 shadow-md ${toast.type === "error" ? "bg-red-600 text-white" : "bg-emerald-600 text-white"
                            }`}
                    >
                        {toast.text}
                    </motion.div>
                )}
            </AnimatePresence>

            <div className="flex flex-col md:flex-row w-full max-w-5xl bg-white rounded-2xl shadow-xl overflow-hidden">
                {/* Left banner */}
                <div className="hidden md:flex md:w-1/2">
                    <img src={login_side_banner} alt="Admin Banner" className="w-full h-full object-cover" />
                </div>

                {/* Right form */}
                <div className="w-full md:w-1/2 p-6 sm:p-8 flex items-center justify-center">
                    <div className="w-full max-w-md">
                        {/* Tabs */}
                        {formMode === "main" && (
                            <motion.div initial="hidden" animate="visible" variants={panelVariant} className="mb-4">
                                <div className="flex justify-center mb-4 space-x-6">
                                    <button
                                        onClick={() => {
                                            setActiveTab("login");
                                            resetAll();
                                        }}
                                        className={`font-semibold ${activeTab === "login" ? "text-orange-600 border-b-2 border-orange-600" : "text-gray-500"
                                            }`}
                                    >
                                        Login
                                    </button>
                                    <button
                                        onClick={() => {
                                            setActiveTab("signup");
                                            resetAll();
                                        }}
                                        className={`font-semibold ${activeTab === "signup" ? "text-orange-600 border-b-2 border-orange-600" : "text-gray-500"
                                            }`}
                                    >
                                        Sign Up
                                    </button>
                                </div>

                                <div className="flex justify-center mb-6 space-x-3 sm:space-x-6">
                                    <button
                                        onClick={() => {
                                            setLoginMode("email");
                                            resetAll();
                                        }}
                                        className={`px-4 py-2 rounded-md text-sm sm:text-base font-medium ${loginMode === "email"
                                                ? "bg-linear-to-r from-orange-500 to-orange-600 text-white shadow-md"
                                                : "bg-gray-200"
                                            }`}
                                    >
                                        Email
                                    </button>
                                    <button
                                        onClick={() => {
                                            setLoginMode("phone");
                                            resetAll();
                                        }}
                                        className={`px-4 py-2 rounded-md text-sm sm:text-base font-medium ${loginMode === "phone"
                                                ? "bg-linear-to-r from-orange-500 to-orange-600 text-white shadow-md"
                                                : "bg-gray-200"
                                            }`}
                                    >
                                        Phone
                                    </button>
                                </div>
                            </motion.div>
                        )}

                        {/* EMAIL FORM */}
                        {formMode === "main" && loginMode === "email" && (
                            <motion.form
                                initial="hidden"
                                animate="visible"
                                variants={panelVariant}
                                onSubmit={activeTab === "login" ? handleEmailLogin : handleEmailSignup}
                                className="space-y-4"
                            >
                                {activeTab === "signup" && (
                                    <input
                                        type="text"
                                        placeholder="Admin Name"
                                        value={signupData.adminName}
                                        onChange={(e) => setSignupData({ ...signupData, adminName: e.target.value })}
                                        className="w-full border p-3 rounded-md text-sm sm:text-base"
                                        required
                                    />
                                )}

                                <input
                                    type="email"
                                    placeholder="Email"
                                    value={activeTab === "login" ? loginData.email : signupData.email}
                                    onChange={(e) =>
                                        activeTab === "login"
                                            ? setLoginData({ ...loginData, email: e.target.value })
                                            : setSignupData({ ...signupData, email: e.target.value })
                                    }
                                    className="w-full border p-3 rounded-md text-sm sm:text-base"
                                    required
                                />

                                <label className="block relative">
                                    <input
                                        type={showPassword ? "text" : "password"}
                                        placeholder="Password"
                                        value={activeTab === "login" ? loginData.password : signupData.password}
                                        onChange={(e) =>
                                            activeTab === "login"
                                                ? setLoginData({ ...loginData, password: e.target.value })
                                                : setSignupData({ ...signupData, password: e.target.value })
                                        }
                                        className="w-full border p-3 rounded-md text-sm sm:text-base"
                                        required
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowPassword(!showPassword)}
                                        className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 text-xs sm:text-sm"
                                    >
                                        {showPassword ? "Hide" : "Show"}
                                    </button>
                                </label>

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

                                <button
                                    type="submit"
                                    className="w-full bg-linear-to-r from-orange-500 to-orange-600 text-white py-3 rounded-md font-semibold hover:brightness-105 transition shadow-sm"
                                >
                                    {activeTab === "login" ? "Login" : "Sign Up"}
                                </button>
                            </motion.form>
                        )}

                        {/* PHONE OTP FORM */}
                        {formMode === "main" && loginMode === "phone" && (
                            <motion.form
                                initial="hidden"
                                animate="visible"
                                variants={panelVariant}
                                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 text-sm sm:text-base"
                                    required
                                />

                                {otpSent && (
                                    <div className="space-y-2">
                                        <div className="flex justify-center gap-2 sm:gap-3" onPaste={handleOtpPaste}>
                                            {otpValues.map((v, i) => (
                                                <input
                                                    key={i}
                                                    ref={(el) => (otpRefs.current[i] = el)}
                                                    inputMode="numeric"
                                                    type="text"
                                                    maxLength="1"
                                                    value={v}
                                                    onChange={(e) => handleOtpChange(i, e.target.value)}
                                                    className="w-10 sm:w-12 border p-2 rounded text-center text-lg focus:outline-none focus:ring-2 focus:ring-orange-400"
                                                />
                                            ))}
                                        </div>

                                        <div className="flex items-center justify-between mt-2">
                                            <p className="text-xs sm:text-sm text-gray-600">
                                                Time left: <span className={`${timer <= 30 ? "text-red-600 font-semibold" : ""}`}>{formatTimer(timer)}</span>
                                            </p>
                                            <button
                                                type="button"
                                                onClick={handleResendOtp}
                                                disabled={timer > 0}
                                                className={`text-sm px-3 py-1 rounded ${timer > 0 ? "bg-gray-200 text-gray-500 cursor-not-allowed" : "bg-orange-600 text-white hover:bg-orange-500"
                                                    }`}
                                            >
                                                Resend
                                            </button>
                                        </div>
                                    </div>
                                )}

                                <button
                                    type="submit"
                                    className="w-full bg-linear-to-r from-orange-500 to-orange-600 text-white py-3 rounded-md font-semibold hover:brightness-105 transition"
                                >
                                    {otpSent ? "Verify OTP" : "Send OTP"}
                                </button>
                            </motion.form>
                        )}

                        {/* Forgot Password */}
                        {formMode === "forgot" && (
                            <motion.form
                                initial="hidden"
                                animate="visible"
                                variants={panelVariant}
                                onSubmit={handleForgotPassword}
                                className="space-y-4"
                            >
                                <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>
                            </motion.form>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
}
