import React, { useEffect, useMemo } from 'react'
import PropTypes from 'prop-types'
import { ProfileContainer } from './Profile.styled'
import ProfileCard from '../ProfileCard/ProfileCard'
import ProfileOffers from './ProfileOffers/ProfileOffers'
import { useDispatch, useSelector } from 'react-redux'
import { selectUserId } from '../../store/selectors/loginSelectors'
import { useRouteMatch } from 'react-router-dom'
import { fetchProfile } from '../../store/actions/profile/profileActions'
import { fetchProfileOffers } from '../../store/actions/offers/offersActions'

const Profile = () => {
  const userId = useSelector(selectUserId);
  const dispatch = useDispatch();
  const routeMatch = useRouteMatch();
  const idProfile = routeMatch.params.idProfile;
  useEffect(() => {
    if (idProfile?.length > 0) {
      dispatch(fetchProfile(idProfile));
      dispatch(fetchProfileOffers(idProfile))
    }
  }, [idProfile]);
  const isMyProfile = useMemo(() => {
    if (userId === idProfile) {
      return true;
    }
    return false;
  }, [userId, idProfile])
  return (
    <ProfileContainer>
        <ProfileCard isMyProfile={isMyProfile}/>
        <ProfileOffers isMyProfile={isMyProfile}/>
    </ProfileContainer>
  )
}

Profile.propTypes = {
    children: PropTypes.node,
}

export default Profile