import { type FC, Fragment, useState } from 'react';

import {
  IconChevronDown,
  IconZoomExclamation,
} from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import ListItemButton from '@material-hu/mui/ListItemButton';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCheckbox from '@material-hu/components/design-system/Checkbox/Checkbox';

import { useAuth } from 'src/contexts/JWTContext';
import usePermissions from 'src/hooks/usePermissions';
import ThreadInfiniteList from 'src/pages/dashboard/Conversations/components/shared/ThreadInfiniteList';
import { BUNNY_IMAGE_CLASSES } from 'src/pages/dashboard/Conversations/constants';
import {
  type Channel,
  type ConversationUser,
  type SelectConversationOrUserPayload,
} from 'src/pages/dashboard/Conversations/types';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { UserPermissions } from 'src/utils/permissions';
import { getFullName, getInitials } from 'src/utils/userUtils';

import { List } from 'src/components/list';

import {
  useConversationList,
  useGetPinnedCount,
  useGetUserList,
} from '../../hooks/useConversationsQueries';
import ConversationItem from '../Conversations/ConversationItem';
import ConversationsSkeleton from '../Conversations/ConversationsSkeleton';

import InfoMessage from './InfoMessage';
import LazySecureImage from './LazySecureImage';

const { CHATS_V2_CREATE_CONVERSATION } = UserPermissions;

type ConversationsAndUsersListProps = {
  filter: string;
  moreLimitConversations?: boolean;
  withCheckbox?: boolean;
  withInternalDetailsConversations?: boolean;
  disabledCheckbox?: boolean;
  onSelect: (payload: SelectConversationOrUserPayload) => void;
  selectedUsers?: ConversationUser[];
  selectedConversations?: Channel[];
};

const ConversationsAndUsersList: FC<ConversationsAndUsersListProps> = props => {
  const {
    filter,
    selectedConversations = [],
    selectedUsers = [],
    withInternalDetailsConversations = true,
    withCheckbox = false,
    disabledCheckbox = false,
    onSelect,
  } = props;
  const { t } = useLokaliseTranslation('chat');
  const theme = useTheme();
  const { user: loggedUser } = useAuth();
  const { hasAll: canCreateConversation = true } = usePermissions([
    CHATS_V2_CREATE_CONVERSATION,
  ]);
  const {
    conversations,
    hasNextPage,
    fetchNextPage,
    isFetchingNextPage,
    isLoading: isLoadingConversations,
  } = useConversationList(filter);
  const pinnedConversationsCount = useGetPinnedCount();
  const { members, ...usersListProps } = useGetUserList({
    query: filter,
    enabled: canCreateConversation,
  });

  const isLoadingSearch = usersListProps.isLoading || isLoadingConversations;

  const handleSelect = (payload: SelectConversationOrUserPayload) => {
    const { conversation, user } = payload;
    if (user) {
      const existingConversation = conversations.find(
        conv => conv.is_im && conv.user === user.id,
      );
      if (existingConversation) {
        onSelect({ conversation: existingConversation });
      } else {
        onSelect({ user });
      }
    }
    if (conversation) {
      onSelect({ conversation });
    }
  };

  return (
    <Stack sx={{ overflow: isLoadingSearch ? 'hidden' : 'auto', flex: 1 }}>
      {isLoadingSearch && <ConversationsSkeleton />}
      {!isLoadingSearch && (
        <>
          {!!conversations.length && (
            <>
              <Typography
                variant="globalM"
                fontWeight="fontWeightSemiBold"
                sx={{ mt: 3, px: 2 }}
              >
                {t('chats')}
              </Typography>

              <List isSuccess={!!conversations?.length}>
                {conversations.map(conversation => (
                  <ConversationItem
                    key={conversation.id}
                    conversation={conversation}
                    onClick={handleSelect}
                    pinnedConversationsCount={pinnedConversationsCount}
                    selectedConversations={selectedConversations}
                    selectedUsers={selectedUsers}
                    disabledCheckbox={disabledCheckbox}
                    withCheckbox={withCheckbox}
                    withInternalDetails={withInternalDetailsConversations}
                  />
                ))}
              </List>
              {hasNextPage && (
                <Button
                  sx={{ justifyContent: 'space-between', mt: 1, mx: 2 }}
                  endIcon={
                    <IconChevronDown
                      color={theme.palette.new.text.neutral.brand}
                    />
                  }
                  loading={isFetchingNextPage}
                  onClick={() => fetchNextPage()}
                >
                  <Typography
                    variant="globalXS"
                    fontWeight="fontWeightSemiBold"
                    color={theme.palette.new.text.neutral.brand}
                  >
                    {t('show_more')}
                  </Typography>
                </Button>
              )}
            </>
          )}
          {!!members.length && (
            <>
              <Typography
                variant="globalM"
                fontWeight="fontWeightSemiBold"
                sx={{ mt: 3, px: 2 }}
              >
                {t('users')}
              </Typography>
              <ThreadInfiniteList
                isSuccess={!!members?.length}
                isEmpty={!members?.length}
                hasNextPage={usersListProps.hasNextPage || false}
                isLoading={usersListProps.isLoading}
                listWrapperProps={usersListProps}
              >
                {members.map(member => {
                  const isSelf = Number(member.id) === loggedUser?.id;
                  const isCheckedConversation = selectedConversations.some(
                    conversation =>
                      conversation.is_im && conversation.user === member.id,
                  );
                  const isChecked =
                    selectedUsers?.some(
                      selectedUser => selectedUser.id === member.id,
                    ) || isCheckedConversation;
                  const isDisabledByLimit = disabledCheckbox && !isChecked;

                  return (
                    <Fragment key={member.id}>
                      <ListItemButton
                        onClick={() =>
                          !isDisabledByLimit && handleSelect({ user: member })
                        }
                        sx={{
                          p: 0,
                          px: 2,
                        }}
                      >
                        <Stack
                          sx={{
                            my: 2,
                            flexDirection: 'row',
                            gap: 1,
                            width: '100%',
                            alignItems: 'center',
                          }}
                        >
                          {withCheckbox && (
                            <HuCheckbox
                              sx={{ zIndex: 0, mr: 1 }}
                              label=""
                              disabled={isDisabledByLimit}
                              checked={isChecked}
                              onClick={e => {
                                e.stopPropagation();
                                if (!isDisabledByLimit)
                                  handleSelect({ user: member });
                              }}
                            />
                          )}
                          <LazySecureImage
                            url={member.hu_data.member.picture_asset_url}
                            isAvatar
                            imageClass={BUNNY_IMAGE_CLASSES.AVATAR}
                            avatarProps={{
                              text: getInitials(
                                getFullName({
                                  firstName: member.hu_data.member.first_name,
                                  lastName: member.hu_data.member.last_name,
                                }),
                              ),
                            }}
                          />
                          <Typography
                            variant="globalS"
                            fontWeight="fontWeightSemiBold"
                          >
                            {`${member.hu_data?.member.first_name} ${member.hu_data?.member.last_name}${isSelf ? ` (${t('you')})` : ''}`}
                          </Typography>
                        </Stack>
                      </ListItemButton>
                      <Divider sx={{ mx: 2 }} />
                    </Fragment>
                  );
                })}
              </ThreadInfiniteList>
            </>
          )}
          {!members.length && !conversations.length && (
            <InfoMessage
              title={t('search.not_found_title')}
              subtitle={t('search.not_found_subtitle')}
              Icon={IconZoomExclamation}
            />
          )}
        </>
      )}
    </Stack>
  );
};

export default ConversationsAndUsersList;
