import { useState } from 'react';

import Skeleton from '@design-system/Skeleton';
import Stack from '@mui/material/Stack/Stack';
import Typography from '@mui/material/Typography/Typography';

import GroupAccordion from './components/GroupAccordion';
import { type CollapsibleGroupSelectorProps } from './types';

const CollapsibleGroupSelector = ({
  fieldName,
  groups,
  title,
  isLoading,
  expanded: expandedProp,
  onExpandedChange,
  selectAllLabel,
  withSearch = false,
  sx,
}: CollapsibleGroupSelectorProps) => {
  const [internalExpanded, setInternalExpanded] = useState(false);
  const [expandedGroup, setExpandedGroup] = useState<string | null>(null);

  const isControlled = expandedProp !== undefined;
  const isExpanded = isControlled ? expandedProp : internalExpanded;

  const handleExpandedChange = (next: boolean) => {
    if (!isControlled) setInternalExpanded(next);
    onExpandedChange?.(next);
  };

  if (isLoading) {
    return (
      <Skeleton
        height={28}
        sx={{ my: 1, ...sx }}
      />
    );
  }

  if (!groups?.length) return null;

  return (
    <Stack sx={{ gap: 2, ...sx }}>
      {title && (
        <Typography
          variant="globalM"
          fontWeight="fontWeightSemiBold"
          sx={{ mb: 2 }}
        >
          {title}
        </Typography>
      )}
      {groups.map(group => (
        <GroupAccordion
          key={group.value}
          isParentExpanded={isExpanded}
          setParentExpanded={handleExpandedChange}
          isExpanded={expandedGroup === group.name}
          setExpandedGroup={setExpandedGroup}
          group={group}
          groupFieldName={fieldName}
          selectAllLabel={selectAllLabel}
          withSearch={withSearch}
        />
      ))}
    </Stack>
  );
};

export type { CollapsibleGroupSelectorProps } from './types';

export default CollapsibleGroupSelector;
