import { type FC } from 'react';
import { useFormContext } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';

import { logEvent } from 'src/config/amplitude';
import { useAuth } from 'src/contexts/JWTContext';
import { CONVERSATION_TYPE } from 'src/pages/dashboard/Conversations/constants';
import {
  type Channel,
  type ConversationUser,
  type SelectConversationOrUserPayload,
} from 'src/pages/dashboard/Conversations/types';
import { EventName } from 'src/types/amplitude';

import { useOpenConversation } from '../../hooks/useConversationsQueries';
import { conversationsRoutes } from '../../routes';
import ConversationsAndUsersList from '../shared/ConversationsAndUsersList';

const ConversationsSearch: FC = () => {
  const navigate = useNavigate();
  const { user } = useAuth();
  const { watch, setValue } = useFormContext();

  const filter = watch('filter');

  const openConversation = useOpenConversation();

  const clearFilter = () => setValue('filter', '');

  const handleSelectConversation = (conversation: Channel): void => {
    clearFilter();
    const isGroupConversation = Boolean(conversation?.is_channel);
    const eventProperties = {
      userId: user?.id.toString(),
      conversationType: isGroupConversation
        ? CONVERSATION_TYPE.GROUP
        : CONVERSATION_TYPE.INDIVIDUAL,
      conversationID: conversation.id,
    };
    logEvent(EventName.CHATS_2_CONVERSATION_OPENED, eventProperties);
    navigate(conversationsRoutes.thread.detail(conversation.id));
  };

  const handleSelectMember = (member: ConversationUser) => {
    const users = [member.id];
    openConversation.mutate({ users });
    clearFilter();
  };

  const handleSelect = ({
    conversation,
    user,
  }: SelectConversationOrUserPayload) => {
    if (conversation) handleSelectConversation(conversation);
    if (user) handleSelectMember(user);
  };

  return (
    <ConversationsAndUsersList
      filter={filter}
      onSelect={handleSelect}
    />
  );
};

export default ConversationsSearch;
