import {
  CallMode,
  type Participant,
  type ParticipantList,
  type UserTypeStream,
} from 'src/types/stream';
import { type MeUser } from 'src/types/user';

import { type LokaliseTFunction } from './i18n';

export const getCorrectLabelButton = (
  t: LokaliseTFunction,
  isLoadingGoLive: boolean,
  isStreaming: boolean,
) => {
  if (isLoadingGoLive) {
    return t('STARTING');
  }
  return t(isStreaming ? 'END_STREAM' : 'START_STREAM');
};

export const getCorrectTime = (time: number) => (time < 10 ? `0${time}` : time);

export const getUserId = (
  role?: UserTypeStream,
  userHumand?: MeUser | null,
) => {
  if (role) {
    return `${userHumand?.id?.toString()}-${role}`;
  }
  return userHumand?.id?.toString();
};

export const getUrl = ({
  id,
  providerCallId,
  emitCall,
  initAndJoinCall,
  lobby,
}: {
  id: string;
  providerCallId: string;
  emitCall?: boolean;
  initAndJoinCall?: boolean;
  lobby?: boolean;
}) => {
  const baseUrl = `${window.location.origin}/call/${id}/${providerCallId}`;

  if (lobby) return baseUrl;

  if (emitCall && typeof initAndJoinCall === 'boolean') {
    const callMode = initAndJoinCall ? CallMode.GROUP : CallMode.SINGLE;
    return `${baseUrl}?new=${callMode}`;
  }

  return `${baseUrl}?new=false`;
};

const firstLetterUpper = (word: string) => word.charAt(0).toUpperCase();

export const getParticipantsForList = (
  participant: Participant,
  participantsGroup: ParticipantList[],
) => {
  const firstLetter = firstLetterUpper(participant.fullName);

  const existingGroup = participantsGroup.find(
    group => group.character === firstLetter,
  );

  if (existingGroup) {
    const participantExists = existingGroup.participants.some(
      p => p.id === participant.id,
    );

    if (!participantExists) {
      existingGroup.participants.push(participant);
    }
  } else {
    participantsGroup.push({
      character: firstLetter,
      participants: [participant],
    });
  }

  return participantsGroup;
};
