import React, { useState } from 'react';
import PropTypes from 'prop-types';

import { CustomTagsPropType } from '../../../constants/propTypes';

import { extractCustomTagsCategories, normalizeCustomTags } from '../../../helpers';

import EmptyTag from '../EmptyTag';
import { CategoriesSlot, Layout, TagsSlot } from '../Layout';
import EditCategory from './components/EditCategory';
import EditTag from './components/EditTag';
import { Chip } from '@/mui/components';
import { CustomLabelTagCircular } from '@/mui/components/CustomIcon';

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

const EDIT_MODE_TAG = 'editModeTag';
const EDIT_MODE_CATEGORY = 'editModeCategory';

function CustomTags(props) {
  const [edit, setEdit] = useState({
    anchor: null,
    entity: null,
    editMode: null,
  });

  const categories = extractCustomTagsCategories(props.tags);
  const tags = normalizeCustomTags(categories, props.tags);

  const categoriesRef = categories.map(() => React.createRef());
  const tagsRef = tags.map(() => React.createRef());

  // tag edit handlers
  const handleOpenEditor = (editMode, entity, ref) => {
    setEdit({
      anchor: ref.current,
      entity,
      editMode,
    });
  };

  const handleCloseEditor = () => {
    setEdit({
      anchor: null,
      entity: null,
      editMode: null,
    });
  };

  return (
    <Layout>
      <CategoriesSlot title="Custom" titleTooltipText="User defined tag categories">
        {categories.map((tag, index) => (
          <div key={tag.id} className={styles.ChipItem} title={tag.label}>
            <Chip
              ref={categoriesRef[index]}
              size="small"
              color={tag.color}
              shape="circular"
              label={tag.label}
              variant="text"
              icon={<CustomLabelTagCircular />}
              onApply={
                props.onEditCategory ? () => handleOpenEditor(EDIT_MODE_CATEGORY, tag, categoriesRef[index]) : null
              }
            />
          </div>
        ))}
      </CategoriesSlot>
      <TagsSlot>
        <>
          {!tags?.length && <EmptyTag />}
          {tags.map((tag, index) => (
            <div key={`${tag.id}-${tag.label}`} className={styles.ChipItem} title={tag.label}>
              <Chip
                ref={tagsRef[index]}
                size="small"
                color={tag.color}
                shape="circular"
                label={tag.label}
                variant="outlined"
                onCancel={props.onDelete ? () => props.onDelete(tag) : null}
                onApply={props.onEditTag ? () => handleOpenEditor(EDIT_MODE_TAG, tag, tagsRef[index]) : null}
              />
            </div>
          ))}
        </>
      </TagsSlot>

      {edit.editMode === EDIT_MODE_TAG && (
        <EditTag
          isOpen={!!edit.anchor}
          anchorEl={edit.anchor}
          accountId={props.accountId}
          tag={edit.entity}
          tags={props.tags}
          onClose={handleCloseEditor}
          onEdit={props.onEditTag}
        />
      )}

      {edit.editMode === EDIT_MODE_CATEGORY && (
        <EditCategory
          isOpen={!!edit.anchor}
          anchorEl={edit.anchor}
          accountId={props.accountId}
          category={edit.entity}
          categories={categories}
          onClose={handleCloseEditor}
          onEdit={props.onEditCategory}
        />
      )}
    </Layout>
  );
}

CustomTags.propTypes = {
  tags: CustomTagsPropType.isRequired,
  accountId: PropTypes.number.isRequired,
  onDelete: PropTypes.func.isRequired,
  onEditCategory: PropTypes.oneOf([null, PropTypes.func]).isRequired,
  onEditTag: PropTypes.oneOf([null, PropTypes.func]).isRequired,
};

export default CustomTags;
