/* eslint-disable jsx-a11y/anchor-is-valid */
import React, { useState, useEffect } from "react";
import Sidebar from "./sidebar";
import { useNavigate } from "react-router-dom";
import UserMaintanceComponent from "./UserMaintance";
import UserGroupMaintanceComponent from "./UserGroupMaintance/UserGroupMaintance";
import MenuMaintanceComponent from "./MenuMaintance/MenuMaintance";
import MenuAccessControlComponent from "./MenuAccessControl/MenuAccessControl";
import SystemParametersComponent from "./SystemParameters/SystemParameters";
// import AccessTypeComponent from "./AccessType/AccessType";
import ApiRegistery from "./ApiRegistery/ApiRegistery";
import TokenRegistery from "./TokenRegistery/TokenRegistery";
import HomePage from "./HomePage";
import Setup from "./Setup.js";
import Report from "./Report";
import { FaCog, FaUsers, FaSignOutAlt, FaHome, FaChartBar } from "react-icons/fa";

const Dashboard = () => {
  const navigate = useNavigate();
  const [menus, setMenus] = useState([]);
  const [selectedUserMaintance, setSelectedUserMaintance] = useState(null);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [content, setContent] = useState("");

  useEffect(() => {
    const fetchMenusData = async () => {
      const token = localStorage.getItem("authtoken");

      const apiUrl = `${process.env.REACT_APP_API_BASE_URL}/fndMenu/menuloadbyuser`;
      console.log("Fetching menus from API:", apiUrl);

      try {
        const response = await fetch(apiUrl, {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
        });

        if (response.ok) {
          const menuData = await response.json();
          setMenus(menuData);
        } else {
          const errorText = await response.text();
          console.error(
            "Failed to fetch menus. Status:",
            response.status,
            "Response:",
            errorText
          );
        }
      } catch (error) {
        console.error("Error during menu fetch:", error);
      }
    };

    fetchMenusData();
  }, [navigate]);

  const handleMenuItemClick = (menuItem) => {
    setSelectedUserMaintance(menuItem);
    setContent(menuItem.menuItemDesc); // Update content based on clicked menu item
  };

  const handleHomeClick = () => {
    setSelectedUserMaintance(null);
    setContent("Home");
  };

  const handleSetupClick = () => {
    setSelectedUserMaintance(null);
    setContent("Setup");
  };

  const handleReportClick = () => {
    setSelectedUserMaintance(null);
    setContent("Report");
  };

  const handleSidebarToggle = () => {
    setSidebarCollapsed(!sidebarCollapsed);
  };

  const handleLogout = () => {
    localStorage.removeItem("authToken");
    localStorage.removeItem("user");
    navigate("/");
  };

  return (
    <div className="flex flex-col h-screen bg-gradient-to-br from-purple-50 via-white to-blue-50">
      {/* Top Navigation Bar */}
      <div className="flex justify-between items-center bg-gradient-to-r from-purple-600 to-indigo-600 text-white p-4 shadow-lg">
        <div className="flex items-center space-x-4">
          <h3 className="text-2xl font-bold">Dashboard</h3>
          <div className="h-6 w-px bg-white/30"></div>
          <nav className="flex space-x-6">
            <button 
              onClick={handleHomeClick}
              className="flex items-center space-x-2 hover:text-purple-200 transition-colors"
            >
              <FaHome className="w-5 h-5" />
              <span>Home</span>
            </button>
            <button 
              onClick={handleSetupClick}
              className="flex items-center space-x-2 hover:text-purple-200 transition-colors"
            >
              <FaCog className="w-5 h-5" />
              <span>Setup</span>
            </button>
            <button 
              onClick={handleReportClick}
              className="flex items-center space-x-2 hover:text-purple-200 transition-colors"
            >
              <FaChartBar className="w-5 h-5" />
              <span>Reports</span>
            </button>
          </nav>
        </div>
        <button
          className="flex items-center space-x-2 bg-white/10 hover:bg-white/20 text-white font-semibold py-2 px-4 rounded-lg transition-all duration-200"
          onClick={handleLogout}
        >
          <FaSignOutAlt className="w-5 h-5" />
          <span>Logout</span>
        </button>
      </div>

      <div className="flex flex-1 overflow-hidden">
        {/* Sidebar */}
        <div
          className={`bg-gradient-to-b from-purple-700 to-indigo-800 text-white transition-all duration-300 ${
            sidebarCollapsed ? "w-16" : "w-64"
          } min-w-16 shadow-xl`}
        >
          <div className="flex justify-end p-2">
            <button 
              onClick={handleSidebarToggle} 
              className="text-white/80 hover:text-white bg-white/10 hover:bg-white/20 p-2 rounded-lg transition-all duration-200"
            >
              {sidebarCollapsed ? ">>" : "<<"}
            </button>
          </div>
          <Sidebar
            menus={menus}
            handleMenuItemClick={handleMenuItemClick}
            collapsed={sidebarCollapsed}
            setCollapsed={setSidebarCollapsed}
          />
        </div>

        {/* Main Content Area */}
        <div className="flex-1 p-6 overflow-auto bg-gradient-to-br from-purple-50 via-white to-blue-50">
          <div className="max-w-7xl mx-auto">
            {content === "Setup" ? (
              <div className="bg-white rounded-xl shadow-lg p-6">
                <Setup />
              </div>
            ) : content === "Home" ? (
              <div className="bg-white rounded-xl shadow-lg p-6">
                <HomePage />
              </div>
            ) : content === "Report" ? (
              <div className="bg-white rounded-xl shadow-lg p-6">
                <Report />
              </div>
            ) : selectedUserMaintance ? (
              <div className="bg-white rounded-xl shadow-lg p-6">
                <h3 className="text-2xl font-bold text-gray-800 mb-6 pb-2 border-b border-purple-100">
                  {selectedUserMaintance.menuItemDesc}
                </h3>
                {selectedUserMaintance.menuItemDesc === "User Maintance" ? (
                  <UserMaintanceComponent />
                ) : selectedUserMaintance.menuItemDesc === "User Group Maintance" ? (
                  <UserGroupMaintanceComponent />
                ) : selectedUserMaintance.menuItemDesc === "Menu Maintance" ? (
                  <MenuMaintanceComponent />
                ) : selectedUserMaintance.menuItemDesc === "Menu Access Control" ? (
                  <MenuAccessControlComponent />
                ) : selectedUserMaintance.menuItemDesc === "System Parameters" ? (
                  <SystemParametersComponent />
                ) : selectedUserMaintance.menuItemDesc === "Api Registery" ? (
                  <ApiRegistery />
                ) : selectedUserMaintance.menuItemDesc === "Token Registery" ? (
                  <TokenRegistery />
                ) : null}
              </div>
            ) : (
              <div className="bg-white rounded-xl shadow-lg p-6">
                <HomePage />
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
