import React, { useState, useEffect } from 'react';
import classNames from 'classnames/bind';

import styles from './NFTCard.scss';
import { Link } from 'react-router-dom';
import CircleThumb from '@src/components/common/CircleThumb';
import DateUtil from '@src/utils/DateUtil';
import ListMenu from './ListMenu';
import { ECurrencyType, ESaleStatus, ESaleType } from '@src/constants/Enums';
import URLInfo from '@src/constants/URLInfo';
import Like from './Like';
import Img from './Img';
import { host } from '@src/constants/NodeEnv';
import FileUtil from '@src/utils/FileUtil';

const cx = classNames.bind(styles);

interface IOwnProps {
  className?: string;
  saleId: number;
  content_title: string;
  endTime: string;
  collectionName: string;
  collectionThumb: string;
  authorThumb: string;
  authorName: string;
  thumbURL: string;
  price: number;
  saleType: ESaleType;
  currency: ECurrencyType;
  totalCount: number;
  tokenId: number;
  likeCount: number;
  isLike: boolean;
  startPrice: number;
  userId: number;
  itemIndex: number;
  handleDisLike?: (id: number) => void;
  fixedPrice: number;
  status: ESaleStatus;
  lastestPrice: number;
  lastestCurrency: ECurrencyType;
};

const NFTCard: React.FC<IOwnProps> = ({
  className,
  saleId,
  content_title,
  endTime,
  collectionThumb,
  collectionName,
  authorThumb,
  authorName,
  thumbURL,
  price,
  currency,
  totalCount,
  tokenId,
  likeCount,
  isLike,
  saleType,
  startPrice,
  userId,
  itemIndex,
  handleDisLike,
  fixedPrice,
  status,
  lastestPrice,
  lastestCurrency
}) => {
  let _currency = '';
  let _latestCurrency = '';

  if (currency === 'mr') {
    _currency = 'MTRA';
  }
  if (currency === 'mf') {
    _currency = 'MF1';
  }
  if (currency === 'eth') {
    _currency = 'ETH';
  }
  if (lastestCurrency === 'mr') {
    _latestCurrency = 'MTRA';
  }
  if (lastestCurrency === 'mf') {
    _latestCurrency = 'MF1';
  }
  if (lastestCurrency === 'eth') {
    _latestCurrency = 'ETH';
  }

  const [timeText, setTimeText] = useState<string>('');

  useEffect(() => {
    let id: NodeJS.Timeout | null = null;
    if (endTime) {
      id = DateUtil.countDownTimer(DateUtil.getTimezoneToDate(endTime), setTimeText).id;
    }

    return () => {
      if (id) {
        clearInterval(id);
      }
    };
  }, [endTime]);

  const menuList = [
    {
      title: 'Refresh Metadata',
      onClick: () => { },
      isDisabled: true
    },
    {
      title: '신고하기',
      onClick: () => { },
      isDisabled: true
    },
    // {
    //   title: '공유하기',
    //   onClick: () => {
    //     const url = status === ESaleStatus.ON_GOING ? `${host}/sale/${saleId}` : `${host}/token/${tokenId}`;
    //     navigator.clipboard.writeText(url).then(() => {
    //       alert('복사되었습니다.');
    //     });
    //   },
    //   isDisabled: false
    // },
  ];
  const isMulti = totalCount > 1;
  const isEnd = status !== ESaleStatus.ON_GOING;

  return (
    <div className={cx("nft_card", isMulti && "multi", className)}>
      <div className={cx("card_wrap")}>
        <Link
          to={isEnd ? URLInfo.getTokenUrl(tokenId) : URLInfo.getSaleUrl(saleId)}
          className={cx("contents_group")}
        >
          <div className={cx("thumb_area")}>
            {FileUtil.isVideo(thumbURL) ? (
              <video
                src={thumbURL}
                width="260"
                height="260"
                className={cx("thumb")}
                autoPlay
                muted
                playsInline
                loop
                preload="metadata"
              />
            ) : (
              <Img
                src={thumbURL}
                alt=""
                width="260"
                height="260"
                className={cx("thumb")}
              />
            )}
            {saleType === ESaleType.TIME &&
              (timeText === "00:00:00" ? (
                <div className={cx("label")}>⌛️ 00:00:00</div>
              ) : (
                <>
                  {timeText && <div className={cx("label")}>🔥 {timeText}</div>}
                </>
              ))}
          </div>
          <div className={cx("info_area")}>
            <div className={cx("collection_name_box")}>
              <div className={cx("collection_name")}>{collectionName}</div>
              <div className={cx("like")}>
                <Like
                  token_id={tokenId}
                  likeCnt={likeCount}
                  isLike={isLike}
                  handleDisLike={handleDisLike}
                />
              </div>
            </div>
            <div className={cx("description_box")}>{content_title}</div>
            <div className={cx("price_box")}>
              <div className={cx("price_inner")}>
                {saleType === ESaleType.FIXED && (
                  <span className={cx("price")}>
                    {isEnd ? (
                      <>
                        {lastestPrice ? (
                          <>
                            {Number(lastestPrice)} {_latestCurrency}
                          </>
                        ) : (
                          "판매이력 없음"
                        )}
                      </>
                    ) : (
                      <>
                        {Number(fixedPrice)} {_currency}
                      </>
                    )}
                  </span>
                )}
                {saleType === ESaleType.AUCTION && (
                  <>
                    {isEnd ? (
                      <>{lastestPrice ? "판매 완료" : "판매이력 없음"}</>
                    ) : (
                      <>
                        {price ? (
                          <span className={cx("price")}>현재 최고 입찰가</span>
                        ) : (
                          <span className={cx("price")}>현재 경매중</span>
                        )}
                      </>
                    )}
                  </>
                )}
                {saleType === ESaleType.TIME && (
                  <>
                    {isEnd ? (
                      <>{lastestPrice ? "판매 완료" : "판매이력 없음"}</>
                    ) : (
                      <>
                        {price ? (
                          <span className={cx("price")}>최고입찰가</span>
                        ) : (
                          <span className={cx("price")}>시작입찰가</span>
                        )}
                      </>
                    )}
                  </>
                )}
                <span className={cx("type")}>
                  {itemIndex ? itemIndex : 1}/{totalCount ? totalCount : 1}
                </span>
              </div>
              {saleType === ESaleType.FIXED && (
                <div className={cx("bid")}>
                  {isEnd ? <>{lastestPrice && "판매완료"}</> : "즉시 구매"}
                </div>
              )}
              {saleType === ESaleType.AUCTION && (
                <>
                  {isEnd ? (
                    lastestPrice && (
                      <div className={cx("bid")}>
                        Bid {Number(lastestPrice)} {_latestCurrency}
                      </div>
                    )
                  ) : (
                    <>
                      {price ? (
                        <div className={cx("bid")}>
                          Bid {Number(price)} {_currency}
                        </div>
                      ) : (
                        <div className={cx("bid")}>입찰하기</div>
                      )}
                    </>
                  )}
                </>
              )}
              {(price || lastestPrice || startPrice) && (
                <>
                  {saleType === ESaleType.TIME && (
                    <>
                      {isEnd ? (
                        lastestPrice && (
                          <div className={cx("bid")}>
                            Bid {Number(lastestPrice)} {_latestCurrency}
                          </div>
                        )
                      ) : (
                        <>
                          {price ? (
                            <div className={cx("bid")}>
                              Bid {Number(price)} {_currency}
                            </div>
                          ) : (
                            <div className={cx("bid")}>
                              Bid {Number(startPrice)} {_currency}
                            </div>
                          )}
                        </>
                      )}
                    </>
                  )}
                </>
              )}
            </div>
          </div>
        </Link>
      </div>
    </div>
  );
};

export default NFTCard;
