import React, { useEffect, useRef, useState } from 'react';
import classNames from 'classnames/bind';
import styles from './ProfileEdit.scss';
import { useDispatch, useSelector } from 'react-redux';
import APIs from '@src/api/APIs';
import { fetchUserInfo } from '@src/store/reducers/UserReducer';
import LoginContainer from '@src/containers/common/LoginContainer';
import URLInfo from '@src/constants/URLInfo';
import InputImage from '@src/components/common/InputImage';

const cx = classNames.bind(styles);

const ProfileEdit: React.FC = () => {
  const dispatch = useDispatch();
  const { userInfo } = useSelector(store => store.user);

  // 이미지
  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 [name, setName] = useState<string>('');
  const [checkDuplicate, setCheckDuplicate] = useState<{ name: string; checked: boolean; duplicate: boolean }>({ name: '', checked: false, duplicate: false });

  // 소개
  const [desc, setDesc] = useState<string>('');
  const descRef = useRef<HTMLTextAreaElement>(null);

  //트위터 URL
  const [twitter, setTwitter] = useState<string>('');

  useEffect(() => {
    if (userInfo) {
      if (imageRef.current) {
        imageRef.current.src = userInfo.simple_profile.thumbnail_image;
      }

      if (coverImageRef.current) {
        coverImageRef.current.src = userInfo.simple_profile.cover_image;
      }

      setName(userInfo.simple_profile.name);
      setCheckDuplicate({ name: userInfo.simple_profile.name, checked: true, duplicate: false });
      setDesc(userInfo.simple_profile.description);
      setTwitter(userInfo.simple_profile.twitter);
    }
  }, [userInfo]);

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

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

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

    if (!descEl) {
      return;
    }

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

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

  const handleClickUpdate = async () => {
    if (!checkDuplicate.checked || checkDuplicate.name !== name) {
      alert('이름을 중복체크 하세요.');
      return;
    }

    if (!name) {
      alert('디스플레이 네임을 입력해주세요.');
      return;
    }

    const json = {
      name,
      description: desc,
      twitter
    };

    const formData = new FormData();

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

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

    await APIs.changeUserProfile(formData).then(() => {
      alert('변경 성공!');
      dispatch(fetchUserInfo());
    });
  };

  return (
    <div className={cx('profile_edit')}>
      <strong className={cx('title')}>프로필편집</strong>
      <LoginContainer containerStyle={{ padding: '20px' }}>
        <>
          <div className={cx('file_area')}>
            <div className={cx('cover_area')}>
              <img src="" alt="" ref={coverImageRef} />
            </div>
            <div className={cx('image_area')}>
              <img src="" alt="" ref={imageRef} />
            </div>
            <p className={cx('file_info')}>프로필 이미지는 PNG, GIF, JPG 1200 * 300 해상도에 최적화 되어있습니다</p>
            <p className={cx('file_info_cover')}>커버 이미지는 PNG, GIF, JPG 4098 * 520 해상도에 최적화 되어있습니다</p>
            <div className={cx('file_select_area')}>
              <InputImage title="프로필사진 선택" imageRef={imageRef} setImage={setImage} limitFileSize={10} fileTypes={['jpg', 'jpeg', 'png', 'gif']} fileSize={{ min: 300, max: 1200 }} />
              <InputImage title="커버사진 선택" imageRef={coverImageRef} setImage={setCoverImage} limitFileSize={10} fileTypes={['jpg', 'jpeg', 'png', 'gif']} fileSize={{ min: 520, max: 4098 }} />
            </div>
          </div>
          <div className={cx('contents_area')}>
            <div className={cx('profile_input')}>
              <strong className={cx('input_title')}>디스플레이 네임</strong>
              <div className={cx('input_container', checkDuplicate.duplicate && 'duplicate', checkDuplicate.checked && 'checked')}>
                <div className={cx('input_wrapper')}>
                  <input type="text" className={cx('input')} onChange={handleChangeName} defaultValue={name} />
                  <span className={cx('icon', 'duplicate_icon')}>❗️</span>
                  <span className={cx('icon', 'checked_icon')}>✔️</span>
                </div>
                <button type="button" className={cx('duplicate_check')} onClick={handleClickDuplicate}>중복 체크</button>
              </div>
            </div>
            <div className={cx('profile_input')}>
              <strong className={cx('input_title')}>프로필 URL</strong>
              <input type="text" className={cx('input')} value={`metarare.com/profile/${name}`} disabled={true} />
            </div>
            <div className={cx('profile_input')}>
              <strong className={cx('input_title')}>소개<span className={cx('optional')}>(선택사항)</span></strong>
              <textarea placeholder="소개를 입력하세요" className={cx('textarea')} onChange={e => setDesc(e.target.value)} cols={30} rows={1} ref={descRef} defaultValue={desc} />
            </div>
            <div className={cx('profile_input')}>
              <strong className={cx('input_title')}>나의 포트폴리오 URL<span className={cx('optional')}>(선택사항)</span></strong>
              <input type="text" className={cx('input')} placeholder="나의 포트폴리오 URL을 입력하세요" onChange={e => setTwitter(e.target.value)} defaultValue={twitter} />
            </div>
            <div className={cx('profile_input')}>
              <strong className={cx('input_title')}>이메일</strong>
              <input type="text" className={cx('input')} value={userInfo?.simple_profile.email} disabled={true} />
            </div>
            {!userInfo?.simple_profile.is_artist && (
              <div className={cx('profile_input')}>
                <strong className={cx('input_title')}>작가 신청</strong>
                <a href={URLInfo.registerArtistUrl} target="_blank" className={cx('author_btn')} rel="noreferrer">작가 신청하기</a>
              </div>
            )}
            <div className={cx('btn_area')} onClick={handleClickUpdate}>
              <button type="button" className={cx('update_btn')}>프로필 업데이트</button>
            </div>
          </div>
        </>
      </LoginContainer>
    </div>
  );
};

export default ProfileEdit;
