import React, { ReactElement, useEffect, useRef, useState, useLayoutEffect } from 'react';
import classNames from 'classnames/bind';
import styles from './Create.scss';
import validateStyles from '../components/common/Input.scss';
import ButtonOption from '@src/components/common/ButtonOption';
import Input from '@src/components/common/Input';
import InputPrice from '@src/components/common/InputPrice';
import CircleThumb from '@src/components/common/CircleThumb';
import { ReactComponent as LogoEhtereum } from '@assets/img/svg/logo_ethereum.svg';
import { ReactComponent as LogoMetafinance } from '@assets/img/svg/logo_metafinance.svg';
import { ReactComponent as IcoSingle } from '@assets/img/svg/ico_single.svg';
import { ReactComponent as IcoMulti } from '@assets/img/svg/ico_multi.svg';
import { ReactComponent as IcoDelete } from '@assets/img/svg/btn_delete.svg';
import { ReactComponent as IcoArrow } from '@assets/img/svg/ico_arrow_down.svg';
import { ReactComponent as IcoCollection } from '@assets/img/svg/ico_collection_color.svg';
import URLInfo from '@src/constants/URLInfo';
import NumberUtil from '@src/utils/NumberUtil';
import HashBox from '@src/components/common/HashBox';
import Layer from '@src/components/common/Layer';
import { EItemType, ESaleType, ECurrencyType } from '@src/constants/Enums';
import Feature, { IFeature } from '@src/components/common/Feature';
import LayerContainer from '@src/containers/common/LayerContainer';
import StringUtil from '@src/utils/StringUtil';
import { useHistory } from 'react-router';
import 'date-fns';
import DesktopDateTimePicker from '@mui/lab/DesktopDateTimePicker';
import AdapterDateFns from '@mui/lab/AdapterDateFns';
import LocalizationProvider from '@mui/lab/LocalizationProvider';
import APIs from '@src/api/APIs';
import { useDispatch, useSelector } from 'react-redux';
import { addCollection, fetchBaseInfo, fetchResaleInfo } from '@src/store/reducers/TokenReducer';
import DateUtil from '@src/utils/DateUtil';
import LoginContainer from '@src/containers/common/LoginContainer';
import useResize from '@src/hooks/useResize';
import InputImage from '@src/components/common/InputImage';
import FileUtil from '@src/utils/FileUtil';
import { toggleLoadingState } from '@src/store/reducers/NetworkLoadingReducer';
import {selectedCurrency} from '@src/components/common/InputPrice'

const cx = classNames.bind(styles);
const cs = classNames.bind(validateStyles);

interface IOwnProps { };

type InputType = {
  "inputName": boolean;
  "inputDesc": boolean;
  "inputRoyalties": boolean;
  "inputTotalCount": boolean;
  "inputPrice" : boolean;
  "inputAuctionPrice": boolean;
  "inputImage" : boolean;
  "inputCollection" : boolean;
}

type CollectionInputType = {
  "inputCollectionName" : boolean,
  "inputCollectionSymbol" : boolean,
  "inputCollectionNameCheck" : boolean,
  "inputCollectionProfile": boolean,
  "inputCollectionCover" : boolean
}

type ResalePageInputType = {
  "inputResalePrice" : boolean;
  "inputResaleTime" : boolean;
}

const SaleType = {
  [ESaleType.FIXED]: '지정가',
  [ESaleType.AUCTION]: '입찰가',
  [ESaleType.TIME]: '타임옥션',
};

const MAX_TOKEN_NAME_LENGTH = 40;
const MAX_TOTAL_COUNT = 20;
const MAX_ITEM_LENGTH = 300;
function b64EncodeUnicode(str: string) {
  return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => {
    return String.fromCharCode(parseInt(p1, 16));
  }));
}

const filenameToBase64 = (originalFile: File) => {
  return new File([originalFile], b64EncodeUnicode(originalFile.name) + `.${originalFile.name.split('.').pop()}`, {
    type: originalFile.type,
    lastModified: originalFile.lastModified,
  });
};

const Create: React.FC<IOwnProps> = ({ }) => {
  const dispatch = useDispatch();
  const history = useHistory();
  const isResalePage = URLInfo.isResalePage();
  const id = URLInfo.getId();
  const { baseInfo, resaleInfo } = useSelector(store => store.token);
  const { userInfo } = useSelector(store => store.user);
  const { height } = useResize();

  // 아이템 설명
  const descRef = useRef<HTMLTextAreaElement>(null);
  const [inputError, setInputError] = useState<InputType>({
    "inputName": false,
    "inputDesc": false,
    "inputRoyalties": false,
    "inputTotalCount": false,
    "inputPrice" : false,
    "inputAuctionPrice": false,
    "inputImage" : false,
    "inputCollection" : false,
  });

  const [inputCollectionError, setInputCollectionError] = useState<CollectionInputType>({
    "inputCollectionName" : false,
    "inputCollectionSymbol" : false,
    "inputCollectionNameCheck" : false,
    "inputCollectionProfile": false,
    "inputCollectionCover" : false
  })

  const [resalePageInput, setResalePageInput] = useState({
    "inputResalePrice" : false,
    "inputResaleTime" : false,
  })

  // 타입 선택
  const [selectedType, setSelectedType] = useState<EItemType>(EItemType.SINGLE);
  // 마켓 등록 형태
  const [selectedSaleType, setSelectedSaleType] = useState<ESaleType>(ESaleType.FIXED);
  // 컬렉션 선택
  const [selectedCollection, setSelectedCollection] = useState<number>();
  // 가격 설정(지정가)
  const [price, setPrice] = useState<string>('');
  const [currencyType, setCurrencyType] = useState<ECurrencyType>(ECurrencyType.ETH);
  const [auctionCurrencyType, setAuctionCurrencyType] = useState<ECurrencyType>(ECurrencyType.ETH);

  // 최소 경매가(타임 옥션)
  const [auctionPrice, setAuctionPrice] = useState<string>('');
  const [timeCurrencyType, setTimeCurrencyType] = useState<ECurrencyType>(ECurrencyType.ETH);

  // 아이템 이름
  const [name, setName] = useState<string>('');
  const [desc, setDesc] = useState<string>('');

  // 특징
  const [featureEl, setFeatureEl] = useState<ReactElement[]>([]);
  const feature = useRef<IFeature[]>([]);
  const featureElRef = useRef<ReactElement[]>([]);

  // 인세
  const [royalties, setRoyalties] = useState<string>('');

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

  // 토큰 개수
  const [totalCount, setTotalCount] = useState<string>('');

  // 컬렉션 추가 레이어
  const [showMakeCollectionLayer, setShowMakeCollectionLayer] = useState<boolean>(false);
  const collectionDescRef = useRef<HTMLTextAreaElement>(null);
  const [collectionImage, setCollectionImage] = useState<File | null>(null);
  const [collectionCoverImage, setCollectionCoverImage] = useState<File | null>(null);
  const [collectionTitle, setCollectionTitle] = useState<string>('');

  const [checkDuplicate, setCheckDuplicate] = useState<{ name: string; checked: boolean; duplicate: boolean }>({ name: '', checked: false, duplicate: false });
  const [collectionToken, setCollectionToken] = useState<string>('');
  const [collectionDesc, setCollectionDesc] = useState<string>('');
  const [collectionHash, setCollectionHash] = useState<string>('');
  const collectionImageRef = useRef<HTMLImageElement>(null);
  const collectionCoverImageRef = useRef<HTMLImageElement>(null);

  // 컬렉션 추가완료 레이어
  const [showCollectionCompleteLayer, setShowCollectionCompleteLayer] = useState<boolean>(false);

  // 아이템 만들기 레이어
  const [showCompleteLayer, setShowCompleteLayer] = useState<boolean>(false);

  // 시작일 & 종료일
  const [startDate, setStartDate] = React.useState<Date | null>(null);
  const [endDate, setEndDate] = React.useState<Date | null>(null);
  const [showStartDate, setShowStartDate] = useState(false);
  const [showEndDate, setShowEndDate] = useState(false);

  // 수수료
  const [commission, setCommission] = useState<number>(0);

  // NFT id
  const [newItemId, setNewItemId] = useState<number>(0);

  // 미리보기 이미지
  const previewImgRef = useRef<HTMLImageElement>(null);
  const previewVideoRef = useRef<HTMLVideoElement>(null);


  useEffect(() => {
    createNewFeature();

    if (isResalePage) {
      dispatch(fetchResaleInfo(id));
    }
  }, []);

  useEffect(() => {
    if (baseInfo) {
      setCommission(baseInfo?.commission);
    }
  }, [baseInfo]);

  useLayoutEffect(() => {
    if (isResalePage && resaleInfo) {
      const { collection_id, content_url, description, name, royalties, type, commission, total_count } = resaleInfo.token;

      setSelectedCollection(collection_id);
      setDesc(description);
      setRoyalties(royalties.toString());
      setName(name);
      setSelectedType(type);
      setCommission(commission);
      setTotalCount(total_count ? total_count.toString() : '');

      feature.current = resaleInfo.traits;

      if (content_url && previewVideoRef.current && previewImgRef.current) {
        if (videoRef.current && FileUtil.isVideo(content_url)) {
          videoRef.current.src = content_url;
          previewVideoRef.current.src = content_url;
        } else {
          if (imageRef.current && previewImgRef.current) {
            imageRef.current.src = content_url;
            previewImgRef.current.src = content_url;
          }
        }
      }
    }
  }, [resaleInfo, imageRef.current, previewImgRef.current, videoRef.current, previewVideoRef.current]);

  const resetInput = () => {
    setTotalCount('');
    setName('');
    setDesc('');
    setRoyalties('');
    feature.current = [];
    setAuctionPrice('');
    setStartDate(null);
    setEndDate(null);
    setSelectedCollection(0);
    setImage(null);
    setPrice('');
    setSelectedSaleType(ESaleType.FIXED);
    setCurrencyType(ECurrencyType.ETH);
    setAuctionCurrencyType(ECurrencyType.ETH);
    setTimeCurrencyType(ECurrencyType.ETH);
    if (imageRef.current) {
      imageRef.current.src = '';
    }
    if (previewImgRef.current) {
      previewImgRef.current.src = '';
    }
  };

  useEffect(() => {
    resetInput();
  }, [history.location.pathname]);

  useEffect(() => {
    if (!isResalePage) {
      dispatch(fetchBaseInfo(selectedType));
    }
    if (!resaleInfo) {
      resetInput();
    }
  }, [selectedType]);

  const handleChangeLayerTitle = (e: React.ChangeEvent<HTMLInputElement>) => {
    setCollectionTitle(e.target.value);
    setCheckDuplicate({ name: e.target.value, checked: false, duplicate: false });
  };

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

    if (!descEl) {
      return;
    }

    descEl.style.height = 'auto';
    descEl.style.height = `${descEl.scrollHeight + 2}px`;
  }, [desc]);

  const handleChangeName = (e: React.ChangeEvent<HTMLInputElement>) => {
    setName(e.target.value);
  };

  const handleChangeItemDesc = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setDesc(e.target.value)
  }

  const handleChangeLayerDesc = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const descEl = collectionDescRef.current;

    if (!descEl) {
      return;
    }

    setCollectionDesc(e.target.value);

    if (height - descEl.scrollHeight <= 740) {
      return;
    }

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

  useEffect(() => {
    const descEl = collectionDescRef.current;

    if (!descEl) {
      return;
    }

    if (height - descEl.scrollHeight < 740) {
      descEl.style.height = `${height - 740}px`;
    }
  }, [collectionDescRef.current]);

  const handleChangeRoyalties = (e: React.ChangeEvent<HTMLInputElement>) => {
    e.target.value = NumberUtil.replaceOnlyNumber(e.target.value);
    setRoyalties(e.target.value);
  };

  const handleChangeTotalCount = (e: React.ChangeEvent<HTMLInputElement>) => {
    e.target.value = NumberUtil.replaceOnlyNumber(e.target.value);
    setTotalCount(e.target.value);
  };

  const createNewFeature = () => {
    const features = [
      ...feature.current,
      { key: '', value: '' }
    ];

    feature.current = features;
    const setFeature = (value: IFeature[]) => {
      feature.current = value;
    };

    const list: ReactElement[] = [];

    [...new Array(featureElRef.current.length + 1).keys()].forEach(item => {
      list.push(<Feature key={item} feature={features} setFeature={setFeature} createNewFeature={createNewFeature} index={item} isResalePage={isResalePage} />);
    });

    featureElRef.current = [...list];
    setFeatureEl(featureElRef.current);
  };

  const handleClickDuplicate = async () => {
    await APIs.checkCollectionDuplicate(collectionTitle).then(() => {
      setCheckDuplicate({ name: collectionTitle, checked: true, duplicate: false });
    }).catch(() => {
      setCheckDuplicate({ name: collectionTitle, checked: false, duplicate: true });
    });
  };

  const handleChangeImage = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files || !e.target.files[0]) {
      return;
    }

    const file = e.target.files[0];
    const reader = new FileReader();
    const img = new Image();

    reader.onload = e => {
      if (previewImgRef.current && previewVideoRef.current) {
        if (FileUtil.isVideo(file.name)) {
          previewVideoRef.current.src = e.target?.result as string;
          previewImgRef.current.src = '';
        } else {
          previewImgRef.current.src = e.target?.result as string;
          previewVideoRef.current.src = '';
          img.src = e.target?.result as string;
        }
      }
    };

    reader.readAsDataURL(file);
  };

  const handleClickSubmit = async () => {
    let currency = currencyType;

    if (selectedSaleType === ESaleType.AUCTION) {
      currency = auctionCurrencyType;
    }

    if (selectedSaleType === ESaleType.TIME) {
      currency = timeCurrencyType;
    }

    if (isResalePage) {
      let json: {
        currency: ECurrencyType; end_at?: string; price?: number; sale_type: ESaleType; start_at?: string; start_price?: number; token_id: number;
      } = {
        sale_type: selectedSaleType,
        currency,
        token_id: id,
      };

      const resalePageErrors: ResalePageInputType = {
        inputResalePrice: !price && selectedSaleType === ESaleType.FIXED,
        inputResaleTime: !auctionPrice && selectedSaleType === ESaleType.TIME && selectedType === EItemType.SINGLE,
      }

      setResalePageInput(resalePageErrors);

      if(Object.values(resalePageErrors).findIndex(v => v === true) > -1) {
        return;
      }

      if (selectedSaleType === ESaleType.FIXED) {
        json = {
          ...json,
          price: Number(price)
        };
      }

      if (selectedSaleType === ESaleType.TIME) {
        if (selectedType === EItemType.SINGLE) {
          if (startDate && startDate.getTime() < new Date().getTime()) {
            alert('시작일은 현재 시각보다 이후 시간이여야 합니다.');
            return;
          }

          const startAt = startDate || new Date();
          const endAt = endDate || DateUtil.getTomorrwDate();

          if (startAt.getTime() > endAt.getTime()) {
            alert('종료일은 시작일보다 이후 시간이여야 합니다.');
            return;
          }

          json = {
            ...json,
            start_price: Number(auctionPrice),
            start_at: DateUtil.getConvertKST(startAt),
            end_at: DateUtil.getConvertKST(endAt),
          };
        }
      }
      dispatch(toggleLoadingState());
      await APIs.resale(json).then((res) => {
        setNewItemId(res.id);
        setShowCompleteLayer(true);
      }).catch(() => {
        alert('만들기 실패');
      }).finally(() => {
        dispatch(toggleLoadingState());
      });
    } else {
      const traits = feature.current.filter(item => !!item.key && !!item.value);
      const addLinkDesc = (desc: string) => {
        const regUrl = new RegExp("(http|https)://([-/.a-zA-Z0-9_~#%$?&=:200-377()]+)", "gi");
        return desc.replace(regUrl, "<a href='$1://$2' target='_blank'>$1://$2</a>")
      }

      let json;
      const commonJson = {
        collection_id: selectedCollection,
        name:name.trim(),
        description: addLinkDesc(desc),
        type: selectedType,
        royalties: Number(royalties),
        sale: {
          sale_type: selectedSaleType,
          currency,
        },
        traits,
        total_count: totalCount ? Number(totalCount) : 1
      };

      if (selectedSaleType === ESaleType.TIME) {
        if (selectedType === EItemType.SINGLE) {
          if (startDate && startDate.getTime() < new Date().getTime()) {
            alert('시작일은 현재 시각보다 이후 시간이여야 합니다.');
            return;
          }

          const startAt = startDate || new Date();
          const endAt = endDate || DateUtil.getTomorrwDate();

          if (startAt.getTime() > endAt.getTime()) {
            alert('종료일은 시작일보다 이후 시간이여야 합니다.');
            return;
          }
        }
      }


      const inputErrors: InputType = {        
        "inputName" : name.length === 0 || name.length > MAX_TOKEN_NAME_LENGTH,
        "inputDesc" : desc.length === 0 || desc.length > MAX_ITEM_LENGTH,
        "inputRoyalties" : royalties === "" || Number(royalties) % 1 !== 0 || Number(royalties) > 50,
        "inputTotalCount": selectedType === EItemType.MULTI && (Number(totalCount) > MAX_TOTAL_COUNT || totalCount.length === 0 || Number(totalCount) === 0 || Number(totalCount) % 1 !== 0),
        "inputPrice" : selectedSaleType === ESaleType.FIXED && !price, 
        "inputAuctionPrice" : selectedSaleType === ESaleType.TIME && !auctionPrice,
        "inputCollection": !selectedCollection,
        "inputImage": !image
      };

      setInputError(inputErrors);
      
      if(Object.values(inputErrors).findIndex(v => v === true) > -1) {
        return;
      }

      if (selectedSaleType === ESaleType.FIXED) {
        json = {
          ...commonJson,
          sale: {
            ...commonJson.sale,
            price: Number(price)
          }
        };
      }

      if (selectedSaleType === ESaleType.AUCTION) {
        json = {
          ...commonJson
        };
      }

      if (selectedSaleType === ESaleType.TIME) {
        if (selectedType === EItemType.SINGLE) {
          const startAt = startDate || new Date();
          const endAt = endDate || DateUtil.getTomorrwDate();

          json = {
            ...commonJson,
            sale: {
              ...commonJson.sale,
              start_price: Number(auctionPrice),
              start_at: DateUtil.getConvertKST(startAt),
              end_at: DateUtil.getConvertKST(endAt),
            },
          };
        }
      }

      const formData = new FormData();
      formData.append('contentImage', filenameToBase64(image!));
      formData.append('json', JSON.stringify(json));
      dispatch(toggleLoadingState());
      await APIs.addToken(formData).then((res) => {
        setNewItemId(res.id);
        setShowCompleteLayer(true);
      }).catch(() => {
        alert('만들기 실패');
      }).finally(() => {
        dispatch(toggleLoadingState());
      });
    }
  };

  const handleSubmitMakeCollection = async () => {
    const inputCollectionErrors: CollectionInputType = {        
      "inputCollectionName" : collectionTitle.length > 100 || collectionTitle.length === 0,
      "inputCollectionSymbol" : !/^[A-Za-z0-9\s]{3,20}$/.test(collectionToken),
      "inputCollectionNameCheck" : !checkDuplicate.checked || checkDuplicate.name !== collectionTitle,
      "inputCollectionProfile" : !collectionImage,
      "inputCollectionCover" : !collectionCoverImage
    };

    setInputCollectionError(inputCollectionErrors);
    
    if(Object.values(inputCollectionErrors).findIndex(v => v === true) > -1) {
      return;
    }

    const json = {
      name: collectionTitle,
      symbol: collectionToken,
      description: collectionDesc,
      type: selectedType
    };

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

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

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

    dispatch(toggleLoadingState());
    await APIs.addCollection(formData)
      .then((res) => {
        setCollectionHash(res.tx_hash);
        setShowCollectionCompleteLayer(true);
        setShowMakeCollectionLayer(false);
        dispatch(addCollection(res));
        resetCollectionInput();
        dispatch(toggleLoadingState());
      })
      .catch(() => {
        dispatch(toggleLoadingState());
        alert('저장 실패');
      });
  };

  const handleClickTransaction = () => {
    setShowCollectionCompleteLayer(false);
    window.open(URLInfo.getTransactionUrl(collectionHash), '_blank');
  };

  const handleClickMakeItem = () => {
    resetInput();
    history.push(URLInfo.getSaleUrl(newItemId));
  };

  const resetCollectionInput = () => {
    setCollectionImage(null);
    setCollectionCoverImage(null);
    setCollectionTitle('');
    setCheckDuplicate({ name: '', checked: false, duplicate: false });
    setCollectionToken('');
    setCollectionDesc('');
  };

  const handleCloseMakeCollection = () => {
    resetCollectionInput();
    setShowMakeCollectionLayer(false);
  };

  const handleCloseCompleteLayer = () => {
    setShowCompleteLayer(false);
    resetCollectionInput();
    resetInput();
  };

  return (
    <div className={cx('create_item')}>
      <div className={cx('create_title')}>
        NFT 만들기
      </div>
      <LoginContainer>
        <>
          <div className={cx('create_item_wrap')}>
            <div className={cx('create_group')}>
              <div className={cx('option_area')}>
                <strong className={cx('item_title')}>블록체인 선택
                  <span className={cx('item_required')}>*</span>
                </strong>
                <div className={cx('option_box')}>
                  <ButtonOption
                    title={'Ethereum'}
                    buttonText={'선택'}
                    isSelected
                  >
                    <LogoEhtereum />
                  </ButtonOption>
                  <ButtonOption
                    title={'BSC'}
                    buttonText={'준비중'}
                    isDisabled
                  >
                    <i className={cx('logo_bsc')}></i>
                  </ButtonOption>
                </div>
              </div>
              <div className={cx('option_area')}>
                <strong className={cx('item_title')}>타입 선택
                  <span className={cx('item_required')}>*</span>
                </strong>
                <div className={cx('option_box')}>
                  <ButtonOption
                    title={'싱글'}
                    buttonText={'선택'}
                    desc={'NFT 단일 아이템을 생성합니다'}
                    isSelected={selectedType === EItemType.SINGLE}
                    onClick={() => setSelectedType(EItemType.SINGLE)}
                    isDisabled={isResalePage && selectedType !== EItemType.SINGLE}
                  >
                    <IcoSingle />
                  </ButtonOption>
                  <ButtonOption
                    title={'멀티'}
                    buttonText={'선택'}
                    desc={'NFT 다수 아이템을 생성합니다'}
                    isSelected={selectedType === EItemType.MULTI}
                    onClick={() => setSelectedType(EItemType.MULTI)}
                    isDisabled={isResalePage && selectedType !== EItemType.MULTI}
                  >
                    <IcoMulti />
                  </ButtonOption>
                </div>
              </div>
              {selectedType === EItemType.MULTI && (
                <div className={cx('option_area')}>
                  <strong className={cx('item_title')}>작품개수
                    <span className={cx('item_required')}>*</span>
                  </strong>
                  <div className={cx('input_box')}>
                    <Input className={cx(inputError.inputTotalCount ? 'validate_input' : 'input')} placeholder={'예시 숫자 기입'} disabled={isResalePage} onChange={handleChangeTotalCount} value={totalCount} />
                    {inputError.inputTotalCount && (<span className={cs('input_validate_message')}>작품개수는 1~20개 사이로 입력해 주세요</span>)}
                  </div>
                </div>
              )}
              <div className={cx('option_area')}>
                <strong className={cx('item_title')}>파일 업로드
                  <span className={cx('item_required')}>*</span>
                </strong>
                <div className={cx('file_box')}>
                  {image && (
                    <div className={cx('preview')}>
                      {FileUtil.isVideo(image.name) ? (
                        <video
                          src=""
                          height="234px"
                          className={cx('img')}
                          ref={videoRef}
                          autoPlay
                        />
                      ) : (
                        <img
                          src=""
                          alt=""
                          height="234px"
                          className={cx('img')}
                          ref={imageRef}
                        />
                      )}
                      <button className={cx('btn_delete')} onClick={() => setImage(null)}>
                        <IcoDelete className={cx('ico_delete')} />
                      </button>
                    </div>
                  )}
                  {isResalePage ? (
                    <div className={cx('preview')}>
                      {FileUtil.isVideo(resaleInfo?.token.content_url || '') ? (
                        <video
                          src=""
                          height="234px"
                          className={cx('img')}
                          ref={videoRef}
                          autoPlay
                        />
                      ) : (
                        <img
                          src=""
                          alt=""
                          height="234px"
                          className={cx('img')}
                          ref={imageRef}
                        />
                      )}
                    </div>
                  ) : (
                    <div className={cx('guide')}>
                      {/* 파일 선택 시, 파일명 텍스트 노출 */}
                      {image ? image.name : 'PNG, GIF, MP4, JPG. Max 10mb.'}
                    </div>
                  )}
                  <div className={cx('file', isResalePage && 'disabled')}>
                    <InputImage title="파일 선택" imageRef={imageRef} videoRef={videoRef} setImage={setImage} limitFileSize={10} fileTypes={['png', 'gif', 'mp4', 'jpg', 'jpeg']} handleChange={handleChangeImage} disabled={isResalePage} />
                    {inputError.inputImage && (<span className={cs('input_validate_message')}>파일을 선택해 주세요</span>)}
                  </div>
                </div>
              </div>
              <div className={cx('option_area')}>
                <strong className={cx('item_title')}>마켓 등록 형태
                  <span className={cx('item_required')}>*</span>
                </strong>
                <div className={cx('option_box')}>
                  <ButtonOption
                    title={'지정가'}
                    buttonText={'선택'}
                    isSelected={selectedSaleType === ESaleType.FIXED}
                    onClick={() => setSelectedSaleType(ESaleType.FIXED)}
                  >
                    <div className={cx('market')}>💰</div>
                  </ButtonOption>
                  <ButtonOption
                    title={'입찰가'}
                    buttonText={'선택'}
                    isSelected={selectedSaleType === ESaleType.AUCTION}
                    onClick={() => setSelectedSaleType(ESaleType.AUCTION)}
                  >
                    <div className={cx('market')}>🚀</div>
                  </ButtonOption>
                  <ButtonOption
                    title={'타임옥션'}
                    buttonText={'선택'}
                    isSelected={selectedSaleType === ESaleType.TIME}
                    onClick={() => setSelectedSaleType(ESaleType.TIME)}
                    isDisabled={selectedType === EItemType.MULTI}
                  >
                    <div className={cx('market')}>🔥</div>
                  </ButtonOption>
                </div>
              </div>
              {selectedSaleType === ESaleType.FIXED && (
                <div className={cx('option_area')}>
                  <strong className={cx('item_title')}>가격 설정
                    <span className={cx('item_required')}>*</span>
                  </strong>
                  <InputPrice className={inputError.inputPrice ? 'validate_input' : undefined} placeholder={'1개 가격'} setValue={setPrice} type={currencyType} setType={setCurrencyType} value={price} />
                  {inputError.inputPrice && <span className={cs('input_validate_message')}>판매 하려는 가격과 토큰/코인을 선택해 주세요</span>}
                  {resalePageInput.inputResalePrice && <span className={cs('input_validate_message')}>판매 하려는 가격과 토큰/코인을 선택해 주세요</span>}
                  <div className={cx('guide_box')}>
                    <div className={cx('guide')}>
                      <span className={cx('guide_title')}>수수료</span>
                      <span className={cx('info')}>{commission}%</span>
                    </div>
                    <div className={cx('guide')}>
                      <span className={cx('guide_title')}>판매 시 수령금액</span>
                      <span className={cx('info')}>{Math.floor((Number(price) * (100 - commission) * 0.01) * 100000) / 100000} {selectedCurrency(currencyType)}</span>
                    </div>
                  </div>
                </div>
              )}
              {selectedSaleType === ESaleType.AUCTION && (
                <div className={cx('option_area')}>
                  <strong className={cx('item_title')}>가격 설정</strong>
                  <InputPrice placeholder={'-'} type={auctionCurrencyType} setType={setAuctionCurrencyType} useInput={false} />

                  <div className={cx('guide_box')}>
                      <div className={cx('guide')}>
                        <span className={cx('guide_title')} style={{color: 'red'}}>* 입찰가는 가격 설정이 불가능하며, 선택한 토큰으로 입찰이 진행됩니다.</span>
                      </div>
                    </div>
                </div>
              )}
              {selectedSaleType === ESaleType.TIME && (
                <>
                  <div className={cx('option_area')}>
                    <strong className={cx('item_title')}>최소 경매가
                      <span className={cx('item_required')}>*</span>
                    </strong>
                    <InputPrice className={inputError.inputAuctionPrice ? 'validate_input' : undefined}placeholder={'1개 가격'} setValue={setAuctionPrice} type={timeCurrencyType} setType={setTimeCurrencyType} value={auctionPrice} />
                    {inputError.inputAuctionPrice && <span className={cs('input_validate_message')}>판매 하려는 가격과 토큰/코인을 선택해 주세요</span>}
                    {resalePageInput.inputResaleTime && <span className={cs('input_validate_message')}>판매 하려는 가격과 토큰/코인을 선택해 주세요</span>}
                    <div className={cx('guide_box')}>
                      <div className={cx('guide')}>
                        <span className={cx('guide_title')}>이 금액 이하의 입찰은 허용되지 않습니다.</span>
                      </div>
                    </div>
                  </div>
                  <div className={cx('option_area')}>
                    <strong className={cx('item_title')}>시작일
                      <span className={cx('item_required')}>*</span>
                    </strong>
                    <LocalizationProvider dateAdapter={AdapterDateFns}>
                      <DesktopDateTimePicker
                        open={showStartDate}
                        onClose={() => setShowStartDate(false)}
                        value={startDate}
                        onChange={(newValue) => {
                          if (newValue) {
                            setStartDate(newValue);
                          }
                        }}
                        showToolbar={false}
                        renderInput={({
                          inputRef,
                          disabled,
                          onChange,
                          inputProps
                        }) => (
                          <div className={cx('date_container')} ref={inputRef}>
                            <input
                              className={cx('btn_date')}
                              onChange={onChange}
                              disabled={disabled}
                              onClick={() => {
                                setShowStartDate(true);
                              }}
                              {...inputProps}
                              placeholder="생성 후 바로"
                            />
                            <IcoArrow className={cx('ico_arrow')} />
                          </div>
                        )}
                      />
                    </LocalizationProvider>
                  </div>
                  <div className={cx('option_area')}>
                    <strong className={cx('item_title')}>종료일
                      <span className={cx('item_required')}>*</span>
                    </strong>
                    <LocalizationProvider dateAdapter={AdapterDateFns}>
                      <DesktopDateTimePicker
                        open={showEndDate}
                        onClose={() => setShowEndDate(false)}
                        value={endDate}
                        onChange={(newValue) => {
                          setEndDate(newValue);
                        }}
                        showToolbar={false}
                        renderInput={({
                          inputRef,
                          disabled,
                          onChange,
                          inputProps
                        }) => (
                          <div className={cx('date_container')} ref={inputRef}>
                            <input
                              className={cx('btn_date')}
                              onChange={onChange}
                              disabled={disabled}
                              onClick={() => {
                                setShowEndDate(true);
                              }}
                              {...inputProps}
                              placeholder="1일"
                            />
                            <IcoArrow className={cx('ico_arrow')} />
                          </div>
                        )}
                      />
                    </LocalizationProvider>
                  </div>
                </>
              )}
              <div className={cx('option_area')}>
                <strong className={cx('item_title')}>컬렉션 선택
                  <span className={cx('item_required')}>*</span> 
                </strong>
                {inputError.inputCollection && (<span className={cs('input_validate_message')}>컬렉션을 선택해 주세요.</span>)}
                <div className={cx('option_box')}>
                  <ButtonOption
                    title={'신규 컬렉션'}
                    buttonText={'만들기'}
                    onClick={() => setShowMakeCollectionLayer(true)}
                    isDisabled={isResalePage}
                  >
                    <IcoCollection />
                  </ButtonOption>
                  {resaleInfo && (
                    <ButtonOption
                      key={resaleInfo.token.collection_id}
                      title={resaleInfo.token.collection_name}
                      buttonText={'선택'}
                      isSelected={resaleInfo.token.collection_id === selectedCollection}
                      onClick={() => setSelectedCollection(resaleInfo.token.collection_id)}
                      isDisabled={resaleInfo.token.collection_id !== selectedCollection && isResalePage}
                    >
                      <CircleThumb
                        thumbSrc={resaleInfo.token.collection_thumbnail_image}
                        width={50}
                        height={50}
                        isOfficial={resaleInfo.token.collection_is_official}
                        officialWidth={20}
                        officialHeight={20}
                      />
                    </ButtonOption>
                  )}
                  {baseInfo?.collection.map(item => (
                    <ButtonOption
                      key={item.collection_id}
                      title={item.name}
                      buttonText={'선택'}
                      isSelected={item.collection_id === selectedCollection}
                      onClick={() => setSelectedCollection(item.collection_id)}
                      isDisabled={item.collection_id !== selectedCollection && isResalePage}
                    >
                      <CircleThumb
                        thumbSrc={item.thumbnail_image}
                        width={50}
                        height={50}
                        isOfficial={item.is_official}
                        officialWidth={20}
                        officialHeight={20}
                      />
                    </ButtonOption>
                  ))}
                </div>
              </div>
              
              <div className={cx('option_area')}>
                <strong className={cx('item_title')}>아이템 이름
                  <span className={cx('item_required')}>*</span>
                </strong>
                <div className={cx('input_box')}>
                  <Input className={cx(inputError.inputName ? 'validate_input' : 'input')} placeholder={'아이템 이름을 입력해주세요'} disabled={isResalePage} onChange={handleChangeName} value={name} />
                  {inputError.inputName && (<span className={cs('input_validate_message')}>40자 이내의 아이템 이름을 입력해주세요 (최대 40자)</span>)}
                </div>
              </div>
              <div className={cx('option_area')}>
                <strong className={cx('item_title')}>
                  아이템 설명
                  <span className={cx('item_required')}>*</span>
                </strong>
                <div className={cx(inputError.inputDesc ? 'input_box_validate' : 'input_box')}>
                  <textarea name="item_descrition" id="item_descrition" className={cx('textarea')} cols={30} rows={1} placeholder="아이템 설명을 입력해주세요" disabled={isResalePage} ref={descRef} onChange={handleChangeItemDesc} value={desc}>
                  </textarea>
                  {inputError.inputDesc && <span className={cx('validate_message')}>아이템의 성격을 나타낼 수 있는 간단한 설명을 넣어주세요 (최대 300자)</span>}
                </div>
              </div>
              <div className={cx('option_area')}>
                <strong className={cx('item_title')}>인세 
                  <span className={cx('item_required')}>*</span>
                </strong>
                <div className={cx('input_box', 'royalties')}>
                    <Input className={cx(inputError.inputRoyalties? 'validate_input': 'input')} placeholder={'인세를 입력해주세요'} onChange={handleChangeRoyalties} disabled={isResalePage} value={royalties} />
                    <div className={cx('percent')}>%</div>
                    {inputError.inputRoyalties && <span className={cs('input_validate_message')}>재판매 시 작품 등록자 에게 주어지는 재판매 수수료를 1% 단위로 입력해 주세요</span>}
                </div>
                <div className={cx('guide_box')}>
                  <div className={cx('guide')}>
                    <div className={cx('guide_title')}>
                      예시: 0%, 10%, 20%, 30%.
                    </div>
                  </div>
                  <div className={cx('guide')}>
                    <div className={cx('guide_title')}>
                      최대: 50%
                    </div>
                  </div>
                </div>
              </div>
              <div className={cx('option_area')}>
                <strong className={cx('item_title')}>
                  특징
                  <span className={cx('optional')}>(선택사항)</span>
                </strong>
                <div className={cx('input_box', 'feature')}>
                  {featureEl}
                </div>
              </div>
              <div className={cx('btn_area')}>
                <button type="button" className={cx('btn_make')} onClick={handleClickSubmit}>
                  만들기
                </button>
              </div>
            </div>
            <div className={cx('pc_wrapper')}>
              <div className={cx('preview_group')}>
                <div className={cx('preview_area')}>
                  <div className={cx('create_title')}>
                    미리보기
                  </div>
                  <div className={cx('preview_box')}>
                    <div className={cx('profile_group')}>
                      <div className={cx('thumb_box')}>
                        <span className={cx('thumb_inner', 'collection_img')}>
                          <img alt="" src={baseInfo?.collection.filter(item => item.collection_id === selectedCollection)[0]?.thumbnail_image || ''} />
                        </span>
                        <span className={cx('thumb_inner')}>
                          <CircleThumb
                            thumbSrc={userInfo?.simple_profile.thumbnail_image}
                            width={19}
                            height={19}
                            border={1}
                            isOfficial={userInfo?.simple_profile.is_artist}
                          />
                        </span>
                      </div>
                      <div className={cx('author_name')}>
                        {userInfo?.simple_profile.name}
                      </div>
                    </div>
                    <div className={cx('thumb_group')}>
                      <video width="161" className={cx('thumb')} ref={previewVideoRef} autoPlay muted />
                      <img width="161" alt="" className={cx('thumb')} ref={previewImgRef} />
                    </div>
                    <div className={cx('info_group')}>
                      <div className={cx('title_box')}>
                        {name || '아이템 이름을 입력하세요'}
                      </div>
                      <div className={cx('price_box')}>
                        {selectedSaleType === ESaleType.FIXED && (
                          <span className={cx('price')}>{price ? `${price} ${selectedCurrency(currencyType).toUpperCase()}` : '가격을 설정해주세요'}</span>
                        )}
                        {selectedSaleType === ESaleType.TIME && (
                          <span className={cx('price')}>{auctionPrice ? `${auctionPrice} ${timeCurrencyType.toUpperCase()}` : '가격을 설정해주세요'}</span>
                        )}
                        <span className={cx('count')}>{`1/${totalCount || 1}`}</span>
                      </div>
                      <div className={cx('market_box')}>
                        {SaleType[selectedSaleType]}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          {/* 컬렉션 만들기 레이어 */}
          {showMakeCollectionLayer && (
            <LayerContainer onClose={handleCloseMakeCollection} useDimmedColor={true}>
              <Layer title={'컬렉션 만들기'} buttonText={'컬렉션 만들기'} onClickButton={handleSubmitMakeCollection}>
                <div className={cx('collection_make')}>
                  <div className={cx('cover_wrap')}>
                    {collectionCoverImage && (
                      <img src="" alt="" ref={collectionCoverImageRef} />
                    )}
                  </div>
                  <div className={cx('thumb_wrap')}>
                    <div className={cx('thumb_box')}>
                      {collectionImage && (
                        <img src="https://blog.kakaocdn.net/dn/kT9Ak/btqKBOnHx3T/xS7HfATinY7sH8AnVwKY70/img.png" width="60" height="60" alt="" className={cx('thumb')} ref={collectionImageRef} />
                      )}
                    </div>
                    <div className={cx('input_box')}>
                        <div className={cx('guide')}>프로필 이미지는 PNG, GIF, JPG 1200 * 300 해상도에 최적화 되어있습니다</div>
                        <div className={cx('guide_cover')}>커버 이미지는 PNG, GIF, JPG 4098 * 520 해상도에 최적화 되어있습니다</div>
                      <InputImage title={'프로필 선택'} imageRef={collectionImageRef} setImage={setCollectionImage} limitFileSize={10} fileTypes={['png', 'gif', 'jpg', 'jpeg']} fileSize={{ min: 300, max: 1200 }} />
                      <InputImage title={'커버 선택'} imageRef={collectionCoverImageRef} setImage={setCollectionCoverImage} limitFileSize={10} fileTypes={['png', 'gif', 'jpg', 'jpeg']} fileSize={{ min: 520, max: 4098 }} />
                      {inputCollectionError.inputCollectionProfile && <div className={cs('input_validate_message')}>프로필 이미지를 선택해 해주세요</div>}
                      {inputCollectionError.inputCollectionCover && <div className={cs('input_validate_message')}>커버 이미지를 선택해 해주세요</div>}
                    </div>
                  </div>
                  <div className={cx('collection_wrap')}>
                    <strong className={cx('title')}>컬렉션 이름</strong>
                    <div className={cx('input_container', checkDuplicate.duplicate && 'duplicate', checkDuplicate.checked && 'checked')}>
                      <div className={cx('input_wrapper')}>
                        <Input className={cx(inputCollectionError.inputCollectionNameCheck ? 'validate_input' : 'input')} placeholder={'컬렉션 이름'} onChange={handleChangeLayerTitle} value={collectionTitle} />
                        {inputCollectionError.inputCollectionName && <div className={cs('input_validate_message')}>컬렉션 이름은 100자 이하이어야 합니다</div>}
                        <span className={cx('icon', 'duplicate_icon')}>❗️</span>
                        <span className={cx('icon', 'checked_icon')}>✔️</span>
                      </div>
                      <button type="button" className={inputCollectionError.inputCollectionNameCheck? cx('validate_duplicate_check') : cx('duplicate_check')} onClick={handleClickDuplicate}>중복 체크</button>
                    </div>
                    {inputCollectionError.inputCollectionNameCheck && <div className={cs('input_validate_message')}>중복 체크를 해주세요</div>}
                  </div>
                  <div className={cx('collection_wrap')}>
                    <strong className={cx('title')}>컬렉션 기호</strong>
                    <Input className={cx(inputCollectionError.inputCollectionSymbol ? 'validate_input' : 'input')}placeholder={'컬렉션 기호'} onChange={e => setCollectionToken(e.target.value)} value={collectionToken} />
                    {inputCollectionError.inputCollectionSymbol && <div className={cs('input_validate_message')}>특수문자 제외 대/소문자 + 숫자, 길이는 3자 이상, 20자 이하이어야 합니다</div>}
                  </div>
                  <div className={cx('collection_wrap')}>
                    <strong className={cx('title')}>설명<span className={cx('optional')}>(선택사항)</span></strong>
                    <textarea name="collection_description" id="collection_description" className={cx('textarea')} cols={30} rows={1} placeholder="컬렉션 설명을 입력해주세요. 컬렉션 생성 원치 않을 경우에는 무료 메타레어 싱글 또는 멀티 컬렉션에서 업로딩 가능" disabled={isResalePage} ref={collectionDescRef} onChange={handleChangeLayerDesc}>
                    </textarea>
                  </div>
                  <div className={cx('collection_wrap')}>
                    <strong className={cx('title')}>컬렉션 URL</strong>
                    <div className={cx('url')}>metarare.com/collection/{collectionTitle}</div>
                  </div>
                </div>
              </Layer>
            </LayerContainer>
          )}
          {showCollectionCompleteLayer && (
            <LayerContainer onClose={() => setShowCollectionCompleteLayer(false)} useDimmedColor={true}>
              <Layer title={'컬렉션 생성 완료'} buttonText={'트렌젝션 확인하기'} onClickButton={handleClickTransaction}>
                <HashBox address={StringUtil.summaryWalletAddress(collectionHash)} />
              </Layer>
            </LayerContainer>
          )}
          {showCompleteLayer && (
            <LayerContainer onClose={handleCloseCompleteLayer} useDimmedColor={true}>
              <Layer title={'아이템 만들기'} buttonText={'아이템 보러가기'} onClickButton={handleClickMakeItem}>
                <p className={cx('make_item_wrap')}>
                  성공적으로 <strong>‘{name}’</strong> 을 만들었습니다! <br />
                  지금 바로 확인해보세요
                </p>
              </Layer>
            </LayerContainer>
          )}
        </>
      </LoginContainer>
    </div >
  );
};

export default Create;
