import React from 'react';
import { string, shape, func } from 'prop-types';
import styled from 'styled-components';
import {
  REM_UNIT_XSM,
  REM_UNIT_MD,
  REM_UNIT_LG,
  REM_FONT_SIZE__SM,
  REM_FONT_SIZE_SM,
  FONT_BOLD,
  EERIE_BLACK,
  ARSENIC,
  SONIC_SILVER,
  GRAY_X11,
  GAINSBORO,
  VERY_LIGHT_TANGELO,
} from '@vincent_za/styles';

const Wrap = styled.div`
  display: flex;
  margin-bottom: ${REM_UNIT_LG};
  background-color: ${ARSENIC};
  padding: ${REM_UNIT_MD} 1.4rem ${REM_UNIT_MD} 2rem;
  align-items: center;
  border-radius: 1px;
  text-transform: uppercase;
  color: ${VERY_LIGHT_TANGELO};
  font-size: ${REM_FONT_SIZE__SM};
  font-family: ${FONT_BOLD};
  box-shadow: 0 0.6rem 1.1rem -0.4rem ${EERIE_BLACK}, 0 0 1.6rem -2px ${EERIE_BLACK};
`;

const Action = styled.div`
  text-transform: uppercase;
  cursor: pointer;
  color: ${GRAY_X11};
  font-size: ${REM_FONT_SIZE_SM};
  padding: ${REM_UNIT_XSM} 0.6rem;

  &:hover {
    color: ${GAINSBORO};
  };
`;

const TimeRemaining = styled.span`
  margin-right: 2rem;
  margin-left: 0.6rem;
  color: ${SONIC_SILVER};
`;

class Undo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      intervalId: undefined,
      secondsRemaining: 5,
    };
  }

  componentDidMount() {
    this.setState({ intervalId: setInterval(() => this.countDown(), 1000) });
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (nextState.intervalId !== this.state.intervalId) return true;
    if (nextState.secondsRemaining !== this.state.secondsRemaining) return true;
    if (nextProps.details !== this.props.details) return true;
    return false;
  }

  onRemove = () => {
    clearInterval(this.state.intervalId);
    this.props.onRemove({ id: this.props.details.id });
  }

  onUndo = () => {
    const { details: { undoCall, params }, onUndo } = this.props;
    this.onRemove();
    onUndo({ undoCall, params });
  }

  countDown = () => {
    const { secondsRemaining } = this.state;

    if (secondsRemaining) {
      this.setState({ secondsRemaining: secondsRemaining - 1 });
    }

    if (!secondsRemaining) {
      clearInterval(this.state.intervalId);
      this.props.onRemove({ id: this.props.details.id });
    }
  }

  render() {
    const { secondsRemaining } = this.state;
    const { details: { title } } = this.props;

    return (
      <Wrap>
        {title}
        <TimeRemaining>{secondsRemaining}</TimeRemaining>
        <Action onClick={this.onRemove}>Cancel</Action>
        <Action onClick={this.onUndo}>Undo</Action>
      </Wrap>
    );
  }
}

Undo.propTypes = {
  details: shape({
    id: string.isRequired,
    title: string.isRequired,
  }).isRequired,
  onUndo: func.isRequired,
  onRemove: func.isRequired,
};

export default Undo;
