import React, { useEffect, useState } from 'react';
import styles from '@/pages/scene/style/cover.module.less';
import { Image, Modal, List } from '@arco-design/web-react';
import { getImageUrl, imageList } from '@/utils/pubUse';

interface CoverProps {
  defaultImage?: string;
  onImageChange?: (image: string) => void;
}

const Cover: React.FC<CoverProps> = ({ defaultImage, onImageChange }) => {
  const [visible, setVisible] = useState(false);
  const [currentImage, setCurrentImage] = useState('');

  useEffect(() => {
    if (defaultImage) {
      setCurrentImage(getImageUrl(defaultImage));
    }
    else {
      const imageKey = Math.floor(Math.random() * Object.keys(imageList).length);
      const imageRandom = Object.keys(imageList)[imageKey];
      setCurrentImage(imageList[imageRandom]);
      onImageChange(imageList[imageRandom]);
    }
  }, [defaultImage]);

  const handleImageSelect = (imageSrc: string) => {
    setCurrentImage(imageSrc);
    setVisible(false);
    if (onImageChange) {
      onImageChange(imageSrc);
    }
  };

  return (
    <div className={styles['cover-container']}>
      <div className={styles['cover-image']}>
        <Image width={200} src={currentImage} preview={false} onClick={() => setVisible(true)}></Image>
      </div>
      <Modal
        style={{ width: '60%' }}
        title="选择封面图"
        visible={visible}
        onOk={() => setVisible(false)}
        onCancel={() => setVisible(false)}
        autoFocus={false}
        focusLock={true}
      >
        <List
          grid={{ gutter: 0, span: 6 }}
          size="small"
          render={(item, index) => {
            return (
              <List.Item key={index}>
                <Image width={200} src={item.src} preview={false} onClick={() => {
                  handleImageSelect(item.src);
                }}></Image>
              </List.Item>
            );
          }}
        />

      </Modal>
    </div>
  );
};

export default Cover;