import React, { useEffect, useRef, useState } from 'react';
import classNames from 'classnames/bind';
import { ReactComponent as IconHeart } from '@assets/img/svg/ico_heart_gray.svg';
import { ReactComponent as IconFilledHeart } from '@assets/img/svg/ico_heart_red.svg';

import styles from './Like.scss';
import APIs from '@src/api/APIs';
import useLogin from '@src/hooks/useLogin';
import URLInfo from '@src/constants/URLInfo';
const cx = classNames.bind(styles);

interface IOwnProps {
  token_id: number;
  isLike: boolean;
  likeCnt: number;
  handleDisLike?: (id: number) => void;
}

let likeTimeoutId: NodeJS.Timeout;

const Like: React.FC<IOwnProps> = ({
  token_id,
  isLike,
  likeCnt,
  handleDisLike
}) => {
  const [selectedLike, setSelectedLike] = useState<boolean>(false);
  const [likeCount, setLikeCount] = useState<number>(0);
  const { checkLogin } = useLogin();
  const likeRef = useRef<HTMLButtonElement>(null);
  const pathname = window.location.pathname;

  useEffect(() => {
    setSelectedLike(isLike);
    setLikeCount(likeCnt);
  }, [isLike, likeCnt]);

  const handleClickLike = async () => {

    if (!URLInfo.isSalePage())  return;
    
    const likeEl = likeRef.current;

    if (!checkLogin() || !likeEl) {
      return;
    }

    if (selectedLike) {
      setSelectedLike(false);
      setLikeCount(likeCount - 1);

      if (likeEl.dataset.isClicked === 'true') {
        clearTimeout(likeTimeoutId);
      } else {
        await APIs.changeLike({ tokenId: token_id, isLike: false }).then(() => {
          handleDisLike?.(token_id);
        });
      }
    } else {
      setSelectedLike(true);
      setLikeCount(likeCount + 1);
      likeEl.dataset.isClicked = 'true';

      likeTimeoutId = setTimeout(() => {
        APIs.changeLike({ tokenId: token_id, isLike: true });
        likeEl.dataset.isClicked = 'false';
      }, 3000);
    }
  };
  return (
    <button type="button" className={cx('btn_like')} onClick={handleClickLike} ref={likeRef}>
      {selectedLike ? (
        <IconFilledHeart className={cx('ico_heart', 'fill')} />
      ) : (
        <IconHeart className={cx('ico_heart')} />
      )}
      <span className={cx('count')}>{likeCount}</span>
    </button>
  );
};

export default Like;
