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

import { CATEGORY_SIZE } from '../../../../../constants';

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

import CategoryColors from '../../../../CategoryColors';
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Grid,
  InputAdornment,
  Popover,
  TextField,
} from '@/mui/components';
import { CustomLabelTag } from '@/mui/components/CustomIcon';

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

function EditCategory(props) {
  const dispatch = useDispatch();
  const [showConfirm, setShowConfirm] = useState(false);
  const [color, setColor] = useState(props.category.color);
  const [name, setName] = useState(props.category.label);

  const isValuesIsSame = color === props.category.color && name.trim() === props.category.label.trim();
  const isDisableSaveButton = !name.length || isValuesIsSame;

  const handleEditCategory = (selectedColor, selectedName) => {
    dispatch(
      editCustomCategoryAction({
        id: props.category.id,
        color: selectedColor,
        name: selectedName,
        callbackAfterCreate(updatedCategory) {
          props.onEdit(updatedCategory);
          props.onClose();
        },
      }),
    );
  };

  const handleConfirmOpen = () => setShowConfirm(true);
  const handleConfirmClose = () => setShowConfirm(false);
  const handleConfirmApply = () => {
    handleEditCategory(color, name);
    handleConfirmClose();
  };

  const handleSaveCategory = () => {
    if (props.category.label.trim() !== name.trim()) {
      handleConfirmOpen();
    } else {
      handleEditCategory(color, name);
    }
  };

  return (
    <Popover
      open={props.isOpen}
      anchorEl={props.anchorEl}
      onClose={props.onClose}
      PaperProps={{
        classes: {
          root: styles.PopoverPaper,
        },
      }}
      anchorOrigin={{
        vertical: 'top',
        horizontal: 'left',
      }}
      transformOrigin={{
        vertical: 'top',
        horizontal: 'left',
      }}
    >
      <Grid container direction="column">
        <Grid item className={styles.InputWrapper}>
          <TextField
            variant="outlined"
            size="small"
            shape="rounded"
            placeholder="Edit category"
            value={name}
            inputProps={{
              maxLength: CATEGORY_SIZE,
            }}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <CustomLabelTag />
                </InputAdornment>
              ),
            }}
            onChange={({ target }) => setName(target.value)}
          />
        </Grid>
        <Grid item>
          <CategoryColors
            selectedColor={color}
            onChange={(value) => {
              setColor(value);
            }}
          />
        </Grid>
        <Grid item className={styles.EditButtonWrapper}>
          <Button
            fullWidth
            disabled={isDisableSaveButton}
            label="Save Category"
            variant="outlined"
            size="small"
            color="primary"
            shape="rounded"
            onClick={handleSaveCategory}
          >
            Save Category
          </Button>
        </Grid>
      </Grid>

      {showConfirm && (
        <Dialog open={showConfirm} onClose={handleConfirmClose} maxWidth="md">
          <DialogTitle onClose={handleConfirmClose}>Warning</DialogTitle>
          <DialogContent>
            <p>Changing the category name will only affect video category attribution in the Studio.</p>
            <p>
              Existing filters and settings in the Watch, Player, Forms and X-Rays will still be using the same category
              name as before.
            </p>
          </DialogContent>
          <DialogActions>
            <Button size="small" variant="outlined" color="primary" onClick={handleConfirmClose}>
              Cancel
            </Button>
            <Button size="small" variant="contained" color="primary" onClick={handleConfirmApply}>
              Confirm
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </Popover>
  );
}

EditCategory.propTypes = {
  // form props
  isOpen: PropTypes.bool.isRequired,
  anchorEl: PropTypes.node.isRequired,
  category: PropTypes.shape({
    id: PropTypes.string,
    label: PropTypes.string,
    color: PropTypes.string,
  }).isRequired,
  onEdit: PropTypes.oneOf([null, PropTypes.func]).isRequired,
  onClose: PropTypes.func.isRequired,
};

export default EditCategory;
