import {
  AppShell,
  Burger,
  Group,
  Tooltip,
  UnstyledButton,
  Title,
  useMantineTheme,
} from '@mantine/core';
import { useMediaQuery } from '@mantine/hooks';
import { useEffect, useMemo } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';

import { submenuLinks } from './Links_Appshell/submenuLinks';
import { mainLinksdata } from './Links_Appshell/navigationsLinks';
import { default as LogoIcon } from '../icons/favicon';

import classes from './Appshell.module.css';

import {
  useAppShellStore,
  getLastSubmenuRoute,
  setLastSubmenuRoute,
} from '@/stores/useAppShellStore';

type AppShellWithMenuProps = {
  children?: React.ReactNode;
};

export function AppShellWithMenu({ children }: AppShellWithMenuProps) {
  const theme = useMantineTheme();
  const location = useLocation();
  const navigate = useNavigate();
  const isMobile = useMediaQuery('(max-width: 768px)');

  // Zustand store
  const {
    activeMain,
    setActiveMain,
    activeLink,
    setActiveLink,
    mobileOpened,
    desktopOpened,
    toggleMobile,
    toggleDesktop,
    openDesktop,
    closeMobile,
  } = useAppShellStore();

  const isCollapsed = useMemo(
    () => (isMobile ? !mobileOpened : !desktopOpened),
    [isMobile, mobileOpened, desktopOpened]
  );

  // Detectar main activo según la ruta
  useEffect(() => {
    const currentPath =
      location.pathname?.toLowerCase().replace(/\/$/, '') ?? '';

    let matchedMain: string | null = null;
    let maxMatchLength = 0;

    Object.entries(submenuLinks).forEach(([main, items]) => {
      items.forEach((item: { to: string }) => {
        const itemPath = item.to.toLowerCase().replace(/\/$/, '');
        if (currentPath === itemPath || currentPath.startsWith(`${itemPath  }/`)) {
          if (itemPath.length > maxMatchLength) {
            matchedMain = main;
            maxMatchLength = itemPath.length;
          }
        }
      });
    });

    if (matchedMain) {setActiveMain(matchedMain);}
  }, [location.pathname, setActiveMain]);

  // Actualizar activeLink
  useEffect(() => {
    const sublinks = submenuLinks[activeMain as keyof typeof submenuLinks] || [];
    const found = sublinks.find((item) => item.to === location.pathname);
    setActiveLink(found?.label ?? '');
  }, [location.pathname, activeMain, setActiveLink]);

  const mainLinks = mainLinksdata.map((link) => (
    <Tooltip
      label={link.label}
      position="right"
      withArrow
      transitionProps={{ duration: 0 }}
      key={link.label}
    >
      <UnstyledButton
        onClick={() => {
          setActiveMain(link.label);
          const remembered = getLastSubmenuRoute(link.label);
          const fallback =
            submenuLinks[link.label as keyof typeof submenuLinks]?.[0]?.to;
          if (isCollapsed && (remembered || fallback)) {
            navigate(remembered ?? fallback);
          }
        }}
        className={classes.mainLink}
        data-active={link.label === activeMain || undefined}
      >
        <link.icon size={24} weight="duotone" />
      </UnstyledButton>
    </Tooltip>
  ));

  const links: React.ReactNode = (
    (submenuLinks[activeMain as keyof typeof submenuLinks] || []) as {
      label: string;
      to: string;
    }[]
  ).map((item) => (
    <Link
      className={classes.link}
      data-active={activeLink === item.label || undefined}
      to={item.to}
      key={item.label}
      style={{ display: isCollapsed ? 'none' : 'block' }}
      onClick={() => {
        setLastSubmenuRoute(activeMain, item.to);
        if (isMobile) {closeMobile();}
      }}
    >
      {item.label}
    </Link>
  ));

  useEffect(() => {
    if (!isMobile) {openDesktop();}
  }, [isMobile, openDesktop]);

  return (
    <AppShell
      header={{ height: 60 }}
      navbar={{
        width: isCollapsed ? 60 : 300,
        breakpoint: 'sm',
        collapsed: { mobile: !mobileOpened, desktop: !desktopOpened },
      }}
      padding={0}
      styles={{
        main: {
          height: '100dvh', // o '100vh', pero mejor con 100dvh para evitar bugs móviles
          display: 'flex',
          flexDirection: 'column',
        },
      }}
    >
      {/* Header */}
      <AppShell.Header>
        <Group h="100%" px="sm">
          <Burger
            opened={mobileOpened}
            onClick={toggleMobile}
            hiddenFrom="sm"
            size="sm"
          />
          <Burger
            opened={desktopOpened}
            onClick={toggleDesktop}
            visibleFrom="sm"
            size="sm"
          />
          <LogoIcon
            style={{ width: 30, height: 30 }}
            circleFill={theme.colors.brand[9]}
            pathFill={theme.colors.secondary[2]}
          />
        </Group>
      </AppShell.Header>

      {/* Navbar */}
      <AppShell.Navbar>
        <div className={classes.wrapper}>
          <div className={classes.aside}>
            <div className={classes.topSection}>{mainLinks}</div>
          </div>
          <div className={classes.main}>
            {!isCollapsed && (
              <Title order={4} className={classes.title}>
                {activeMain}
              </Title>
            )}
            {links}
          </div>
        </div>
      </AppShell.Navbar>

      {/* Main Content */}
      <AppShell.Main>{children}</AppShell.Main>
    </AppShell>
  );
}
