import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import dayjs from 'dayjs';
import { Info } from '@mui/icons-material';

import {
  SYSTEM_TAGS_CATEGORY_OPTIONS,
  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 '../../../constants';

import { excludeCategoryBy, normalizeSystemTags } from '../../../helpers';
import { getInfoTooltipKey } from '@/modules/editorial/aiWorkbench/TagLog/helpers';

import EmptyTag from '../EmptyTag';
import { CategoriesSlot, Layout, TagsSlot } from '../Layout';
import { Chip, Stack, Tooltip } from '@/mui/components';
// import { useTheme } from '@mui/material/styles';
import {
  CustomBrandSafetyCircular,
  CustomBrandsCircular,
  CustomCcCircular,
  CustomIABCircular,
  CustomKeywordsCircular,
  CustomPeopleCircular,
  CustomTextCircular,
} from '@/mui/components/CustomIcon';

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

const systemTags = {
  [TAG_SYSTEM_CATEGORY_KEYWORDS]: {
    Icon: CustomKeywordsCircular,
    colorKey: '-tagKeywords',
  },
  [TAG_SYSTEM_CATEGORY_PEOPLE]: {
    Icon: CustomPeopleCircular,
    colorKey: '-tagPeople',
  },
  [TAG_SYSTEM_CATEGORY_BRANDS]: {
    Icon: CustomBrandsCircular,
    colorKey: '-tagBrands',
  },
  [TAG_SYSTEM_CATEGORY_IAB]: {
    Icon: CustomIABCircular,
    colorKey: '-tagIAB',
  },
  [TAG_SYSTEM_CATEGORY_BRAND_SAFETY]: {
    Icon: CustomBrandSafetyCircular,
    colorKey: '-tagBrandSafety',
  },
  [TAG_SYSTEM_CATEGORY_TEXT]: {
    Icon: CustomTextCircular,
    colorKey: '-tagText',
  },
  [TAG_SYSTEM_CATEGORY_CC]: {
    Icon: CustomCcCircular,
    colorKey: '-tagCC',
  },
};

function SystemTags(props) {
  // const theme = useTheme();
  const tags = normalizeSystemTags(props.tags);

  const getTooltipText = useCallback(
    (tag) => {
      if (!props.infoTooltip?.tagKeywords) {
        return '';
      }

      const { logRowUid } = props.infoTooltip.tagKeywords.find((t) => tag.id === t.id || tag.id === t.value) || {};
      const key = getInfoTooltipKey(props.infoTooltip?.context, tag.id, logRowUid);
      const tagInfoTooltip = props.infoTooltip?.data[key];
      if (!tagInfoTooltip) return '';

      if (!tagInfoTooltip.created && !tagInfoTooltip.versions?.length && !tagInfoTooltip.providers?.length) {
        return 'Tag information not found';
      }

      return (
        <Stack>
          {tag.id && tag.category !== TAG_SYSTEM_CATEGORY_TEXT && <Stack>{`Id: ${tag.id} `}</Stack>}

          {tagInfoTooltip.created && (
            <Stack>{`Created: ${dayjs(+tagInfoTooltip.created).format('MMM D, YYYY hh:mm A')}`}</Stack>
          )}

          {!!tagInfoTooltip.versions?.length && (
            <Stack>
              {`Type: ${tagInfoTooltip.versions
                .map((ver, index) => `${ver.version} (${ver.description})${index < tagInfoTooltip.length ? '/' : ''}`)
                .join(', ')}`}
            </Stack>
          )}

          {!!tagInfoTooltip.providers?.length && (
            <Stack>
              {`Models: ${tagInfoTooltip.providers
                .map((provider) =>
                  provider.models
                    .map((model) => `${provider.provider}/${model.value} (${(model.probability * 100).toFixed(0)}%)`)
                    .join(', '),
                )
                .join(', ')}`}
            </Stack>
          )}
        </Stack>
      );
    },
    [props.infoTooltip?.data],
  );

  return (
    <Layout>
      <CategoriesSlot title="System" titleTooltipText="System defined tag categories">
        {excludeCategoryBy(props.excludeTagsCategory, SYSTEM_TAGS_CATEGORY_OPTIONS).map((tag) => {
          const { Icon, colorKey } = systemTags[tag.value];

          return (
            <Chip
              key={tag.value}
              size="small"
              color={colorKey}
              shape="circular"
              label={tag.label}
              variant="text"
              icon={<Icon />}
            />
          );
        })}
      </CategoriesSlot>
      <TagsSlot>
        <>
          {!tags?.length && <EmptyTag />}
          {tags.map((tag, index) => {
            const key = `${tag.id}-${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 { colorKey } = systemTags[type];

            const tooltip = getTooltipText(tag);

            const ChipRender = (
              <Chip
                size="small"
                color={colorKey}
                shape="circular"
                label={tag.label}
                variant="filled"
                onCancel={props.onDelete ? () => props.onDelete(tag) : null}
                onApplyIcon={Info}
                onApply={props.infoTooltip?.action ? () => props.infoTooltip.action(tag) : null}
              />
            );

            return (
              <div key={key} className={styles.ChipItem} title={tag.label}>
                {tooltip && <Tooltip title={tooltip}>{ChipRender}</Tooltip>}
                {!tooltip && <>{ChipRender}</>}
              </div>
            );
          })}
        </>
      </TagsSlot>
    </Layout>
  );
}

SystemTags.propTypes = {
  infoTooltip: PropTypes.oneOf([
    null,
    PropTypes.shape({
      action: PropTypes.func,
      data: PropTypes.shape({}),
      context: PropTypes.string,
      tagKeywords: PropTypes.arrayOf(PropTypes.shape({})),
    }),
  ]),
  tags: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.string,
      type: PropTypes.string,
      text: PropTypes.string,
    }),
  ).isRequired,
  excludeTagsCategory: PropTypes.arrayOf(PropTypes.string).isRequired,
  onDelete: PropTypes.func.isRequired,
};

export default SystemTags;
