import React, { useEffect } from 'react';
import classNames from 'classnames/bind';
import styles from './TabOwner.scss';
import CircleThumb from '../CircleThumb';
import { useDispatch, useSelector } from 'react-redux';
import { fetchOwner } from '@src/store/reducers/TokenReducer';
import TimeUtil from '@src/utils/TimeUtil';
import { Link, useLocation } from 'react-router-dom';
import URLInfo from '@src/constants/URLInfo';
import { ISaleDetail, ITokenDetail } from 'metarare';

const cx = classNames.bind(styles);

const TabOwner: React.FC = () => {
  const location = useLocation();
  const dispatch = useDispatch();
  const { owner } = useSelector(store => store.token);
  const { data: saleData } = useSelector(store => store.sale);
  const { data: tokenData } = useSelector(store => store.token);

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

  useEffect(() => {
    if (data) {
      const tokenUid = URLInfo?.isSalePage() ? (data as ISaleDetail).token_uid : (data as ITokenDetail).uid;
      dispatch(fetchOwner(tokenUid));
    }
  }, [data, location.pathname]);

  return (
    <div className={cx('tab_owner')}>
      {owner?.length ? (
        <ul className={cx('owner_list')}>
          {owner.map(item => (
            <li className={cx('item')} key={item.token_id}>
              <Link to={URLInfo.getProfileUserUrl(item.name)} className={cx('link')}>
                <div className={cx('thumb_area')}>
                  <CircleThumb
                    thumbSrc={item.thumbnail_image}
                    width={30}
                    height={30}
                    isOfficial={item.is_official}
                    officialWidth={10}
                    officialHeight={10}
                  />
                </div>
                <div className={cx('info_area')}>
                  <div className={cx('info_box')}>
                    <span className={cx('info')}>
                      {item.index}/{item.total_count}
                    </span>
                  </div>
                  <div className={cx('info_box')}>
                    <span className={cx('info')}>
                      by
                      <span className={cx('name')}>
                        {item.name}
                      </span>
                    </span>
                    <span className={cx('info', 'date')}>
                      {TimeUtil.getPeriodTimeString(item.updated_at)}
                    </span>
                  </div>
                </div>
              </Link>
            </li>
          ))}
        </ul>
      ) : (
        <div className={cx('no_result')}>
          소유자가 없습니다.
        </div>
      )}
    </div >
  );
};

export default TabOwner;
