import React, { useEffect, useState } from "react";
import classNames from "classnames/bind";
import styles from "./Sale.scss";
import CircleThumb from "@src/components/common/CircleThumb";
import ProfileDesc from "@src/components/common/ProfileDesc";
import SaleButtonContainer from "@src/components/common/sale/SaleButtonContainer";
import { ESaleStatus, ESaleType } from "@src/constants/Enums";
import SaleTab from "@src/components/common/sale/SaleTab";
import { useDispatch, useSelector } from "react-redux";
import { fetchSale } from "@src/store/reducers/SaleReducer";
import DateUtil, { IDateFormat } from "@src/utils/DateUtil";
import URLInfo from "@src/constants/URLInfo";
import Like from "@src/components/common/Like";
import { Link, useHistory } from "react-router-dom";
import { fetchToken } from "@src/store/reducers/TokenReducer";
import { ISaleDetail, ITokenDetail } from "metarare";
import Loading from "@src/components/common/Loading";
import FileUtil from "@src/utils/FileUtil";
import { ReactComponent as IconShare_2 } from "@assets/img/svg/ico_share_2.svg";
import useResize from "@src/hooks/useResize";

const cx = classNames.bind(styles);

const Sale: React.FC = () => {
  const { isMobileSize } = useResize();
  const dispatch = useDispatch();
  const history = useHistory();
  const { data: saleData, isDataLoaded: isSaleDataLoaded } = useSelector(
    (store) => store.sale
  );
  const { data: tokenData, isDataLoaded: isTokenDataLoaded } = useSelector(
    (store) => store.token
  );

  const pageId = URLInfo.getId();
  const data = URLInfo.isSalePage() ? saleData?.sale : tokenData?.token;

  // 남은 시간
  const [dateText, setDateText] = useState<IDateFormat>({
    d: 0,
    h: 0,
    m: 0,
    s: 0,
  });
  const [isEnd, setIsEnd] = useState<boolean>(false);
  const [countStart, setCountStart] = useState<boolean>(false);

  useEffect(() => {
    if (data && URLInfo.isSalePage()) {
      const { status, token_id, id } = data as ISaleDetail;
      const isEnd = status !== ESaleStatus.ON_GOING;

      if (pageId === id && isEnd) {
        if (token_id) {
          history.replace(URLInfo.getTokenUrl(token_id));
        } else {
          history.replace(URLInfo.ERROR);
        }
      }
    }
  }, [data]);

  useEffect(() => {
    if (URLInfo.isSalePage()) {
      dispatch(fetchSale(pageId));
    } else {
      dispatch(fetchToken(pageId));
    }
  }, [history.location.pathname, isEnd]);

  useEffect(() => {
    let id: NodeJS.Timeout | null = null;
    const endAt = (data as ISaleDetail)?.end_at;

    if (endAt) {
      id = DateUtil.countDownDayTimer(
        DateUtil.getTimezoneToDate(endAt),
        setDateText
      ).id;
    }

    return () => {
      if (id) {
        clearInterval(id);
      }
    };
  }, [(data as ISaleDetail)?.end_at]);

  useEffect(() => {
    if (data && (data as ISaleDetail).sale_type === ESaleType.TIME) {
      const isEnd =
        new Date(
          DateUtil.getTimezoneToDate((data as ISaleDetail).end_at)
        ).getTime() < new Date().getTime();
      setIsEnd(isEnd);

      const dateTextSum = Object.values(dateText).reduce((a, b) => a + b, 0);
      if (dateTextSum) {
        setCountStart(dateTextSum > 0);
      }
    }
  }, [dateText, data]);

  const currency = (data as ISaleDetail)?.currency?.toUpperCase();
  const saleType = (data as ISaleDetail)?.sale_type;
  const highestPrice = (data as ISaleDetail)?.highest_price;
  const price = (data as ISaleDetail)?.price;
  const myBiddingPrice = (data as ISaleDetail)?.my_bidding_price;
  let _currency = "";
  if (saleData?.sale.currency === "mr") {
    _currency = "MTRA";
  }
  if (saleData?.sale.currency === "mf") {
    _currency = "MF1";
  }
  if (saleData?.sale.currency === "eth") {
    _currency = "ETH";
  }

  const handleShare = () => {
    navigator.clipboard.writeText(window.location.href).then(() => {
      alert("복사되었습니다.");
    });
  };

  return (
    <div className={cx("detail_item")}>
      {isSaleDataLoaded && isTokenDataLoaded ? (
        <>
          {data && (
            <div className={cx("detail_wrap")}>
              <div className={cx("thumb_group")}>
                {FileUtil.isVideo(data.content_url) ? (
                  <video
                    className={cx("thumb")}
                    src={data.content_url}
                    width="100%"
                    height="auto"
                    autoPlay
                  />
                ) : (
                  <img
                    className={cx("thumb")}
                    src={data.content_url}
                    alt=""
                    width="100%"
                    height="auto"
                  />
                )}
              </div>
              <div className={cx("info_group")}>
                <div className={cx("header_box")}>
                  <Link
                    to={URLInfo.getProfileCollectionUrl(data.collection_name)}
                    className={cx("name")}
                  >
                    {data.collection_name}
                  </Link>
                  <div className={cx("group")}>
                    <div className={cx("like")}>
                      <Like
                        token_id={
                          URLInfo.isSalePage()
                            ? (data as ISaleDetail).token_id
                            : data.id
                        }
                        isLike={data.is_like}
                        likeCnt={data.like_count}
                      />
                    </div>
                    <div className={cx("share")} onClick={handleShare}>
                      <IconShare_2 />
                      공유하기
                    </div>
                  </div>
                </div>
                <div className={cx("detail_info")}>
                  <strong className={cx("title_area")}>{data.name}</strong>
                  <div className={cx("info_area")}>
                    <div className={cx("info_box")}>
                      <div className={cx("info")}>
                        {URLInfo.isSalePage() && (
                          <>
                            <span className={cx("market")}>
                              {saleType === ESaleType.FIXED && "💰 지정가"}
                              {saleType === ESaleType.AUCTION &&
                                (highestPrice
                                  ? "🚀 현재 최고입찰가"
                                  : "🚀 현재 경매중")}
                              {saleType === ESaleType.TIME &&
                                (highestPrice
                                  ? "🔥 현재 최고입찰가"
                                  : "🔥 시작입찰가")}
                            </span>
                            <span className={cx("type")}>
                              {data.total_count
                                ? `${data.index}/${data.total_count}`
                                : "1/1"}
                            </span>
                          </>
                        )}
                      </div>
                    </div>
                    {URLInfo.isSalePage() && (
                      <>
                        {saleType === ESaleType.FIXED && (
                          <div className={cx("price_box")}>
                            {price} {_currency}
                          </div>
                        )}
                        {saleType === ESaleType.AUCTION && (
                          <div className={cx("price_box")}>
                            {highestPrice
                              ? `${highestPrice} ${_currency}`
                              : "입찰을 기다리고 있습니다."}
                          </div>
                        )}
                        {saleType === ESaleType.TIME && (
                          <div className={cx("price_box")}>
                            {highestPrice
                              ? `${highestPrice} ${_currency}`
                              : `${
                                  (data as ISaleDetail).start_price
                                } ${_currency}`}
                          </div>
                        )}
                      </>
                    )}
                  </div>
                  <div className={cx("info_area")}>
                    <div className={cx("title")}>
                      작가 인세 {data.royalties}%
                    </div>
                    <Link
                      to={URLInfo.getProfileUserUrl(data.artist_name)}
                      className={cx("info_box")}
                    >
                      <div className={cx("thumb")}>
                        <CircleThumb
                          thumbSrc={data.artist_profile_image}
                          width={30}
                          height={30}
                          isOfficial={data.artist_is_official}
                          officialWidth={10}
                          officialHeight={10}
                        />
                      </div>
                      <div className={cx("name")}>{data.artist_name}</div>
                    </Link>
                  </div>
                  {/* <div className={cx("info_area")}>
                    <div className={cx("title")}>컬렉션</div>
                    <Link
                      to={URLInfo.getProfileCollectionUrl(data.collection_name)}
                      className={cx("info_box")}
                    >
                      <div className={cx("thumb")}>
                        <CircleThumb
                          thumbSrc={data.collection_thumbnail_image}
                          width={30}
                          height={30}
                          isOfficial={data.collection_is_official}
                          officialWidth={10}
                          officialHeight={10}
                        />
                      </div>
                      <div className={cx("name_box")}>
                        <div className={cx("name")}>{data.collection_name}</div>
                        <div className={cx("like")}>
                          <Like
                            token_id={
                              URLInfo.isSalePage()
                                ? (data as ISaleDetail).token_id
                                : data.id
                            }
                            isLike={data.is_like}
                            likeCnt={data.like_count}
                          />
                        </div>
                      </div>
                    </Link>
                  </div> */}
                  <div className={cx("description_area")}>
                    <ProfileDesc description={data.description} />
                  </div>
                  {URLInfo.isSalePage() && (
                    <div
                      className={cx("btn_group")}
                      style={{
                        position: "relative",
                        width: "100%",
                        boxShadow: "none",
                      }}
                    >
                      {" "}
                      {saleType === ESaleType.AUCTION && !!myBiddingPrice && (
                        <div className={cx("price_area")}>
                          내 입찰가
                          <span className={cx("price")}>
                            {myBiddingPrice} {_currency}
                          </span>
                        </div>
                      )}
                      {saleType === ESaleType.TIME &&
                        (isEnd ? (
                          <>
                            <div className={cx("price_area")}>
                              최종 입찰가
                              <span className={cx("price", "final")}>
                                {highestPrice} {_currency}
                              </span>
                            </div>
                            <div className={cx("time_area")}>
                              남은시간
                              <span className={cx("time", "end")}>
                                종료되었습니다
                              </span>
                            </div>
                          </>
                        ) : (
                          <>
                            {countStart && (
                              <>
                                {highestPrice ? (
                                  <div className={cx("price_area")}>
                                    현재 최고 입찰가{" "}
                                    <span className={cx("price")}>
                                      {highestPrice} {_currency}
                                    </span>
                                  </div>
                                ) : (
                                  <div className={cx("price_area")}>
                                    시작 입찰가{" "}
                                    <span className={cx("price")}>
                                      {(data as ISaleDetail).start_price}{" "}
                                      {_currency}
                                    </span>
                                  </div>
                                )}
                                <div className={cx("time_area")}>
                                  남은시간
                                  <span className={cx("time")}>
                                    {dateText.d}d
                                  </span>
                                  <span className={cx("time")}>
                                    {dateText.h}h
                                  </span>
                                  <span className={cx("time")}>
                                    {dateText.m}m
                                  </span>
                                  <span className={cx("time")}>
                                    {dateText.s}s
                                  </span>
                                </div>
                              </>
                            )}
                          </>
                        ))}{" "}
                      <SaleButtonContainer
                        type={
                          URLInfo.isSalePage()
                            ? (data as ISaleDetail).token_type
                            : (data as ITokenDetail).type
                        }
                        saleType={saleType}
                        isOwner={(data as ISaleDetail).is_owner}
                        highestPrice={highestPrice}
                        currency={(data as ISaleDetail).currency}
                        name={data.name}
                        artist_name={data.artist_name}
                        myBiddingPrice={myBiddingPrice}
                        price={price}
                        isTimeout={isEnd}
                        status={(data as ISaleDetail).status}
                        tokenId={
                          URLInfo.isSalePage()
                            ? (data as ISaleDetail).token_id
                            : (data as ITokenDetail).id
                        }
                        startPrice={(data as ISaleDetail).start_price}
                      />
                    </div>
                  )}
                </div>
                <SaleTab
                  type={
                    URLInfo.isSalePage()
                      ? (data as ISaleDetail).token_type
                      : (data as ITokenDetail).type
                  }
                  saleType={(data as ISaleDetail).sale_type}
                />
              </div>
              <div className={cx("btn_group")}>
                {/* {URLInfo.isSalePage() && (
                  <>
                    {saleType === ESaleType.AUCTION && !!myBiddingPrice && (
                      <div className={cx("price_area")}>
                        내 입찰가
                        <span className={cx("price")}>
                          {myBiddingPrice} {_currency}
                        </span>
                      </div>
                    )}
                    {saleType === ESaleType.TIME &&
                      (isEnd ? (
                        <>
                          <div className={cx("price_area")}>
                            최종 입찰가
                            <span className={cx("price", "final")}>
                              {highestPrice} {_currency}
                            </span>
                          </div>
                          <div className={cx("time_area")}>
                            남은시간
                            <span className={cx("time", "end")}>
                              종료되었습니다
                            </span>
                          </div>
                        </>
                      ) : (
                        <>
                          {countStart && (
                            <>
                              {highestPrice ? (
                                <div className={cx("price_area")}>
                                  현재 최고 입찰가{" "}
                                  <span className={cx("price")}>
                                    {highestPrice} {_currency}
                                  </span>
                                </div>
                              ) : (
                                <div className={cx("price_area")}>
                                  시작 입찰가{" "}
                                  <span className={cx("price")}>
                                    {(data as ISaleDetail).start_price}{" "}
                                    {_currency}
                                  </span>
                                </div>
                              )}
                              <div className={cx("time_area")}>
                                남은시간
                                <span className={cx("time")}>
                                  {dateText.d}d
                                </span>
                                <span className={cx("time")}>
                                  {dateText.h}h
                                </span>
                                <span className={cx("time")}>
                                  {dateText.m}m
                                </span>
                                <span className={cx("time")}>
                                  {dateText.s}s
                                </span>
                              </div>
                            </>
                          )}
                        </>
                      ))}
                  </>
                )} */}
                {!URLInfo.isSalePage() && (
                  <SaleButtonContainer
                    type={
                      URLInfo.isSalePage()
                        ? (data as ISaleDetail).token_type
                        : (data as ITokenDetail).type
                    }
                    saleType={saleType}
                    isOwner={(data as ISaleDetail).is_owner}
                    highestPrice={highestPrice}
                    currency={(data as ISaleDetail).currency}
                    name={data.name}
                    artist_name={data.artist_name}
                    myBiddingPrice={myBiddingPrice}
                    price={price}
                    isTimeout={isEnd}
                    status={(data as ISaleDetail).status}
                    tokenId={
                      URLInfo.isSalePage()
                        ? (data as ISaleDetail).token_id
                        : (data as ITokenDetail).id
                    }
                    startPrice={(data as ISaleDetail).start_price}
                  />
                )}
              </div>
            </div>
          )}
        </>
      ) : (
        <Loading />
      )}
    </div>
  );
};

export default Sale;
