import React, { useEffect, useRef, useState } from 'react';
import classNames from 'classnames/bind';
import styles from './Profile.scss';
import ProfileInfo from '@src/components/common/ProfileInfo';
import ProfileDesc from '@src/components/common/ProfileDesc';
import ListMenu from '@src/components/common/ListMenu';
import Share from '@src/components/common/Share';
import Tab, { ITab } from '@src/components/common/Tab';
import ActivityContentContainer from '@src/containers/common/ActivityContentContainer';
import { useDispatch, useSelector } from 'react-redux';
import { fetchCollection, fetchCollectionActivity, fetchCollectionItem, resetItem } from '@src/store/reducers/CollectionReducer';
import useMore from '@src/hooks/useMore';
import NumberUtil from '@src/utils/NumberUtil';
import URLInfo from '@src/constants/URLInfo';
import { useHistory } from 'react-router';
import InputImage from '@src/components/common/InputImage';
import APIs from '@src/api/APIs';
import useActivityFilter from '@src/hooks/useActivityFilter';
import NFTCardList from '@src/components/common/NFTCardList';
import Loading from '@src/components/common/Loading';

const cx = classNames.bind(styles);

interface IOwnProps { };

enum EProfileCollectionTabType {
  ITEM = 'item',
  ACTIVITY = 'acitivity'
}

const tabList: ITab[] = [{
  title: '아이템',
  type: EProfileCollectionTabType.ITEM
},
{
  title: '활동',
  type: EProfileCollectionTabType.ACTIVITY
}];

const ProfileCollection: React.FC<IOwnProps> = ({ }) => {
  const history = useHistory();
  const name = window.location.pathname.split('/')[2];
  const isEditPage = URLInfo.isProfileCollectionEdit();
  const dispatch = useDispatch();
  const { activity, item, baseInfo, isBaseInfoLoaded } = useSelector(store => store.collection);
  const [selectedTab, setSelectedTab] = useState<string>(tabList[0].type);

  // 이미지(편집)
  const [image, setImage] = useState<File | null>(null);
  const imageRef = useRef<HTMLImageElement>(null);

  // 커버이미지(편집)
  const [coverImage, setCoverImage] = useState<File | null>(null);
  const coverImageRef = useRef<HTMLImageElement>(null);

  // 설명(편집)
  const [desc, setDesc] = useState<string>('');
  const descRef = useRef<HTMLTextAreaElement>(null);

  const { activityList, setSelectedActivityFilter, selectedActivityFilter } = useActivityFilter({ activity });
  const dispatchCollectionItem = (offset: number, limit: number) => {
    dispatch(fetchCollectionItem({
      name,
      filter: {
        offset,
        limit
      }
    }));
  };

  const { onClickMore, showMore, resetPagination, defaultDisplayCnt } = useMore({ list: item, dispatchFnc: dispatchCollectionItem });

  const menuList = [
    {
      title: '신고하기',
      onClick: () => { },
      isDisabled: true
    }
    // ,
    // {
    //   title: '컬렉션 편집',
    //   onClick: () => {
    //     history.push(URLInfo.getCollectionEditUrl(name));
    //   },
    //   isDisabled: !baseInfo?.is_owner,
    // }
  ];

  const editMenuList = [
    {
      title: '저장하기',
      onClick: async () => {
        const json = {
          collection_id: baseInfo?.id,
          description: desc,
        };

        const formData = new FormData();
        if (image) {
          formData.append('thumbnailImage', image);
        }

        if (coverImage) {
          formData.append('coverImage', coverImage);
        }

        formData.append('json', JSON.stringify(json));

        await APIs.updateCollection(formData)
          .then(() => {
            history.push(URLInfo.getProfileCollectionUrl(name));
            dispatch(fetchCollection(name));
          })
          .catch(() => {
            alert('저장 실패');
          });
      },
      isDisabled: false
    },
  ];

  useEffect(() => {
    dispatch(fetchCollection(name));
    setSelectedTab(tabList[0].type);
  }, [history.location.pathname]);

  useEffect(() => {
    if (selectedTab === EProfileCollectionTabType.ITEM) {
      dispatch(resetItem());
      resetPagination();
      dispatchCollectionItem(0, defaultDisplayCnt);
    }

    if (selectedTab === EProfileCollectionTabType.ACTIVITY) {
      dispatch(fetchCollectionActivity(name));
    }
  }, [selectedTab]);

  useEffect(() => {
    if (baseInfo?.description) {
      setDesc(baseInfo.description);
    }
  }, [baseInfo]);

  const changeDescHeight = () => {
    const descEl = descRef.current;

    if (!descEl) {
      return;
    }

    descEl.style.height = 'auto';
    descEl.style.height = `${descEl.scrollHeight + 2}px`;
  };

  useEffect(() => {
    changeDescHeight();
  }, [desc]);

  return (
    <>
      {isBaseInfoLoaded ? (
        <div className={cx('profile')}>
          <div className={cx('banner')}>
            <img src={baseInfo?.cover_image} alt="" ref={coverImageRef} />
          </div>
          <div className={cx('profile_container')}>
            <div className={cx('menu_wrap')}>
              <ListMenu alignLeft={true} list={isEditPage ? editMenuList : menuList} />
            </div>
            <div className={cx('share_wrap')}>
              <Share />
            </div>
            <ProfileInfo thumbnailImage={baseInfo?.thumbnail_image} name={baseInfo?.name} userName={baseInfo?.user_name} address={baseInfo?.contract_address} imgRef={imageRef} />
            {isEditPage && (
              <div className={cx('file_select_area')}>
                <InputImage title="컬렉션사진 선택" imageRef={imageRef} setImage={setImage} limitFileSize={10} fileTypes={['jpg', 'jpeg', 'png', 'gif']} fileSize={{ min: 520, max: 4098 }}/>
                <InputImage title="커버사진 선택" imageRef={coverImageRef} setImage={setCoverImage} limitFileSize={10} fileTypes={['jpg', 'jpeg', 'png', 'gif']} fileSize={{ min: 520, max: 4098 }}/>
              </div>
            )}
            <ul className={cx('info_list_set')}>
              <li className={cx('info_list_list')}>
                <p className={cx('title')}>Highest Sale</p>
                <p className={cx('desc')}>${NumberUtil.numFormatter(baseInfo?.highest_sale_price)}</p>
              </li>
              <li className={cx('info_list_list')}>
                <p className={cx('title')}>Floor price</p>
                <p className={cx('desc')}>0</p>
              </li>
              <li className={cx('info_list_list')}>
                <p className={cx('title')}>Market Cap</p>
                <p className={cx('desc')}>${NumberUtil.numFormatter(baseInfo?.market_cap)}</p>
              </li>
              <li className={cx('info_list_list')}>
                <p className={cx('title')}>Items</p>
                <p className={cx('desc')}>{baseInfo?.items}</p>
              </li>
              <li className={cx('info_list_list')}>
                <p className={cx('title')}>Owners</p>
                <p className={cx('desc')}>1</p>
              </li>
              <li className={cx('info_list_list')}>
                <p className={cx('title')}>Total Volume</p>
                <p className={cx('desc')}>${NumberUtil.numFormatter(baseInfo?.total_volume)}</p>
              </li>
            </ul>
            <div className={cx('desc_wrapper')}>
              {isEditPage ? (
                <div className={cx('text_area_wrapper')}>
                  <textarea name="item_descrition" id="item_descrition" className={cx('textarea')} placeholder="아이템 설명을 입력해주세요" onChange={e => setDesc(e.target.value)} defaultValue={baseInfo?.description} ref={descRef}>
                  </textarea>
                </div>
              ) : (
                <ProfileDesc description={baseInfo?.description} />
              )}
            </div>
            <div className={cx('tab_wrapper')}>
              <Tab tabList={tabList} selectedTab={selectedTab} setSelectedTab={setSelectedTab} />
            </div>
            <div className={cx('list_wrapper')}>
              {(selectedTab === EProfileCollectionTabType.ITEM) && (
                <NFTCardList list={item} onClickMore={onClickMore} showMore={showMore} />
              )}
              {(selectedTab === EProfileCollectionTabType.ACTIVITY) && (
                <ActivityContentContainer list={activityList} setSelectedFilterType={setSelectedActivityFilter} selectedActivityFilter={selectedActivityFilter} />
              )}
            </div>
          </div>
        </div>
      ) : (
        <Loading />
      )}
    </>
  );
};

export default ProfileCollection;
