import * as React from 'react';
import * as classNames from 'classnames';
import {HTMLProps, SFC} from 'react';
import {compose, defaultProps, setDisplayName, withHandlers, withStateHandlers} from 'recompose';
import {Button, Icon, Img, ImgModal, Modal, ModalBody, ModalFooter} from './';
import {Image} from './models';

export interface ImageThumbnailState {
  modalOpen: boolean;
}

export interface ImageThumbnailInternalProps extends ImageThumbnailExternalProps, Partial<ImageThumbnailState> {
  toggleModal?: () => ImageThumbnailState;
  handleRemoveButtonClick?: () => void;
}

export interface ImageThumbnailExternalProps extends HTMLProps<HTMLDivElement> {
  image: Image;
  imageAlt?: string;
  imageClassName?: string;
  noModal?: boolean;
  noRemoveButton?: boolean;
  onClickRemoveButton?: (image: Image) => void;
}

const enhance = compose<ImageThumbnailInternalProps, {}>(
  setDisplayName('ImgThumbnail'),
  defaultProps<Partial<ImageThumbnailInternalProps>>({
    imageAlt: '',
    imageClassName: '',
    noModal: false,
    noRemoveButton: false,
    toggleModal: () => { return null; },
    onClickRemoveButton: () => { return null; },
  }),
  withStateHandlers(
    {modalOpen: false},
    {toggleModal: ({modalOpen}) => () => ({modalOpen: !modalOpen})},
  ),
  withHandlers({
    handleRemoveButtonClick: (props: ImageThumbnailInternalProps) => () => {
      props.onClickRemoveButton(props.image);
    },
  }),
);

export const ImgThumbnail: SFC<ImageThumbnailInternalProps> = enhance(({
  className,
  image,
  imageClassName,
  imageAlt,
  modalOpen,
  noModal,
  noRemoveButton,
  handleRemoveButtonClick,
  toggleModal,
  onClickRemoveButton,
  onLoad,
  onError,
  ...otherProps}) => {

  const anchorProps = noModal ? {} : {
    ...otherProps,
    href: 'javascript:void(0)',
    onClick: toggleModal,
  };

  return (
    <a className={classNames('img-thumbnail', {[className]: className} as any)} {...anchorProps}>
      <Img
        className={classNames({[imageClassName]: imageClassName} as any)}
        src={image.url}
        alt={imageAlt}
        onError={onError as any}
        onLoad={onLoad as any}
      />

      {!noRemoveButton && (
        <Button
          className="btn-icon"
          color="danger"
          size="sm"
          onClick={handleRemoveButtonClick}
        >
          <Icon name="delete" />
        </Button>
      )}

      <ImgModal
        src={image.url}
        alt={image.url}
        toggleModal={toggleModal}
        modalOpen={modalOpen}
      />
    </a>
  );
}) as any;
