import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import classNames from 'clsx';
// import { useTheme } from '@mui/material/styles';
import { AddCircleOutlineRounded, EditOutlined, MoreHorizOutlined, RemoveRedEyeOutlined } from '@mui/icons-material';

import {
  TAG_SYSTEM_CATEGORY_BRAND_SAFETY,
  TAG_SYSTEM_CATEGORY_BRANDS,
  TAG_SYSTEM_CATEGORY_CC,
  TAG_SYSTEM_CATEGORY_IAB,
  TAG_SYSTEM_CATEGORY_KEYWORDS,
  TAG_SYSTEM_CATEGORY_PEOPLE,
  TAG_SYSTEM_CATEGORY_TEXT,
} from '@/modules/editorial/TagEditor/constants';

import { tagsGenerator } from '../../../../editorialVideoDetails/helpers';
import { extractCustomTagsCategories, normalizeCustomTags, normalizeSystemTags } from '../../../../TagEditor/helpers';

import { Button, Chip, Grid } from '@/mui/components';

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

const sizes = {
  small: 'small',
  wide: 'wide',
  wideXl: 'wideXl',
};

const types = {
  [TAG_SYSTEM_CATEGORY_KEYWORDS]: '-tagKeywords',
  [TAG_SYSTEM_CATEGORY_PEOPLE]: '-tagPeople',
  [TAG_SYSTEM_CATEGORY_BRANDS]: '-tagBrands',
  [TAG_SYSTEM_CATEGORY_IAB]: '-tagIAB',
  [TAG_SYSTEM_CATEGORY_BRAND_SAFETY]: '-tagBrandSafety',
  [TAG_SYSTEM_CATEGORY_TEXT]: '-tagText',
  [TAG_SYSTEM_CATEGORY_CC]: '-tagCC',
};

function Tags({ size = sizes.small, isEditable = false, searchFilters = {}, ...props }) {
  // const theme = useTheme();

  const [shouldShowMoreIcon, setShouldShowMoreIcon] = useState(false);
  const containerRef = useRef(null);

  const systemTags = normalizeSystemTags(tagsGenerator(props.video, searchFilters));
  const customTags = normalizeCustomTags(extractCustomTagsCategories(props.video.label || []), props.video.label || []);

  const systemTagsRef = systemTags.map(() => React.createRef());
  const customTagsRef = customTags.map(() => React.createRef());

  const isNoTags = !(systemTags.length || customTags.length);

  const getEditIcon = () => {
    switch (true) {
      case isEditable && isNoTags:
        return <AddCircleOutlineRounded />;
      case isEditable:
        return <EditOutlined />;
      default:
        return <RemoveRedEyeOutlined />;
    }
  };

  useEffect(() => {
    const compareWith =
      (containerReact) =>
      ({ current }) => {
        const tagRect = current?.getBoundingClientRect();
        return tagRect?.bottom > containerReact?.bottom;
      };

    const showMoreIcons = () => {
      const containerReact = containerRef.current.getBoundingClientRect();
      const isSystemTagOut = systemTagsRef.some(compareWith(containerReact));
      const isCustomTagOut = customTagsRef.some(compareWith(containerReact));

      setShouldShowMoreIcon(isSystemTagOut || isCustomTagOut);
    };

    showMoreIcons();

    window.addEventListener('resize', showMoreIcons);

    return () => window.removeEventListener('resize', showMoreIcons);
  }, [systemTagsRef, customTagsRef]);

  return (
    <Grid
      container
      justifyContent="space-between"
      className={classNames(styles.DetailTags, {
        [styles.DetailTags___wide]: size === sizes.wide,
        [styles.DetailTags___wideXl]: size === sizes.wideXl,
      })}
    >
      <Grid item className={styles.Tags} ref={containerRef}>
        {isNoTags && <Chip size="medium" color="neutral" variant="filled" shape="circular" label="No Tags Yet" />}

        {customTags.map((tag, index) => (
          <div key={`${tag.id}-${tag.label}`} title={`${tag.category}: ${tag.label}`} className={styles.TagItem}>
            <Chip
              ref={customTagsRef[index]}
              size="small"
              color={tag.color}
              shape="circular"
              label={tag.label}
              variant="outlined"
            />
          </div>
        ))}

        {systemTags.map((tag, index) => {
          // @todo remove tag.category === 'brandsafety' after implement video card tags
          // ref why its needs -> modules/editorial/editorialVideoDetails/helpers/index.js:120
          const type = tag.category === 'BRANDSAFETY' ? TAG_SYSTEM_CATEGORY_BRAND_SAFETY : tag.category;

          const key = `${tag.id}-${index}`;
          return (
            <div key={key} className={styles.TagItem} title={tag.label}>
              <Chip
                ref={systemTagsRef[index]}
                color={types[type]}
                size="small"
                shape="circular"
                label={tag.label}
                variant="filled"
              />
            </div>
          );
        })}
      </Grid>
      <Grid item className={styles.TagMoreIconPosition}>
        {shouldShowMoreIcon && (
          <MoreHorizOutlined htmlColor="info.main" fontSize="large" className={styles.TagMoreIcon} />
        )}
      </Grid>
      <Grid item className={styles.OpenTagEditorButtonPosition}>
        <Button
          className={styles.OpenTagEditorButton}
          variant="contained"
          size="medium"
          color="neutral"
          shape="rounded"
          label=""
          square
          disabled={props.disabled || (!isEditable && isNoTags)}
          startIcon={getEditIcon()}
          onClick={props.onClickEdit}
        />
      </Grid>
    </Grid>
  );
}

Tags.propTypes = {
  video: PropTypes.shape({
    label: PropTypes.arrayOf(
      PropTypes.shape({
        labelId: PropTypes.string,
        value: PropTypes.string,
        name: PropTypes.string,
        color: PropTypes.string,
      }),
    ),
  }).isRequired,
  searchFilters: PropTypes.shape({}),
  size: PropTypes.oneOf(Object.values(sizes)),
  isEditable: PropTypes.bool,
  disabled: PropTypes.bool,
  onClickEdit: PropTypes.func.isRequired,
};

export default Tags;
