import React, { useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import PropTypes from 'prop-types';
import styled from '@emotion/styled';
import ArrowBackIosIcon from '@mui/icons-material/ArrowBackIos';

const Header = ({ handleSubmitInputs, buttonType }) => {
  const history = useHistory();
  const { pathname: currentPath } = useLocation();

  useEffect(() => {
    const fromPath=  history.location.state === undefined ? '/'

    // history.push({
    //   state: { from: from || '/', current: currentPath },
    // });
  }, []);

  const goBack = () => {
    // 얘가 핵심인데 어디에 저장하지? => 렌더 되면서 지워지는구나
    const prevPath = history.location.state.from || '/';

    const locationState = history.location.state;
    const { current: currentPathName } = locationState;

    history.push(prevPath, {
      ...history.location.state,
      from: currentPathName,
    });
  };

  // console.log(history.location.state);

  return (
    <>
      {buttonType === 'finish' ? (
        <PageHeaderWithFinish>
          <div>
            <ArrowBackIosIcon onClick={goBack} />
          </div>
          <button type="button" onClick={handleSubmitInputs}>
            완료
          </button>
        </PageHeaderWithFinish>
      ) : (
        <PageHeader>
          <ArrowBackIosIcon onClick={goBack} />
        </PageHeader>
      )}
    </>
  );
};

export default Header;

Header.defaultProps = {
  buttonType: '',
  handleSubmitInputs: () => {},
};

Header.propTypes = {
  buttonType: PropTypes.string,
  handleSubmitInputs: PropTypes.func,
};

const PageHeader = styled.div`
  border-bottom: 1px solid #c4c4c4;
  color: #89cff0;
  height: 2.625rem;
  left: 0;
  padding-left: 1rem;
  padding-top: 0.75rem;
  position: absolute;
  top: 0;
  width: 100%;

  svg {
    cursor: pointer;
  }
`;

const PageHeaderWithFinish = styled.div`
  display: flex;
  border-bottom: 1px solid #c4c4c4;
  color: #89cff0;
  height: 2.625rem;
  left: 0;
  padding: 0.5rem 1rem;
  justify-content: space-between;
  position: absolute;
  top: 0;
  width: 100%;
  align-content: center;

  svg {
    cursor: pointer;
  }
`;

// current: main, from: '', state: ''

// 다음 페이지로 이동

// 1. useEffect
// current: 설정, from: 공백, state: 공백

// 2. goBack
// 2-1 from -> state에 저장
//   - 문제가 발생한다 : from === "" => state : '/'
//   - 문제가 발생 X  : from -> state 로 전달

// 2-2
// current: 설정 -> from: 설정

// 2-3
// state에 있는 주소로 이동.

// 다음 페이지로 간다.
// current: 수정, from: 설정

// from -> state : state = 설정

// current -> from -> from = 수정