import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchPerson } from '../../store/features/peopleSlice';
import { useResponsive } from '@farfetch/react-context-responsive';

import JKLatencyBadge from '../profile/JKLatencyBadge';
import JKProfileSidePanel from '../profile/JKProfileSidePanel';
import JKProfileAvatar from '../profile/JKProfileAvatar';
import PropTypes from 'prop-types';

function JKSessionUser({ user }) {
  const dispatch = useDispatch();
  const latencyData = useSelector(state => state.latency.latencies.find(l => l.user_id === user.id));
  const [showSidePanel, setShowSidePanel] = useState(false);
  const { greaterThan } = useResponsive();

  const toggleMoreDetails = async e => {
    e.preventDefault();
    try {
      await dispatch(fetchPerson({ userId: user.id })).unwrap();
    } catch (error) {
      console.log(error);
    }

    setShowSidePanel(prev => !prev);
  };
  return (
    <>
      {!greaterThan.sm ? (
        <div className="d-flex flex-row justify-content-between">
          <div className="avatar avatar-sm">
            <JKProfileAvatar url={user.photo_url} />
          </div>
          <div className="ml-2 ms-2" style={{ width: '70%'}}>
            <a href="/#" onClick={toggleMoreDetails}>
              {user.name}
            </a>
          </div>
          <div className="ml-2 ms-2" style={{ marginRight: 'auto'}}>
            <JKLatencyBadge latencyData={latencyData} />
          </div>
        </div>
      ) : (
        <div className="d-flex flex-row align-items-center mb-1 fs-0">
          <div className="avatar avatar-xl">
            <JKProfileAvatar url={user.photo_url} />
          </div>
          <div className="ml-2 ms-2">
            <strong>{user.name}</strong>
          </div>
        </div>
      )}
      <JKProfileSidePanel show={showSidePanel} user={user} toggle={toggleMoreDetails} />
    </>
  );
}

JKSessionUser.propTypes = { user: PropTypes.object.isRequired };

export default JKSessionUser;
