import { FC, useEffect, ReactNode } from 'react';
import { useFormContext } from 'react-hook-form';

import Stack from '@material-hu/mui/Stack';

import FormSwitcher from '@material-hu/components/design-system/Switcher/form';

import AdvancedFilterAccordion from 'src/components/AdvancedFilter/Accordion';

export type AdvancedFilterProps = {
  name: string;
  title: string;
  description: string;
  expanded: boolean;
  children: ReactNode;
  keyReset?: string;
  multiple?: boolean;
};

const AdvancedFilter: FC<AdvancedFilterProps> = props => {
  const {
    name,
    title,
    description,
    expanded,
    children,
    keyReset,
    multiple = false,
  } = props;

  const { reset, watch } = useFormContext();

  const enabledField = watch(name);

  useEffect(() => {
    if (!enabledField) {
      reset(prevValues => ({
        ...prevValues,
        [keyReset as string]: multiple ? [] : null,
      }));
    }
  }, [enabledField]);

  return (
    <AdvancedFilterAccordion
      label={
        <Stack
          sx={{
            alignItems: 'center',
            flexDirection: 'row',
            justifyContent: 'space-between',
            gap: 4,
            width: '100%',
          }}
        >
          <FormSwitcher
            name={name}
            switcherProps={{
              sx: { width: 'unset', minWidth: '100%' },
              title,
              description,
            }}
          />
        </Stack>
      }
      accordionProps={{
        sx: {
          backgroundColor: ({ palette }) =>
            enabledField ? palette.new.background.layout.default : 'initial',
          '&:before': {
            display: 'none',
          },
          '& .MuiAccordionSummary-expandIconWrapper': {
            display: 'none',
          },
          '& .MuiCollapse-root': {
            maxHeight: '260px',
            overflow: 'scroll',
          },
        },
        expanded,
      }}
      withDivider={false}
    >
      {children}
    </AdvancedFilterAccordion>
  );
};

export default AdvancedFilter;
