/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useState } from "react";
import { Layout } from "antd";
import Sider from "antd/es/layout/Sider";
import { Route, Routes, useLocation, useNavigate } from "react-router-dom";
import SiderMenu from "@/components/SiderMenu";
import ProcessDiagramPage from "./ProcessDiagramPage";
import AccountsPage from "./AccountsPage";
import ConfigurationPage from "./ConfigurationPage";
import EventsListPage from "./EventsListPage";
import RunningProcessesPage from "./RunningProcessesPage";

export default function MainLayout() {
  const navigate = useNavigate();
  const location = useLocation();
  const [collapsed, setCollapsed] = useState(false);
  const [selectedKey, setSelectedKey] = useState("1");

  const [width, setWidth] = useState<number | string>("15%");
  const [collapsedWidth, setCollapsedWidth] = useState(50);

  const calculateWidths = () => {
    const windowWidth = window.innerWidth;
    const expanded = Math.min(Math.max(windowWidth * 0.15, 180), 240);
    const collapsed = Math.max(windowWidth * 0.038, 50);
    setWidth(expanded);
    setCollapsedWidth(collapsed);
  };

  useEffect(() => {
    calculateWidths();
    window.addEventListener("resize", calculateWidths);
    return () => window.removeEventListener("resize", calculateWidths);
  }, []);

  useEffect(() => {
    if (location.pathname === "/") {
      navigate("/process-diagram");
    }
    setSelectedKey(location.pathname);
  }, [location.pathname]);

  function hangleMenuClick(e: any) {
    const key = e.key;
    if (key === "toggle") {
      setCollapsed(!collapsed);
      return;
    }
    if (key === "divider") {
      return;
    }

    setSelectedKey(key);
    navigate(key);
  }

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider
        className="sider"
        collapsible
        collapsed={collapsed}
        onCollapse={(value) => setCollapsed(value)}
        theme="light"
        width={width}
        collapsedWidth={collapsedWidth}
        trigger={null}
      >
        <SiderMenu
          collapsed={collapsed}
          selectedKey={selectedKey}
          hangleMenuClick={hangleMenuClick}
        />
      </Sider>
      <Layout>
        <Routes>
          <Route path="/process-diagram" element={<ProcessDiagramPage />} />
          <Route path="/running-processes" element={<RunningProcessesPage />} />
          <Route path="/accounts" element={<AccountsPage />} />
          <Route path="/events-list" element={<EventsListPage />} />
          <Route path="/configuration" element={<ConfigurationPage />} />
          <Route path="*" element={<div>404 Not Found</div>} />
        </Routes>
      </Layout>
    </Layout>
  );
}
