import { ICharacterPartyShared, isMobileOrTablet } from '@rpg-engine/shared';
import React from 'react';
import styled from 'styled-components';
import { uiColors } from '../../../constants/uiColors';
import { PartyManagerRow } from './PartyManagerRows';

export interface IPartyManagerProps {
  partyRows: ICharacterPartyShared | null;

  userId: string;
  onRemovePlayer: (id: string) => void;
  onChangeLeader: (id: string) => void;
}

export const PartyManager: React.FC<IPartyManagerProps> = ({
  partyRows,
  userId,
  onRemovePlayer,
  onChangeLeader,
}) => {
  const invitationActionText = isMobileOrTablet() ? 'Tap' : 'Right click';

  const sortedMembers =
    partyRows?.leader && partyRows?.members
      ? [partyRows.leader, ...partyRows.members].sort((a, b) =>
          a._id === partyRows.leader._id
            ? -1
            : b._id === partyRows.leader._id
            ? 1
            : 0
        )
      : [];

  return (
    <>
      <RowsWrapper className="partyRows">
        {partyRows && sortedMembers.length ? (
          sortedMembers.map(partyRow => (
            <PartyManagerRow
              userId={userId}
              key={partyRow._id}
              charName={partyRow.name}
              charClass={partyRow.class}
              id={partyRow._id}
              isLeader={partyRow._id === partyRows.leader._id}
              leaderId={partyRows.leader._id}
              onRemovePlayer={() => onRemovePlayer(partyRow._id)}
              onChangeLeader={() => onChangeLeader(partyRow._id)}
            />
          ))
        ) : (
          <NotInParty>
            <p>You're not in a party.</p>
            <p>
              Tip: <YellowText>{invitationActionText}</YellowText> on a player
              to invite them.
            </p>
          </NotInParty>
        )}
      </RowsWrapper>
    </>
  );
};

const RowsWrapper = styled.div`
  width: 100%;
  max-height: 300px;
  overflow-y: auto;
  overflow-x: hidden;
`;

const YellowText = styled.span`
  color: ${uiColors.yellow} !important;
`;

const NotInParty = styled.h1`
  font-size: 0.6rem;
  margin: auto;
`;
