import React, { useState } from "react";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import PasswordPopup from "./PasswordPopup";

const AdminLayout = () => {
  const location = useLocation();
  const navigate = useNavigate();

  const [showPopup, setShowPopup] = useState(false);
  const [popupFor, setPopupFor] = useState(""); 

  const PASSWORDS = {
    Projects: "Lcepl@2026",   // ← set your Projects password
    Gallery: "Lcepl#2026",     // ← set your Gallery password
  };

  const menuItems = [
    { name: "Projects", path: "/admin/projects" },
    { name: "Gallery", path: "/admin/gallery" },
    { name: "HR", path: "/admin/hr" },
  ];

  // When user clicks menu
  const handleMenuClick = (item) => {
    if (item.name === "Projects" || item.name === "Gallery") {
      setPopupFor(item.name);
      setShowPopup(true);
    } else {
      navigate(item.path);
    }
  };

  // Validate password
  const handlePasswordSubmit = (password) => {
    if (password === PASSWORDS[popupFor]) {
      setShowPopup(false);
      navigate(`/admin/${popupFor.toLowerCase()}`);
    } else {
      alert("❌ Incorrect password");
    }
  };

  const handleLogout = () => {
    sessionStorage.removeItem("admin");
    navigate("/admin-login");
  };

  return (
    <div className="flex min-h-screen">

      {/* Sidebar */}
      <div className="w-64 bg-gray-800 text-white flex flex-col">
        <div className="text-2xl font-bold p-4 border-b border-gray-700">
          Admin Panel
        </div>

        <nav className="flex-1 p-4">
          {menuItems.map((item) => (
            <button
              key={item.name}
              onClick={() => handleMenuClick(item)}
              className={`w-full text-left px-4 py-2 rounded mb-2 hover:bg-gray-700 transition-colors ${
                location.pathname === item.path ? "bg-gray-700 font-semibold" : ""
              }`}
            >
              {item.name}
            </button>
          ))}
        </nav>
      </div>

      {/* Main Content */}
      <div className="flex-1 bg-gray-100 p-4 relative">

        <button
          onClick={handleLogout}
          className="absolute top-4 right-4 bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded"
        >
          Logout
        </button>

        <Outlet />
      </div>

      {/* Password Popup */}
      {showPopup && (
        <PasswordPopup
          title={`${popupFor} Access`}
          onSubmit={handlePasswordSubmit}
          onClose={() => setShowPopup(false)}
        />
      )}
    </div>
  );
};

export default AdminLayout;
