import { useMemo, useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import Swal from "sweetalert2";
import { Eye, EyeOff, LogIn, Mail, Lock } from "lucide-react";
import { motion } from "framer-motion";
import "../../Styles/authentication/login.css";
import { useSession } from "../context/SessionContext";
import BASE_URL from "@backend/server/config";
import useRoles from "../authentication/useRoles";
import userImage from "../assets/user.png";
import ModernButton from "../components/ui/ModernButton";
import {
  getBrandContextHeaders,
  hydrateBrandSelection,
} from "../components/utils/axiosInstance";
import VerseOfTheDay from "./VerseOfTheDay";

export default function Login() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [passwordVisible, setPasswordVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  const navigate = useNavigate();
  const { user, setUser } = useSession();
  const { roles, loading: rolesLoading } = useRoles();

  // Prevent authenticated users from accessing the login page
  useEffect(() => {
    if (user?.isLoggedIn && user?.role) {
      const roleName = String(user.role).toUpperCase();
      navigate(roleName === "EMPLOYEE" ? "/employee/dashboard" : "/dashboard", { replace: true });
    }
  }, [user, navigate]);

  /**
   * Important:
   * This prevents this error:
   * TypeError: (t || []).map is not a function
   *
   * Because sometimes backend returns:
   * { success: true, data: [...] }
   *
   * Instead of:
   * [...]
   */
  const safeRoles = useMemo(() => {
    if (Array.isArray(roles)) return roles;
    if (Array.isArray(roles?.data)) return roles.data;
    if (Array.isArray(roles?.roles)) return roles.roles;
    if (Array.isArray(roles?.records)) return roles.records;
    return [];
  }, [roles]);

  const getRoleName = (role) => {
    return String(role?.role_name || role?.name || role?.role || "")
      .trim()
      .toUpperCase();
  };

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

    if (rolesLoading || loading) return;

    setLoading(true);

    try {
      const response = await axios.post(
        `${BASE_URL}/api/login`,
        { username, password },
        {
          headers: {
            "Content-Type": "application/json",
            ...getBrandContextHeaders(),
          },
          withCredentials: true,
        },
      );


      if (response.data?.message === "Login successful") {
        const userRole = String(response.data?.role || "")
          .trim()
          .toUpperCase();

        const actualFullName =
          response.data?.full_name || response.data?.username || username;

        const allowedBrands = Array.isArray(response.data?.allowed_brands)
          ? response.data.allowed_brands
          : response.data?.current_brand
            ? [response.data.current_brand]
            : [];

        const currentBrand = response.data?.current_brand || null;

        const backendSelectedBrandCode =
          response.data?.selectedBrandCode || currentBrand?.brand_code || "";

        const selectedBrandCode = hydrateBrandSelection(
          allowedBrands,
          currentBrand,
          backendSelectedBrandCode,
        );

        const userObject = {
          user_id: response.data?.user_id || null,
          username: response.data?.username || username,
          full_name: response.data?.full_name || actualFullName,
          role: userRole,
          status: response.data?.status || "active",
          allowed_brands: allowedBrands,
          current_brand: currentBrand,
          selectedBrandCode,
          token: response.data?.token || null,
          isLoggedIn: true,
        };

        setUser(userObject);

        Swal.fire({
          icon: "success",
          title: "Welcome!",
          text: `Hello, ${actualFullName}!`,
          timer: 1500,
          showConfirmButton: false,
        });

        const employeeRoles = safeRoles
          .filter((r) => getRoleName(r) === "EMPLOYEE")
          .map((r) => getRoleName(r));

        const adminRoles = safeRoles
          .filter((r) => getRoleName(r) !== "EMPLOYEE")
          .map((r) => getRoleName(r))
          .filter(Boolean);

        setTimeout(() => {
          if (employeeRoles.includes(userRole)) {
            navigate("/employee/dashboard");
          } else if (adminRoles.includes(userRole)) {
            navigate("/dashboard");
          } else {
            /**
             * Fallback:
             * If roles API failed or returned empty, still route common roles properly.
             */
            if (userRole === "EMPLOYEE") {
              navigate("/employee/dashboard");
            } else if (userRole) {
              navigate("/dashboard");
            } else {
              navigate("/unauthorized");
            }
          }
        }, 1400);
      } else {
        Swal.fire({
          icon: "error",
          title: "Login Failed",
          text: response.data?.message || "Invalid username or password",
        });
      }
    } catch (error) {
      console.error("Login error:", error);

      Swal.fire({
        icon: "warning",
        title: "Server Issue",
        text:
          error?.response?.data?.message ||
          "Hostinger might be under high load. Please check their status page.",
        footer: `<a href="https://status.hostinger.com" target="_blank" rel="noopener" class="text-indigo-600 underline font-semibold">Check Hostinger Status</a>`,
      });
    } finally {
      setLoading(false);
    }
  };

  if (rolesLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-slate-50">
        <div className="flex flex-col items-center gap-3">
          <span className="w-6 h-6 border-2 rounded-full border-sky-600 border-t-transparent animate-spin" />
          <p className="text-sm font-medium text-slate-600">Loading roles...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col min-h-screen overflow-hidden lg:flex-row bg-linear-to-br from-sky-100 via-white to-sky-200">
      {/* LEFT PANEL */}
      <motion.div
        initial={{ opacity: 0, x: -40 }}
        animate={{ opacity: 1, x: 0 }}
        transition={{ duration: 0.6 }}
        className="relative flex-col items-center justify-center hidden h-screen p-12 lg:flex lg:w-1/2"
      >
        <div className="max-w-md text-center">
          <img
            src="/systemImage/HorizonHR-logoPC.png"
            alt="HorizonHR"
            className="mx-auto w-100 drop-shadow-2xl"
          />
        </div>

        <div className="absolute left-0 right-0 flex justify-center w-full px-8 bottom-10">
          <VerseOfTheDay />
        </div>
      </motion.div>

      {/* RIGHT PANEL */}
      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        className="relative z-10 flex items-center justify-center w-full min-h-screen p-6 lg:w-1/2"
      >
        <div className="flex flex-col items-center w-full max-w-lg">
          <div className="w-full p-8 bg-white border border-gray-100 shadow-2xl rounded-2xl">
            <div className="flex flex-col items-center gap-3 mb-6 text-center">
              <div className="p-3 border rounded-xl bg-sky-50 border-sky-100">
                <img
                  src={userImage}
                  alt="User"
                  className="object-contain w-10 h-10"
                />
              </div>

              <h1 className="text-2xl font-bold text-slate-800">
                Welcome back
              </h1>

              <p className="text-sm text-slate-500">
                Sign in to continue to Horizon HR
              </p>
            </div>

            <form onSubmit={handleLogin} className="space-y-5">
              <div>
                <label className="block mb-2 text-sm font-semibold text-slate-700">
                  User ID
                </label>

                <div className="relative">
                  <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                    <Mail className="w-5 h-5 text-slate-400" />
                  </div>

                  <input
                    aria-label="username"
                    type="text"
                    placeholder="Employee ID or username"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-400 focus:border-transparent transition"
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block mb-2 text-sm font-semibold text-slate-700">
                  Password
                </label>

                <div className="relative">
                  <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                    <Lock className="w-5 h-5 text-slate-400" />
                  </div>

                  <input
                    aria-label="password"
                    type={passwordVisible ? "text" : "password"}
                    placeholder="Enter your password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="w-full pl-10 pr-12 py-2.5 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-400 focus:border-transparent transition"
                    required
                  />

                  <button
                    type="button"
                    onClick={() => setPasswordVisible((prev) => !prev)}
                    aria-label={
                      passwordVisible ? "Hide password" : "Show password"
                    }
                    className="absolute right-1 top-1/2 flex h-10 w-10 -translate-y-1/2 cursor-pointer items-center justify-center rounded-lg text-slate-500 transition hover:bg-slate-100 hover:text-sky-600"
                  >
                    {passwordVisible ? (
                      <EyeOff className="w-5 h-5" />
                    ) : (
                      <Eye className="w-5 h-5" />
                    )}
                  </button>
                </div>
              </div>

              <div className="flex items-center justify-end">
                <button
                  type="button"
                  className="cursor-pointer text-sm text-sky-600 hover:underline"
                  onClick={() => navigate("/reset-password")}
                >
                  Forgot password?
                </button>
              </div>

              <ModernButton
                type="submit"
                disabled={rolesLoading}
                loading={loading}
                loadingText="Logging in..."
                fullWidth
                size="lg"
                icon={<LogIn />}
                className="font-semibold"
              >
                Sign in
              </ModernButton>
            </form>

            <div className="mt-6 text-sm text-center text-gray-500">
              POWERED BY{" "}
              <a
                href="https://about.centraljuan.com"
                className="font-semibold text-slate-700 hover:underline"
                target="_blank"
                rel="noopener noreferrer"
              >
                Central Juan I.T. Solutions
              </a>
            </div>
          </div>

          <div className="w-full mt-8 mb-6 lg:hidden">
            <VerseOfTheDay />
          </div>
        </div>
      </motion.div>
    </div>
  );
}
