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

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

import { replaceTagsAction } from '../../redux/slices';

import useGetSelectedVideo from '@/modules/editorial/bulkActions/hooks/useGetSelectedVideo';
import TagsItem from './components/TagsItem/TagsItem';
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, Stack } from '@/mui/components';

const CONFIRM_DELETE = 'CONFIRM_DELETE';
const CONFIRM_REPLACE = 'CONFIRM_REPLACE';

// now find has only one tag type ( keywords or labels or iab )
function getAllowedTagCategoryForReplace(findTags) {
  const { keywords = [], labels = [], iab = [] } = findTags || {};
  const category = {
    excludeSystemTagsCategory: [TAG_SYSTEM_CATEGORY_TEXT, TAG_SYSTEM_CATEGORY_KEYWORDS],
    shouldExcludeAllCustomTags: false,
  };

  if (keywords.length || labels.length) {
    category.excludeSystemTagsCategory = [
      TAG_SYSTEM_CATEGORY_IAB,
      TAG_SYSTEM_CATEGORY_TEXT,
      TAG_SYSTEM_CATEGORY_KEYWORDS,
    ];
    category.shouldExcludeAllCustomTags = false;
  } else if (iab.length) {
    category.excludeSystemTagsCategory = [
      TAG_SYSTEM_CATEGORY_PEOPLE,
      TAG_SYSTEM_CATEGORY_BRANDS,
      TAG_SYSTEM_CATEGORY_BRAND_SAFETY,
      TAG_SYSTEM_CATEGORY_TEXT,
      TAG_SYSTEM_CATEGORY_KEYWORDS,
    ];
    category.shouldExcludeAllCustomTags = true;
  }

  return category;
}

function BulkActionAddTags(props) {
  const dispatch = useDispatch();
  const [tags, setTags] = useState({ find: null, replace: null });
  const [confirmType, setConfirmType] = useState(null);

  const selectedVideo = useGetSelectedVideo();

  const CONFIRM_CONTENT = {
    [CONFIRM_DELETE]: {
      title: 'Delete Tags',
      body: `Are you sure you want to delete tags on ${selectedVideo} selected videos?`,
      action: 'Delete All',
      btnColor: 'error',
    },
    [CONFIRM_REPLACE]: {
      title: 'Replace Confirmation',
      body: `Are you sure you want to replace tags on ${selectedVideo} videos?`,
      action: 'Replace All',
      btnColor: 'primary',
    },
  };

  const shouldDisabledAddButton = !(tags.find?.keywords?.length || tags.find?.iab?.length || tags.find?.labels.length);

  const { excludeSystemTagsCategory, shouldExcludeAllCustomTags } = getAllowedTagCategoryForReplace(tags.find);

  const handleSetTags = (tagsForSet, key) => setTags((prevState) => ({ ...prevState, [key]: tagsForSet }));

  const handleFindTags = (findTags) => handleSetTags(findTags, 'find');
  const handleReplaceTags = (replaceTags) => handleSetTags(replaceTags, 'replace');

  const handleShowConfirm = () => {
    const isDeleteMode = !(tags.replace?.keywords?.length || tags.replace?.iab?.length || tags.replace?.labels.length);
    setConfirmType(isDeleteMode ? CONFIRM_DELETE : CONFIRM_REPLACE);
  };

  const handleProcessTag = () => {
    dispatch(replaceTagsAction(tags));
    props.onClose();
  };

  return (
    <>
      <Dialog open={props.open} onClose={props.onClose} maxWidth="lg">
        <DialogTitle onClose={props.onClose}>Replace Tags</DialogTitle>
        <DialogContent>
          <Stack spacing={3}>
            <TagsItem
              label="Find"
              tagsDialogTitle="Select Tags to Find"
              shouldSelectOnlyOneTag
              excludeSystemTagsCategory={[TAG_SYSTEM_CATEGORY_TEXT, TAG_SYSTEM_CATEGORY_KEYWORDS]}
              onTagsApply={handleFindTags}
            />
            <TagsItem
              label="Replace"
              tagsDialogTitle="Select Tags to Replace"
              hint="Leave empty to delete tags"
              excludeSystemTagsCategory={excludeSystemTagsCategory}
              shouldExcludeAllCustomTags={shouldExcludeAllCustomTags}
              onTagsApply={handleReplaceTags}
            />
          </Stack>
        </DialogContent>
        <DialogActions>
          <Button variant="text" color="primary" onClick={props.onClose}>
            Cancel
          </Button>
          <Button variant="contained" color="primary" onClick={handleShowConfirm} disabled={shouldDisabledAddButton}>
            Replace All
          </Button>
        </DialogActions>
      </Dialog>

      {confirmType && (
        <Dialog open={confirmType} onClose={() => setConfirmType(null)} maxWidth="md">
          <DialogTitle onClose={() => setConfirmType(null)}>{CONFIRM_CONTENT[confirmType].title}</DialogTitle>
          <DialogContent>{CONFIRM_CONTENT[confirmType].body}</DialogContent>
          <DialogActions>
            <Button variant="outlined" color="primary" onClick={() => setConfirmType(null)}>
              Cancel
            </Button>
            <Button variant="contained" color={CONFIRM_CONTENT[confirmType].btnColor} onClick={handleProcessTag}>
              {CONFIRM_CONTENT[confirmType].action}
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </>
  );
}

BulkActionAddTags.propTypes = {
  open: PropTypes.bool.isRequired,
  onClose: PropTypes.func.isRequired,
};

export default BulkActionAddTags;
