"use client";

import { useEffect, useState, useRef } from "react";
import { usePathname, useRouter } from "next/navigation";
import axios from "axios";
import {
  FaUser,
  FaSignOutAlt,
  FaUserCircle,
  FaChartLine,
  FaMoneyBillAlt,
  FaHandsHelping,
  FaComments,
} from "react-icons/fa";
import { FiMenu } from "react-icons/fi";
import { CgProfile } from "react-icons/cg";
import { IoTicketOutline } from "react-icons/io5";
import {
  BsPersonCheck,
  BsPencilSquare,
  BsFileText,
  BsCardList,
  BsTicketPerforated,
} from "react-icons/bs";
import { Briefcase, ClipboardList, Users, Gift, FileText } from "lucide-react";
import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
import BusinessCenterIcon from "@mui/icons-material/BusinessCenter";
import MobileSidebar from "./MobileSidebar";
import { useUserRefresh } from "@/context/UserRefreshContext"; // ← ADD THIS

const Header = ({ title, onPageChange }) => {
  const { refreshTrigger } = useUserRefresh(); // ← ADD THIS: Listen for refresh

  const [isMobileSidebarOpen, setIsMobileSidebarOpen] = useState(false);
  const [user, setUser] = useState(null);
  const [roles, setRoles] = useState([]);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [isRolesOpen, setIsRolesOpen] = useState(false);
  const [isUserDropdownOpen, setIsUserDropdownOpen] = useState(false);
  const [showUserDataModal, setShowUserDataModal] = useState(false);
  const [decodedUserData, setDecodedUserData] = useState(null);
  const [underlineKey, setUnderlineKey] = useState(0);
  const [dynamicTitle, setDynamicTitle] = useState(title);
  const [icon, setIcon] = useState(null);
  const [isLoggingOut, setIsLoggingOut] = useState(false);
  const [logoUrl, setLogoUrl] = useState(null);
  const [isLogoLoading, setIsLogoLoading] = useState(true);

  const pathname = usePathname();
  const router = useRouter();
  const rolesRef = useRef(null);
  const userDropdownRef = useRef(null);

  // Decode JWT
  const decodeJWT = (token) => {
    try {
      const base64Url = token.split(".")[1];
      if (!base64Url) throw new Error("Invalid token");
      const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
      const jsonPayload = decodeURIComponent(
        atob(base64)
          .split("")
          .map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
          .join("")
      );
      return JSON.parse(jsonPayload);
    } catch (error) {
      console.error("Error decoding JWT:", error);
      return null;
    }
  };

  // Fetch logo
  const fetchLogo = async () => {
    try {
      setIsLogoLoading(true);
      const userToken = localStorage.getItem("userToken");
      if (!userToken) return;
      const response = await axios.get(
        "https://eammsapi.old.bluai.ai/api/get-user-logo",
        {
          headers: { Authorization: `Bearer ${userToken}` },
        }
      );
      setLogoUrl(response.data.logo || "/bluaccess_logo_dark.png");
    } catch (error) {
      setLogoUrl("/bluaccess_logo_dark.png");
    } finally {
      setIsLogoLoading(false);
    }
  };

  // NEW: Fetch fresh user profile data (includes latest profile_image)
  const fetchFreshUserData = async () => {
    try {
      const userToken = localStorage.getItem("userToken");
      if (!userToken) {
        router.push("/");
        return;
      }

      // Decode JWT for base data
      const decoded = decodeJWT(userToken);
      if (!decoded) {
        router.push("/");
        return;
      }
      setDecodedUserData(decoded);

      // Fetch latest profile from backend (this has updated image, mobile, etc.)
      const response = await axios.get(
        "https://eammsapi.old.bluai.ai/api/user-profile",
        {
          headers: { Authorization: `Bearer ${userToken}` },
        }
      );

      const freshData = response.data;

      // Merge: Use fresh data for dynamic fields (image, name, mobile), fallback to JWT
      setUser({
        ...decoded,
        ...freshData, // This overrides profile_image, name if changed, etc.
        first_name: freshData.name || decoded.first_name || "User",
        company_code: freshData.company_code || decoded.company_code,
        profile_image: freshData.profile_image || "", // ← Critical: latest image
      });
    } catch (error) {
      console.error("Error fetching fresh user data:", error);
      if (error.response?.status === 401) {
        localStorage.removeItem("userToken");
        router.push("/");
      }
    }
  };

  // Fetch roles
  const fetchRoles = async () => {
    try {
      const userToken = localStorage.getItem("userToken");
      if (!userToken) return;
      const response = await axios.get(
        "https://eammsapi.old.bluai.ai/api/user-roles",
        {
          headers: { Authorization: `Bearer ${userToken}` },
        }
      );
      setRoles(response.data.roles || []);
    } catch (error) {
      if (error.response?.status === 401) {
        localStorage.removeItem("userToken");
        router.push("/");
      }
    }
  };

  // Re-fetch everything when refreshTrigger changes (after profile update)
  useEffect(() => {
    fetchFreshUserData();
    fetchLogo();
    fetchRoles();
  }, [refreshTrigger]); // ← This triggers update after profile save

  // Close dropdowns on outside click
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (rolesRef.current && !rolesRef.current.contains(event.target)) {
        setIsRolesOpen(false);
      }
      if (
        userDropdownRef.current &&
        !userDropdownRef.current.contains(event.target)
      ) {
        setIsUserDropdownOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Handle role switching
  const handleRoleClick = async (role) => {
    try {
      if (role === "travelsalesperson") {
        window.open("https://crmdev.eamms.bluai.ai", "_blank");
        setIsRolesOpen(false);
        return;
      }
      if (role !== "employee") {
        const userToken = localStorage.getItem("userToken");
        const response = await axios.post(
          "https://eammsapi.old.bluai.ai/api/admin/switch",
          {},
          {
            headers: {
              Authorization: `Bearer ${userToken}`,
              "Content-Type": "application/json",
            },
          }
        );
        if (response.data.success) {
          window.open("/admin-login", "_blank");
        }
      }
    } catch (error) {
      console.error("Error switching role:", error);
    } finally {
      setIsRolesOpen(false);
    }
  };

  // Handle logout
  const handleLogout = async () => {
    setIsLoggingOut(true);
    try {
      const userToken = localStorage.getItem("userToken");
      if (userToken) {
        await axios.post(
          "https://eammsapi.old.bluai.ai/api/user-comp-logout",
          {},
          {
            headers: { Authorization: `Bearer ${userToken}` },
          }
        );
      }
    } catch (error) {
      console.error("Logout error:", error);
    }
    localStorage.removeItem("userToken");
    setTimeout(() => router.push("/"), 500);
  };

  // Dynamic title and icon
  useEffect(() => {
    const navItems = [
      {
        path: "/user-portal/dashboard",
        title: "Dashboard",
        icon: (
          <svg
            className="w-6 h-6 mr-2"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth="2"
              d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"
            ></path>
          </svg>
        ),
      },
      {
        path: "/user-portal/profile",
        title: "Manage Profile",
        icon: <CgProfile className="mr-2" size={24} />,
      },
      {
        path: "/user-portal/attendance",
        title: "Employee Attendance",
        icon: <BsPersonCheck className="mr-2" size={24} />,
      },
      {
        path: "/user-portal/attendance-regularization",
        title: "Attendance Regularization",
        icon: <BsPencilSquare className="mr-2" size={24} />,
      },
      {
        path: "/user-portal/attendance-details",
        title: "Monthly Attendance",
        icon: <BsFileText className="mr-2" size={24} />,
      },
      {
        path: "/user-portal/leave",
        title: "Leave Application",
        icon: <Briefcase className="mr-2" size={24} />,
      },
      {
        path: "/user-portal/holiday-list",
        title: "Holiday List",
        icon: <Gift className="mr-2" size={24} />,
      },
      {
        path: "/user-portal/raise-ticket",
        title: "Raise Ticket",
        icon: <IoTicketOutline className="mr-2" size={24} />,
      },
      {
        path: "/user-portal/paystubs",
        title: "Paystubs",
        icon: <FileText className="mr-2" size={24} />,
      },
      {
        path: "/user-portal/us-paystubs",
        title: "US Paystubs",
        icon: <FileText className="mr-2" size={24} />,
      },
      {
        path: "/user-portal/performancereview",
        title: "Performance View",
        icon: <FaChartLine className="mr-2" size={24} />,
      },
      {
        path: "/user-portal/bonusreview",
        title: "Bonus View",
        icon: <FaMoneyBillAlt className="mr-2" size={24} />,
      },
      {
        path: "/user-portal/employeetoemplyeehelp",
        title: "Team Assistance Initiative",
        icon: <FaHandsHelping className="mr-2" size={24} />,
      },
      {
        path: "/user-portal/feedback",
        title: "Employee/Employer Feedback",
        icon: <FaComments className="mr-2" size={24} />,
      },
    ];

    const currentNavItem = navItems.find((item) => pathname === item.path);
    if (currentNavItem) {
      setDynamicTitle(currentNavItem.title);
      setIcon(currentNavItem.icon);
    } else {
      setDynamicTitle(title || "User Management");
      setIcon(<FaUser className="inline-block mr-2 text-blue-800" />);
    }
    setUnderlineKey((prev) => prev + 1);
  }, [pathname, title]);

  const LogoSkeleton = () => (
    <div className="flex items-center space-x-2 animate-pulse">
      <div className="w-12 h-12 bg-gray-300 rounded-lg"></div>
    </div>
  );

  return (
    <header className="bg-white shadow-md">
      <div className="px-4 py-4 flex justify-between items-center sm:px-6 lg:px-6">
        {/* Logo */}
        <div
          className="flex items-center lg:hidden cursor-pointer"
          onClick={() => router.push("/user-portal/dashboard")}
        >
          {isLogoLoading ? (
            <LogoSkeleton />
          ) : (
            <img
              src={logoUrl}
              alt="Company Logo"
              className="h-12 sm:h-16 w-auto"
            />
          )}
        </div>

        {/* Title */}
        <div className="flex-1 flex justify-center lg:justify-start">
          <h2 className="text-2xl font-bold text-gray-800 tracking-tight relative pb-1">
            <div className="flex items-center relative">
              {icon}
              <h2 className="text-2xl font-bold text-gray-800 tracking-tight relative pr-2">
                {user?.company_code || ""}
              </h2>
              {dynamicTitle}
              <span
                key={underlineKey}
                className="absolute -bottom-1 left-0 w-full h-[2px] bg-blue-800 origin-left"
                style={{ animation: "grow-underline 1s ease-in-out forwards" }}
              />
            </div>
            <style jsx>{`
              @keyframes grow-underline {
                0% {
                  transform: scaleX(0);
                }
                100% {
                  transform: scaleX(1);
                }
              }
            `}</style>
          </h2>
        </div>

        {/* Right Section */}
        <div className="flex items-center gap-6">
          <button
            className="lg:hidden text-gray-600 focus:outline-none"
            onClick={() => setIsMobileSidebarOpen(true)}
            aria-label="Toggle mobile menu"
          >
            <FiMenu className="w-6 h-6" />
          </button>

          <div className="hidden lg:flex items-center gap-4">
            {/* Roles Dropdown */}
            <div className="relative inline-block" ref={rolesRef}>
              <button
                className="flex items-center gap-1 text-sm text-gray-700 hover:text-blue-600 cursor-pointer focus:outline-none"
                onClick={() => setIsRolesOpen(!isRolesOpen)}
                onMouseEnter={() => setIsRolesOpen(true)}
                onMouseLeave={() => setIsRolesOpen(false)}
              >
                <BusinessCenterIcon fontSize="small" />
                <span>Roles</span>
                <ArrowDropDownIcon
                  style={{ transform: isRolesOpen ? "rotate(180deg)" : "none" }}
                />
              </button>
              {isRolesOpen && (
                <div
                  className="absolute left-1/2 transform -translate-x-1/2 w-34 bg-white border border-gray-200 rounded-md shadow-lg z-50 divide-y divide-gray-300"
                  onMouseEnter={() => setIsRolesOpen(true)}
                  onMouseLeave={() => setIsRolesOpen(false)}
                >
                  {roles.length > 0 ? (
                    roles.map((role, idx) => (
                      <button
                        key={`role-${idx}`}
                        onClick={() => handleRoleClick(role)}
                        className={`w-full text-left px-2 py-2 text-sm font-medium text-gray-700 hover:bg-gray-200 transition-colors duration-150 cursor-pointer capitalize ${
                          idx === 0 ? "rounded-t-md" : ""
                        } ${idx === roles.length - 1 ? "rounded-b-md" : ""}`}
                      >
                        {role}
                      </button>
                    ))
                  ) : (
                    <div className="px-4 py-3 text-sm text-gray-500 italic">
                      No roles assigned
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* User Dropdown */}
            <div className="relative inline-block" ref={userDropdownRef}>
              <button
                className="flex items-center gap-2 text-sm text-gray-700 hover:text-blue-600 cursor-pointer focus:outline-none"
                onClick={() => setIsUserDropdownOpen(!isUserDropdownOpen)}
                onMouseEnter={() => setIsUserDropdownOpen(true)}
                onMouseLeave={() => setIsUserDropdownOpen(false)}
              >
                {user && (
                  <div
                    className="flex items-center gap-3 px-3 py-2 rounded-full 
               bg-white/70 backdrop-blur-md 
               shadow-sm border border-gray-200 
               cursor-pointer transition-all duration-200 
               hover:shadow-md hover:bg-white"
                  >
                    {/* Avatar */}
                    <div className="relative">
                      <img
                        src={user.profile_image || "/default-avatar.png"}
                        alt="User Profile"
                        className="w-9 h-9 rounded-full object-cover 
                   ring-2 ring-indigo-500/30"
                        onError={(e) => (e.target.src = "/default-avatar.png")}
                      />

                      {/* Online indicator (optional) */}
                      <span
                        className="absolute bottom-0 right-0 w-2.5 h-2.5 
                       bg-green-500 border-2 border-white 
                       rounded-full"
                      ></span>
                    </div>

                    {/* Name */}
                    <div className="hidden md:flex flex-col leading-tight">
                      <span className="text-xs text-gray-500 tracking-wide">
                        Welcome
                      </span>
                      <span className="text-sm font-semibold text-gray-800 uppercase tracking-wide">
                        {user.first_name || "User"}
                      </span>
                    </div>

                    {/* Dropdown Icon */}
                    <ArrowDropDownIcon
                      className="text-gray-600 transition-transform duration-300"
                      style={{
                        transform: isUserDropdownOpen
                          ? "rotate(180deg)"
                          : "rotate(0deg)",
                      }}
                    />
                  </div>
                )}
              </button>

              {isUserDropdownOpen && (
                <div
                  className="absolute left-1/2 transform -translate-x-1/2 w-32 bg-white border border-gray-200 rounded-md shadow-lg z-50 divide-y divide-gray-300"
                  onMouseEnter={() => setIsUserDropdownOpen(true)}
                  onMouseLeave={() => setIsUserDropdownOpen(false)}
                >
                  <button
                    onClick={() => {
                      router.push("/user-portal/profile");
                      setIsUserDropdownOpen(false);
                    }}
                    className="w-full text-left px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-200 flex items-center cursor-pointer"
                  >
                    <FaUserCircle size={20} className="me-1" />
                    Profile
                  </button>
                  <button
                    onClick={() => {
                      setShowConfirmModal(true);
                      setIsUserDropdownOpen(false);
                    }}
                    className="w-full text-left px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-200 flex items-center cursor-pointer"
                  >
                    <FaSignOutAlt size={20} className="me-1" />
                    Logout
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Mobile Sidebar */}
      <MobileSidebar
        isOpen={isMobileSidebarOpen}
        onClose={() => setIsMobileSidebarOpen(false)}
        onPageChange={onPageChange}
      />

      {/* Logout Confirmation Modal */}
      {showConfirmModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div
            className="absolute inset-0 bg-black/30 backdrop-blur-md transition-opacity duration-300"
            onClick={() => setShowConfirmModal(false)}
          />
          <div className="relative w-full max-w-md max-h-[80vh] overflow-y-auto transform transition-all duration-300 ease-out animate-fade-in-up">
            <div className="bg-gradient-to-br from-white to-gray-50 rounded-xl shadow-2xl overflow-hidden border border-gray-100">
              <div className="p-6 border-b border-gray-100">
                <h2 className="text-2xl font-semibold text-gray-800">
                  Confirm Log Out
                </h2>
                <p className="mt-1 text-gray-500">
                  This action cannot be undone
                </p>
              </div>
              <div className="p-6">
                <div className="flex items-start">
                  <div className="flex-shrink-0 p-2 bg-red-100 rounded-full">
                    <svg
                      className="w-6 h-6 text-red-600"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
                      />
                    </svg>
                  </div>
                  <div className="ml-4">
                    <p className="mt-1 text-gray-600">
                      You're about to log out. Make sure all activities are
                      properly documented before proceeding.
                    </p>
                  </div>
                </div>
              </div>
              <div className="px-6 py-4 bg-gray-50 flex justify-end space-x-3">
                <button
                  onClick={() => setShowConfirmModal(false)}
                  className="px-5 py-2.5 text-sm font-medium rounded-lg border border-gray-300 text-gray-700 hover:bg-gray-100 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 cursor-pointer"
                  disabled={isLoggingOut}
                >
                  Cancel
                </button>
                <button
                  onClick={handleLogout}
                  className="px-5 py-2.5 text-sm font-medium rounded-lg bg-gradient-to-r from-red-500 to-red-600 text-white shadow-sm hover:from-red-600 hover:to-red-700 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 disabled:opacity-70 cursor-pointer"
                  disabled={isLoggingOut}
                >
                  {isLoggingOut ? (
                    <span className="flex items-center">
                      <svg
                        className="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
                        xmlns="http://www.w3.org/2000/svg"
                        fill="none"
                        viewBox="0 0 24 24"
                      >
                        <circle
                          className="opacity-25"
                          cx="12"
                          cy="12"
                          r="10"
                          stroke="currentColor"
                          strokeWidth="4"
                        ></circle>
                        <path
                          className="opacity-75"
                          fill="currentColor"
                          d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                        ></path>
                      </svg>
                      Processing...
                    </span>
                  ) : (
                    "Logout"
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* User Data Modal */}
      {showUserDataModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div
            className="absolute inset-0 bg-black/30 backdrop-blur-md transition-opacity duration-300"
            onClick={() => setShowUserDataModal(false)}
          />
          <div className="relative w-full max-w-md max-h-[80vh] overflow-y-auto transform transition-all duration-300 ease-out animate-fade-in-up">
            <div className="bg-gradient-to-br from-white to-gray-50 rounded-xl shadow-2xl overflow-hidden border border-gray-100">
              <div className="p-6 border-b border-gray-100">
                <h2 className="text-2xl font-semibold text-gray-800">
                  User Data
                </h2>
                <p className="mt-1 text-gray-500">
                  Details decoded from user token
                </p>
              </div>
              <div className="p-6">
                {decodedUserData ? (
                  <div className="space-y-2">
                    {Object.entries(decodedUserData).map(([key, value]) => (
                      <div key={key} className="flex justify-between text-sm">
                        <span className="font-medium text-gray-700 capitalize">
                          {key.replace(/_/g, " ")}:
                        </span>
                        <span className="text-gray-600">
                          {typeof value === "object"
                            ? JSON.stringify(value)
                            : value || "N/A"}
                        </span>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-gray-600">
                    No user data available. The token may be invalid or not a
                    JWT.
                  </p>
                )}
              </div>
              <div className="px-6 py-4 bg-gray-50 flex justify-end">
                <button
                  onClick={() => setShowUserDataModal(false)}
                  className="px-5 py-2.5 text-sm font-medium rounded-lg border border-gray-300 text-gray-700 hover:bg-gray-100 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 cursor-pointer"
                >
                  Close
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </header>
  );
};

export default Header;
