import { useEffect, useState } from 'react';

import { Collapse, Stack } from '@mui/material';
import { IconInfoCircle } from '@tabler/icons-react';

import CardContainer from '../../design-system/CardContainer';
import Switcher from '../../design-system/Switcher';
import Title from '../../design-system/Title';
import Tooltip from '../../design-system/Tooltip';

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

function SwitcherCard({
  children,
  onContentToggle,
  disabled,
  slotProps = {},
  sx,
  open,
}: SwitcherCardProps) {
  const [isOpen, setIsOpen] = useState(!!open);

  const handleContentToggle = () => {
    setIsOpen(!isOpen);
  };

  useEffect(() => {
    setIsOpen(!!open);
  }, [open]);

  // biome-ignore lint/correctness/useExhaustiveDependencies: onContentToggle must not be a dep — it changes reference on every render and would re-fire this effect with stale isOpen, overwriting an external reset
  useEffect(() => {
    onContentToggle?.(isOpen);
  }, [isOpen]);

  return (
    <CardContainer
      sx={{
        border: 'none',
        backgroundColor: theme => theme.palette.new.background.layout.default,
        gap: 2,
        ...sx,
      }}
      {...slotProps.root}
    >
      <Stack
        sx={{
          flexDirection: 'row',
          justifyContent: 'space-between',
        }}
      >
        {slotProps?.title && (
          <Stack
            sx={{
              flexDirection: 'row',
              flexGrow: 1,
              gap: 1,
              alignItems: 'center',
              color: theme => theme.palette.new.text.neutral.default,
            }}
          >
            <Title
              variant="S"
              title={slotProps?.title?.title}
              description={slotProps?.title?.description}
              sx={slotProps?.title?.sx}
              {...slotProps.title}
            />
            {slotProps?.tooltip && (
              <Tooltip {...slotProps.tooltip}>
                <IconInfoCircle />
              </Tooltip>
            )}
          </Stack>
        )}
        <Switcher
          value={isOpen}
          disabled={!!disabled}
          onChange={handleContentToggle}
          sx={{ alignSelf: 'end', width: 'auto' }}
          {...slotProps.switcher}
        />
      </Stack>
      <Collapse
        {...slotProps.collapse}
        in={isOpen}
      >
        {children}
      </Collapse>
    </CardContainer>
  );
}

export default SwitcherCard;
