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

import HelpOutlineIcon from '@material-hu/icons/material/HelpOutline';
import Stack from '@material-hu/mui/Stack';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import AdvancedFilterAccordion from 'src/components/AdvancedFilter/Accordion';
import { uncheckAllOptions } from 'src/components/AdvancedFilter/utils';
import { FormSwitch } from 'src/components/FormInputs';

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

const AdvanceReportFilters: FC<AdvanceReportFiltersProps> = props => {
  const { name, title, description, expanded, children, keyReset } = props;

  const { reset, watch } = useFormContext();

  const enabledField = watch(name);

  useEffect(() => {
    if (!enabledField) {
      reset(prevValues => ({
        ...prevValues,
        [keyReset]: uncheckAllOptions(prevValues[keyReset]),
      }));
    }
  }, [enabledField]);

  return (
    <AdvancedFilterAccordion
      label={
        <Stack
          sx={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
            width: '100%',
            '& .MuiFormControlLabel-root': {
              mx: 0,
            },
          }}
        >
          <Stack sx={{ flexDirection: 'row', gap: 1 }}>
            <Typography variant="subtitle1">{title}</Typography>
            <Tooltip
              title={description}
              sx={{ color: theme => theme.palette.secondary.main }}
            >
              <HelpOutlineIcon />
            </Tooltip>
          </Stack>
          <FormSwitch name={name} />
        </Stack>
      }
      accordionProps={{
        sx: {
          '&:before': {
            display: 'none',
          },
          '& .MuiAccordionSummary-expandIconWrapper': {
            display: 'none',
          },
          '& .MuiCollapse-root': {
            maxHeight: '260px',
            overflow: 'scroll',
          },
        },
        expanded,
      }}
    >
      {children}
    </AdvancedFilterAccordion>
  );
};

export default AdvanceReportFilters;
