import React, { useState, useEffect } from "react";
import { Layout, Menu, Breadcrumb, Button } from "antd";
import {
  HomeOutlined,
  LogoutOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
} from "@ant-design/icons";
import { useHistory, useLocation, Link } from "react-router-dom";
import { useAuth } from "../../hooks";
import { dashboardRoutes } from "../../routers";
import "../../styles/DashboardLayout.less";
import {Helmet} from "react-helmet-async";
const { REACT_APP_VERSION } = process.env;

const { Header, Content, Footer, Sider } = Layout;

const rootSubmenuKeys = [""];

const DashboardLayout = ({ children: PanelContent }) => {
  const history = useHistory();
  const [collapsed, setCollapsed] = useState(true);
  const [openKeys, setOpenKeys] = useState([""]);
  const [selectedKey, setSelectedKey] = useState("");
  const [breadcrumbItems, setBreadcrumbItems] = useState([]);
  const [titulo, setTitulo] = useState("");
  const location = useLocation();
  const { userLoading, signOut, session, userDoc } = useAuth();

  const esAdmin = userDoc?.rol === "admin";
  let finalDashboardRoutes = dashboardRoutes;
  if( !esAdmin ) {
    finalDashboardRoutes = finalDashboardRoutes.filter(f => !f?.path.includes("administracion"));
  }

  useEffect(() => {
    const flatter = (r) =>
      r?.routes
        ? [
            r,
            ...r?.routes
              .map((sub) => ({ ...sub, path: r.path + sub.path }))
              .flatMap(flatter),
          ]
        : r;
    const flatted = dashboardRoutes.flatMap(flatter);
    const paths = flatted.map((r) => r.path);
    const key = paths.find((path) => path === location.pathname);
    setSelectedKey(key);
    const tmpOpenKeys = flatted
      .filter(
        (r) =>
          r?.sidebar === "collapse" && location?.pathname?.includes(r?.path)
      )
      .map((r) => "collapse-" + r.path);
    setOpenKeys(tmpOpenKeys);
  }, [location]);

  const onOpenChange = (keys) => {
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys);
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  };

  const sidebarMapper = (route) => {
    if (route.sidebar === "single") {
      return {
        key: route.path,
        icon: route.icon,
        label: route.name,
        onClick: () => {
          setSelectedKey(route.path);
          history.push(route.path);
        },
      };
    } else if (route.sidebar === "collapse") {
      const innerMap = (r) => ({ ...r, path: route.path + r.path });
      const finalKey = "collapse-" + route.path;
      return {
        key: finalKey,
        icon: route.icon,
        label: route.name,
        children: route.routes.map(innerMap).map(sidebarMapper),
      };
    }
    return null;
  };

  useEffect(() => {
    const rutasBreadCrumbs = (
      rutasOrig,
      rutaDividida,
      indice = 0,
      ruta = ""
    ) => {
      let rutas = [];
      let path = "";
      
      if (indice === 0) {
        return rutasBreadCrumbs(rutasOrig, rutaDividida, indice + 1);
      }
      if (indice > rutaDividida.length - 1) {
        return rutas;
      }
      if (rutaDividida.length >= indice + 1 && rutaDividida[indice] !== "") {
        path = rutasOrig.find(
          (r) => r?.path.indexOf(rutaDividida[indice]) !== -1
        );
        if (path !== undefined) {
          ruta += path?.path;
          rutas.push({
            name: path?.name,
            to: ruta,
            icon: path?.icon,
          });
        }
        rutas = [
          ...rutas,
          ...rutasBreadCrumbs(path?.routes, rutaDividida, indice + 1, ruta),
        ];

        setTitulo(`${rutas[rutas?.length - 1]?.name} - LAUD`);
      }
      return rutas;
    };

    let rutas = [
      { name: "Inicio", to: "/", icon: <HomeOutlined /> },
      ...rutasBreadCrumbs(dashboardRoutes, location?.pathname?.split("/")),
    ];

    setBreadcrumbItems(rutas);
  }, [location?.pathname]);

  if (!session && userLoading) return null;

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Helmet><title>{titulo}</title></Helmet>
      <Sider
        trigger={null}
        id="auth-sider"
        breakpoint="md"
        collapsedWidth={60}
        collapsible
        onBreakpoint={()=>setCollapsed(!collapsed)}
        collapsed={collapsed}
        theme="light"
        width={236}
      >
        <div
          className={collapsed ? "logo-collapsed" : "logo"}
          style={{
            height: collapsed ? 50 : 103,
            margin: 0,
            backgroundImage: collapsed
              ? `url("/assets/LAUD-Avatar.png")`
              : `url("/assets/LAUD-Logotipo.png")`,
          }}
        />

        <Menu
          theme="dark"
          mode="inline"
          openKeys={openKeys}
          onOpenChange={onOpenChange}
          className="sider-menu"
          selectedKeys={selectedKey}
          inlineIndent={18}
          items={[
            ...finalDashboardRoutes.map(sidebarMapper),
            {
              key: "logout",
              icon: <LogoutOutlined />,
              label: "Cerrar sesión",
              onClick: () => signOut(),
            },
          ]}
        ></Menu>
      </Sider>

      <Layout className="site-layout">
        <Header style={{ padding: 0 }}>
          <div className="ed-topbar">
            <div className="breadcrumb">
              <Button
                type="link"
                icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                className="trigger"
                onClick={() => setCollapsed(!collapsed)}
              />

              <Breadcrumb>
                {breadcrumbItems?.map((item, index) => (
                  <Breadcrumb.Item key={index}>
                    <Link to={item?.to}>
                      {item?.icon}
                      <span> {item?.name} </span>
                    </Link>
                  </Breadcrumb.Item>
                ))}
              </Breadcrumb>
            </div>

            <div className="user">
              {userDoc?.email}
            </div>
          </div>
        </Header>
        <Content
          className="site-layout-background"
          style={{
            padding: 0,
            minHeight: 280,
          }}
        >
          {PanelContent}
        </Content>
        <Footer style={{ textAlign: "center" }}>
          Derechos reservados {new Date().getFullYear()} &#xa9; - {REACT_APP_VERSION}
        </Footer>
      </Layout>
    </Layout>
  );
};

export default DashboardLayout;
