import React, { memo, useState } from 'react';
import Thumb from 'components/Thumb';
import DeleteConfirmModal from 'components/DeleteConfirmModal/Modal';
import FavoriteModal from '../Favorite/FavoriteModal';
import defaultThumb from 'images/favorite_default.jpg';
import styles from './FavoriteItem.less';
import {getAssetsUrl} from 'utils/utils';

function FavoriteItem({ id, name, thumb, onAdd, onDelete, onUpdate }) {
  const [deleteVisible, setDeleteVisible] = useState(false);
  const [updateVisible, setUpdateVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleDelete = (e) => {
    e.stopPropagation();
    setDeleteVisible(true);
  };

  const handleUpdate = (e) => {
    e.stopPropagation();
    setUpdateVisible(true);
  };

  const handleDeleteCancel = () => {
    setDeleteVisible(false);
  };

  const handleUpdateCancel = () => {
    setUpdateVisible(false);
  };

  const handleDeleteOk = () => {
    onDelete(id);
  };

  const handleUpdateOk = async (values) => {
    setLoading(true);
    const result = await onUpdate({ ...values, id });
    setLoading(false);
    if (result) {
      setUpdateVisible(false);
    }
  };

  return (
    <li className={styles.container}>
      <div onClick={() => onAdd(id)}>
        <Thumb className={styles.img} src={thumb ? getAssetsUrl(thumb) : defaultThumb} />
        <p className={styles.name}>{name}</p>
      </div>

      <div className={styles.operate}>
        <i className="icon iconfont icon-icon_more" />
        <ul className={styles.list}>
          <li className={styles.item} onClick={handleUpdate}>
            编辑
          </li>
          <li className={styles.item} onClick={handleDelete}>
            删除
          </li>
        </ul>
      </div>

      <DeleteConfirmModal visible={deleteVisible} onClose={handleDeleteCancel} onOk={handleDeleteOk} />

      <FavoriteModal
        visible={updateVisible}
        confirmLoading={loading}
        name={name}
        thumb={thumb}
        onCancel={handleUpdateCancel}
        onOk={handleUpdateOk}
      />
    </li>
  );
}

export default memo(FavoriteItem);
