/* eslint-disable @typescript-eslint/ban-ts-comment */
import React, { createRef, useEffect, useMemo, useRef } from 'react';
import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.css';
import { expandObj } from 'src/types';

import './index.scss';

interface PreviewImageI {
  data?: string | string[];
  options?: expandObj;
  numPerLine?: number;
  padding?: number;
  viewRef?: React.RefObject<Viewer>;
  itemStyle: expandObj;
  imageStyle: expandObj;
}

const isNeedPadding = (index: number, numPerLine: number) => {
  return index % numPerLine !== numPerLine - 1;
};

export default function PreviewImage(props: PreviewImageI) {
  const {
    data,
    options = {},
    numPerLine = 1,
    padding = 1,
    viewRef,
    itemStyle,
    imageStyle,
  } = props;

  const imageRef = createRef();
  const viewer = viewRef || createRef<Viewer>();
  useEffect(() => {
    if (imageRef.current) {
      // @ts-ignore
      viewer.current = new Viewer(imageRef.current as HTMLElement, options);
    }
  }, []);

  const images = useMemo(() => {
    return Array.isArray(data) ? data : [data ?? ''];
  }, [data]);

  return (
    // @ts-ignore
    <ul className='op-preivew-image' ref={imageRef}>
      {(images || []).map((item, index) => (
        <li
          style={{
            width: `calc((100% - ${
              (numPerLine - 1) * padding
            }px) / ${numPerLine})`,
            marginRight: isNeedPadding(index, numPerLine) ? padding : 0,
            ...(itemStyle || {}),
          }}
        >
          <img
            src={item}
            alt='图片'
            className='op-preivew-image__img'
            style={{
              cursor: 'pointer',
              ...(imageStyle || {}),
            }}
          />
        </li>
      ))}
    </ul>
  );
}
