import React, { useState, useEffect, useRef } from 'react';
import cs from 'classnames';
import { mergeObject, getOssSrc } from '../utils';
import { SysModel } from '../utils/system';
import { getNodeStyle } from '../utils/style';
import useTrack from '../components/hooks/useTrack';
import { PREFIX_CLS } from '../config';
import JsCss, { plugin } from './jscss';
import Hocs from '../components/hocs';
import './style/index';

const prefixCls = `${PREFIX_CLS}-image`;
export default options => {
  const { terminal, data, dispatch, model, imageModel } = options;
  const { style, props, animation } = mergeObject(plugin, data);
  const { src, alt, link } = props;
  const { src: ossSrc } = getOssSrc({ terminal, src, style });
  const [imageStyle, setImageStyle] = useState({});
  const { ref } = useTrack(data);
  const imgRef = useRef();
  const [opacity, setOpacity] = useState(0);

  const updateRatio = ratio => {
    dispatch({
      type: 'tree/updateByKey',
      payload: {
        key: 'style.ratio',
        value: Math.round(ratio * 1000000) / 1000000,
        id: data.id,
        pid: data.pid,
        createHistory: false,
      },
    });
  };

  const show = () => {
    setOpacity(1);
    ref.current.style.background = 'transparent';
  };

  const hide = () => {
    setOpacity(0);
  };

  const handleImageStyle = imgDom => {
    const { naturalHeight, naturalWidth } = imgDom;
    const wrapper = imgDom.parentNode;
    const wrapperWidth = wrapper.clientWidth;
    const wrapperHeight = wrapper.clientHeight;
    if (naturalWidth / naturalHeight > wrapperWidth / wrapperHeight) {
      setImageStyle({ width: 'auto', height: '100%', maxWidth: 'none' });
    } else {
      setImageStyle({ width: '100%', height: 'auto' });
    }
  };

  const onload = e => {
    if (model === SysModel.DEV) {
      const { naturalHeight, naturalWidth } = e.currentTarget;
      updateRatio(naturalHeight / naturalWidth);
    }
    if (imageModel === 'aspectFill') {
      if (imgRef.current) {
        handleImageStyle(imgRef.current);
      }
    }
    show();
  };

  useEffect(() => {
    if (imgRef.current.complete) {
      if (imageModel === 'aspectFill') {
        if (imgRef.current) {
          handleImageStyle(imgRef.current);
        }
      }
      show();
    }
  }, []);

  useEffect(() => {
    hide();
    if (imgRef.current.complete) {
      show();
    }
  }, [ossSrc]);

  const modelClassName = imageModel ? `${prefixCls}--${imageModel}` : '';

  return (
    <Hocs
      link={link}
      animation={animation}
      width={style.width}
      height={style.height}
    >
      <JsCss
        ref={ref}
        className={cs(`${prefixCls}`, modelClassName)}
        style={getNodeStyle(style)}
        styles={style}
      >
        <div
          className={`${prefixCls}__wrapper`}
          style={{ paddingBottom: `${style.ratio * 100}%` }}
        >
          <img
            ref={imgRef}
            style={{ opacity, ...imageStyle }}
            src={ossSrc}
            onLoad={onload}
            alt={alt}
          />
        </div>
      </JsCss>
    </Hocs>
  );
};
