import { type FC, memo } from 'react';
import { Link as RouterLink } from 'react-router-dom';

import { IconSearch } from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import IconButton from '@material-hu/mui/IconButton';
import Link from '@material-hu/mui/Link';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { useAuth } from 'src/contexts/JWTContext';
import useCommunityFeature from 'src/hooks/useCommunityFeature';
import useFeatureFlag from 'src/hooks/useFeatureFlag';
import { BUNNY_IMAGE_CLASSES } from 'src/pages/dashboard/Conversations/constants';
import { useSearchHighlight } from 'src/pages/dashboard/Conversations/contexts/SearchHighlightContext';
import {
  type Channel,
  type Member,
} from 'src/pages/dashboard/Conversations/types';
import {
  getIsSelfConversation,
  getMembersNamesOfGroup,
  getOtherUserStatus,
} from 'src/pages/dashboard/Conversations/utils';
import { profileRoutes } from 'src/pages/dashboard/profile/routes';
import { MAX_CALL_PARTICIPANTS } from 'src/pages/dashboard/videoCall/constants';
import { CommunityFeature } from 'src/types/communityFeatures';
import { FeatureFlags } from 'src/types/featureFlags';
import { type MartyVideoCallResponse } from 'src/types/stream';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getInitials } from 'src/utils/userUtils';

import { useGetPinnedMessages } from '../../../hooks/useConversationsQueries';
import LazySecureImage from '../../shared/LazySecureImage';

import CallButtons from './CallButtons';
import PinnedMessages from './PinnedMessages';
import SearchInput from './SearchInput';

type ConversationThreadToolbarProps = {
  members: Member[];
  conversation: Channel;
  onOpenGroupInfo?: () => void;
  activeVideoCall?: MartyVideoCallResponse;
};

const ConversationThreadToolbar: FC<ConversationThreadToolbarProps> = props => {
  const { members, conversation, onOpenGroupInfo, activeVideoCall } = props;
  const { t } = useLokaliseTranslation('chat');
  const { user: loggedUser, instance } = useAuth();
  const canCall = useCommunityFeature(CommunityFeature.VIEW_CALL);
  const { isSearchOpen, openSearch } = useSearchHighlight();
  const isSearchEnabled = useFeatureFlag(
    FeatureFlags.CHATS_V2_SEARCH_IN_CHAT_WEB,
  );

  const enabledPinMessage = useFeatureFlag(FeatureFlags.CHATS_V2_PIN_MESSAGE);
  const { data: pinnedMessages } = useGetPinnedMessages({
    channelId: conversation.id,
    enabled: enabledPinMessage,
  });
  const isGroupConversation = conversation?.is_channel || false;
  const { num_members = 0 } = conversation;
  const isSelfConversation = getIsSelfConversation(
    Number(conversation.hu_data?.other_membership?.user?.id),
    loggedUser?.id,
    isGroupConversation,
  );

  const { isDeleted, isInactive, otherMember } = getOtherUserStatus({
    isGroupConversation: isGroupConversation && !isSelfConversation,
    conversation,
  });

  const isCallEnabled =
    (instance?.allowChatCall || canCall) &&
    num_members <= MAX_CALL_PARTICIPANTS &&
    num_members > 1;

  if (isGroupConversation) {
    return (
      <Stack
        key={conversation.id}
        sx={{
          backgroundColor: theme =>
            theme.palette.new.background.layout.tertiary,
          flexDirection: 'column',
        }}
      >
        <Stack
          sx={{
            cursor: 'pointer',
            height: '72px',
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
            px: 3,
            gap: 1,
          }}
        >
          <Stack
            onClick={onOpenGroupInfo}
            sx={{
              width: '100%',
              flexDirection: 'row',
              alignItems: 'center',
              gap: 2,
            }}
          >
            <LazySecureImage
              url={conversation?.hu_data?.picture_url || ''}
              isAvatar
              imageClass={BUNNY_IMAGE_CLASSES.AVATAR}
            />
            <Stack sx={{ display: 'grid' }}>
              <Typography
                variant="globalM"
                fontWeight="fontWeightSemiBold"
                sx={{
                  textAlign: 'flex-start',
                  whiteSpace: 'nowrap',
                }}
              >
                {conversation?.name}
              </Typography>
              <Typography
                variant="globalXS"
                sx={{
                  textAlign: 'flex-start',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                }}
              >
                {getMembersNamesOfGroup(
                  members,
                  conversation?.num_members,
                  loggedUser?.id,
                  t,
                )}
              </Typography>
            </Stack>
          </Stack>
          {isCallEnabled && (
            <CallButtons
              chatId={conversation.id}
              canCall={canCall}
              activeVideoCall={activeVideoCall}
              isGroupCall
            />
          )}
          {isSearchEnabled && (
            <IconButton onClick={openSearch}>
              <IconSearch />
            </IconButton>
          )}
        </Stack>
        {isSearchOpen && (
          <SearchInput
            channelId={conversation.id}
            isSearchEnabled={isSearchEnabled}
          />
        )}
        <Divider />
        {enabledPinMessage && pinnedMessages && pinnedMessages.length > 0 && (
          <PinnedMessages pinnedMessages={pinnedMessages} />
        )}
      </Stack>
    );
  }

  return (
    <Stack
      key={conversation.id}
      sx={{
        backgroundColor: theme => theme.palette.new.background.layout.tertiary,
        flexDirection: 'column',
      }}
    >
      <Stack
        sx={{
          height: '72px',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          px: 3,
        }}
      >
        {otherMember?.id && (
          <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 2 }}>
            <LazySecureImage
              alt={otherMember.id.toString()}
              isAvatar
              imageClass={BUNNY_IMAGE_CLASSES.AVATAR}
              url={otherMember.picture_asset_url}
              avatarProps={{
                color: isDeleted ? 'error' : 'default',
                text:
                  !isDeleted || !isInactive
                    ? getInitials(
                        `${otherMember.first_name} ${otherMember.last_name}`,
                      )
                    : undefined,
              }}
            />
            <Link
              component={RouterLink}
              to={profileRoutes.profile(otherMember.id)}
              sx={{
                textDecoration: 'none',
                pointerEvents: isDeleted ? 'none' : 'auto',
              }}
            >
              <Typography
                variant="globalM"
                fontWeight="fontWeightSemiBold"
              >
                {`${otherMember.first_name} ${otherMember.last_name}${isSelfConversation ? ` (${t('you')})` : ''}`}
              </Typography>
            </Link>
          </Stack>
        )}
        <Stack sx={{ flexDirection: 'row' }}>
          {isCallEnabled && (
            <CallButtons
              chatId={conversation.id}
              canCall={canCall}
              activeVideoCall={activeVideoCall}
              isGroupCall={false}
            />
          )}
          {isSearchEnabled && (
            <IconButton onClick={openSearch}>
              <IconSearch />
            </IconButton>
          )}
        </Stack>
      </Stack>
      {isSearchOpen && (
        <SearchInput
          channelId={conversation.id}
          isSearchEnabled={isSearchEnabled}
        />
      )}
      {enabledPinMessage && pinnedMessages && pinnedMessages.length > 0 && (
        <>
          <Divider />
          <PinnedMessages pinnedMessages={pinnedMessages} />
        </>
      )}
    </Stack>
  );
};

export default memo(ConversationThreadToolbar);
