import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'clsx';

import { Accordion, AccordionDetails, AccordionSummary, Checkbox, Typography } from '@/mui/components';

import styles from './MetricItem.module.scss';

function MetricItem(props) {
  const subMetricValues = props.values?.map((value) => value.value);
  const amountChecked = props.checkedMetrics.filter((item) => subMetricValues?.includes(item)) ?? [];

  const handleMetricItemChange = () => {
    if (amountChecked?.length === subMetricValues?.length) {
      props.setField({
        checkedMetrics: props.checkedMetrics.filter((item) => !subMetricValues.includes(item)),
      });
    } else {
      props.setField({
        checkedMetrics: [...new Set([...props.checkedMetrics, ...subMetricValues])],
      });

      // when select some metric (Ad Requesrs) needs to select some dimensions
      if (props.selectWithDimensions?.length) {
        props.selectWithDimensions.forEach((item) => {
          props.checkDimension(item);
        });
      }
    }
  };

  const handleSubMetricItemChange = (value) => {
    const isValueChecked = props.checkedMetrics?.includes(value);
    if (isValueChecked) {
      props.setField({
        checkedMetrics: props.checkedMetrics.filter((item) => item !== value),
      });
    } else {
      props.setField({
        checkedMetrics: [...props.checkedMetrics, value],
      });
    }
  };

  return (
    <div className={styles.MetricItem}>
      <Accordion
        classes={{
          root: styles.Accordion,
        }}
        expanded={props.values?.length > 1 ? props.expanded : false}
        onChange={(event) => {
          if (event.target.id !== 'metric-checkbox') {
            props.onChangeAccordion(props.id);
          }
        }}
        disabled={props.disabled}
      >
        <AccordionSummary
          classes={{
            root: styles.AccordionSummary,
            disabled: styles.AccordionSummary___disabled,
          }}
          {...(props.values?.length > 1 ? {} : { expandIcon: null })}
        >
          <div className={styles.MetricItemMain}>
            <div>
              <Checkbox
                id="metric-checkbox"
                color="primary"
                size="xSmall"
                checked={amountChecked?.length === subMetricValues?.length}
                indeterminate={amountChecked?.length > 0 && amountChecked?.length < subMetricValues?.length}
                onChange={handleMetricItemChange}
                disabled={props.disabled}
              />

              <Typography className={styles.Label} variant="caption" color="text.primary" fontWeight={600}>
                {props.label}
              </Typography>
            </div>

            {props.values?.length > 1 && (
              <Typography variant="captionSmall" color="text.secondary" fontWeight={400}>
                {`${amountChecked?.length}/${props.values?.length}`}
              </Typography>
            )}
          </div>
        </AccordionSummary>
        <AccordionDetails
          classes={{
            root: classNames(styles.AccordionDetails, {
              [styles.AccordionDetails___disabled]: props.disabled,
            }),
          }}
        >
          {props.values.map((item, index) => (
            <div className={styles.SubMetricItem} key={`${+index}-${item.value}`}>
              <Checkbox
                id="metric-checkbox"
                color="primary"
                size="xSmall"
                checked={props.checkedMetrics?.includes(item.value)}
                onChange={() => {
                  handleSubMetricItemChange(item.value);
                }}
                disabled={props.disabled}
              />

              <Typography className={styles.Label} variant="caption" color="text.primary" fontWeight={400}>
                {item.label}
              </Typography>
            </div>
          ))}
        </AccordionDetails>
      </Accordion>
    </div>
  );
}

MetricItem.propTypes = {
  id: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  expanded: PropTypes.bool.isRequired,
  values: PropTypes.arrayOf(
    PropTypes.shape({
      label: PropTypes.string.isRequired,
      value: PropTypes.string.isRequired,
      tooltip: PropTypes.string.isRequired,
    }),
  ).isRequired,
  checkedMetrics: PropTypes.arrayOf(PropTypes.string).isRequired,
  selectWithDimensions: PropTypes.arrayOf(PropTypes.string).isRequired,
  onChangeAccordion: PropTypes.func.isRequired,
  setField: PropTypes.func.isRequired,
  disabled: PropTypes.bool.isRequired,
  checkDimension: PropTypes.func.isRequired,
};

export default MetricItem;
