import React, { useEffect } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { useAuth } from '../../context/UserAuth';
import { useDispatch, useSelector } from 'react-redux';
import { fetchUserLatencies } from '../../store/features/latencySlice';
import { toast } from 'react-toastify';
import { useTranslation } from 'react-i18next';
import { useResponsive } from '@farfetch/react-context-responsive';
import PropTypes from 'prop-types';
import { Row, Col, Button } from 'reactstrap';

import jkCustomUrlScheme from '../../helpers/jkCustomUrlScheme';

import JKUserLatencyBadge from '../profile/JKUserLatencyBadge';
import JKSessionUser from './JKSessionUser';

function JKSession({ session }) {
  const { currentUser } = useAuth();
  const dispatch = useDispatch();
  const { t } = useTranslation();
  const { greaterThan } = useResponsive();

  useEffect(() => {
    const participantIds = session.participants.map(p => p.user.id);
    const options = { currentUserId: currentUser.id, participantIds };
    dispatch(fetchUserLatencies(options));
  }, []);

  function joinSession() {
    if (session.musician_access && session.approval_required) {
      toast.info(t('list.alerts.join_request_sent', { ns: 'sessions' }));
    } else {
      const q = `joinSessionId~${session.id}`;
      const urlScheme = jkCustomUrlScheme('findSession', q);
      window.open(urlScheme);
      return;
    }
  }

  const sessionDescription = session => {
    if (session.description) {
      return session.description;
    } else if (session.musician_access && !session.approval_required) {
      return t('list.descriptions.public_open_session', { ns: 'sessions' });
    } else if (session.musician_access && session.approval_required) {
      return t('list.descriptions.private_session', { ns: 'sessions' });
    } else if (!session.musician_access && !session.approval_required) {
      return t("list.descriptions.rsvp_session", { ns: "sessions" });
    }
  };

  const invitedNote = session => {
    if (session.invitations.find(i => i.receiver_id === currentUser.id)) {
      return t('list.notes.invited', { ns: 'sessions' });
    }
  };

  const hasFriendNote = session => {
    if (session.participants.find(p => p.user.is_friend)) {
      return  t('list.notes.has_friend', { ns: 'sessions' })
    }
  };

  const actionButtons = () => {
    return (
      <div>
        <Button onClick={joinSession} color="primary" data-testid="joinBtn" className="btn-join mr-1 mb-1">
          <FontAwesomeIcon icon="arrow-right" transform="shrink-4 down-1" className="mr-1" />
        </Button>
        <Button
          color="primary"
          onClick={() =>
            console.log(`TODO: If the user
clicks this button, we open an audio stream using Icecast server to let the user hear what’s being played currently in the session`)
          }
        >
          <FontAwesomeIcon icon="volume-up" transform="shrink-4 down-1" className="mr-1" />
        </Button>
      </div>
    );
  };

  return (
    <>
      {greaterThan.sm ? (
        <tr key={session.id}>
          <td>
            <div>
              <u>
                <small>
                  <strong>{invitedNote(session)}</strong>
                </small>
              </u>
            </div>
            <div>
              <u>
                <small>{hasFriendNote(session)}</small>
              </u>
            </div>
            <div>{sessionDescription(session)}</div>
          </td>
          <td>
            {session.participants.map(participant => (
              <JKSessionUser key={participant.id} user={participant.user} />
            ))}
          </td>
          <td>
            <div>
              {session.participants.map(participant => (
                <JKUserLatencyBadge user={participant.user} />
              ))}
            </div>
          </td>
          <td>
            {session.participants.map(participant => (
              <div className="d-flex flex-row" key={participant.id} data-testid={`Participant${participant.id}Tracks`}>
                {participant.tracks.map(track => (
                  <div key={track.id}>{track.instrument}</div>
                ))}
              </div>
            ))}
          </td>
          <td>{actionButtons()}</td>
        </tr>
      ) : (
        <Row>
          <Col>
            <div>
              <u>
                <small>
                  <strong>{invitedNote(session)}</strong>
                </small>
              </u>
            </div>
            <div>
              <u>
                <small>{hasFriendNote(session)}</small>
              </u>
            </div>
            <div>{sessionDescription(session)}</div>
            <div className="d-flex flex-row justify-content-between mt-3">
              <div className="ml-2 ms-2">
                <h5>{t('list.header.musicians', { ns: 'sessions'})}</h5>
              </div>
              <div className="ml-2 ms-2">
                <strong>{t('list.header.latency', { ns: 'sessions'})}</strong>
              </div>
            </div>
            <div>
              {session.participants.map(participant => (
                <JKSessionUser key={participant.id} user={participant.user} />
              ))}
            </div>
            <div className="mt-4 d-flex flex-row justify-content-center">{actionButtons()}</div>
          </Col>
        </Row>
      )}
    </>
  );
}

JKSession.propTypes = { session: PropTypes.object.isRequired };

export default JKSession;
