import { useEffect, useState } from 'react';

import { Stack, useTheme } from '@mui/material';

import { type SubSidebarValue } from '../../types';
import SubSidebarAccordionsCollapsed from '../AccordionsCollapsed';
import SubSidebarAccordionsOpen from '../AccordionsOpen';
import SubSidebarAccordionsSkeleton from '../AccordionsSkeleton';

import { type SubSidebarAccordionsProps } from './types';

const SubSidebarAccordions = ({
  accordionSections,
  id,
  isCollapsed,
  handleClickItem,
  isLoading,
  defaultOpenAccordions = [],
}: SubSidebarAccordionsProps) => {
  const { transitions } = useTheme();
  const [delayedIsCollapsed, setDelayedIsCollapsed] = useState(isCollapsed);
  const [openAccordions, setOpenAccordions] = useState<SubSidebarValue[]>(
    defaultOpenAccordions,
  );

  useEffect(() => {
    const timer = setTimeout(
      () => {
        setDelayedIsCollapsed(isCollapsed);
      },
      isCollapsed ? 0 : transitions.duration.standard,
    );
    return () => clearTimeout(timer);
  }, [isCollapsed]);

  if (isLoading) return <SubSidebarAccordionsSkeleton />;
  if (!accordionSections) return null;

  const handleOpenAccordion = (sectionValue: SubSidebarValue) => {
    if (openAccordions.includes(sectionValue)) {
      setOpenAccordions(prev => prev.filter(prevId => prevId !== sectionValue));
    } else {
      setOpenAccordions(prev => [...prev, sectionValue]);
    }
  };

  return (
    <Stack
      sx={{
        mt: 1,
        p: delayedIsCollapsed ? 2 : 0,
        transition: transitions.create(['p'], {
          duration: transitions.duration.standard,
          easing: transitions.easing.easeInOut,
        }),
        opacity: delayedIsCollapsed === isCollapsed ? 1 : 0.5,
      }}
    >
      {accordionSections.map(section => {
        const props = {
          id,
          section,
          openAccordions,
          handleClickItem,
          handleOpenAccordion,
        };

        if (delayedIsCollapsed) {
          return (
            <SubSidebarAccordionsCollapsed
              key={`${id}-accordion-section-${section.value}`}
              {...props}
            />
          );
        }

        return (
          <SubSidebarAccordionsOpen
            key={`${id}-accordion-section-${section.value}`}
            {...props}
          />
        );
      })}
    </Stack>
  );
};

export default SubSidebarAccordions;
