import { type FC, useEffect } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useNavigate, useParams } from 'react-router-dom';

import { IconX } from '@material-hu/icons/tabler';
import DialogActions from '@material-hu/mui/DialogActions';
import DialogTitle from '@material-hu/mui/DialogTitle';
import Divider from '@material-hu/mui/Divider';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuFormSearch from '@material-hu/components/design-system/Inputs/Search/form';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { AUTO_HIDE_DURATION } from 'src/pages/dashboard/Conversations/constants';
import {
  useForwardMessage,
  useOpenConversation,
} from 'src/pages/dashboard/Conversations/hooks/useConversationsQueries';
import {
  type Channel,
  type ConversationMessage,
  type ConversationUser,
} from 'src/pages/dashboard/Conversations/types';
import { getDescriptionToForwardMessage } from 'src/pages/dashboard/Conversations/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

type MessageForwardProps = {
  title: string;
  onClose: () => void;
  message: ConversationMessage;
};
type ForwardFormValues = {
  filter: string;
  users: ConversationUser[];
  conversations: Channel[];
};

const limitAddMember = 5;

const MessageForward: FC<MessageForwardProps> = props => {
  const { title, onClose, message } = props;
  const { t } = useLokaliseTranslation('chat');
  const { id } = useParams();
  const navigate = useNavigate();
  const { enqueueSnackbar } = useHuSnackbar();
  const openConversation = useOpenConversation();

  const form = useForm<ForwardFormValues>({
    defaultValues: {
      filter: '',
      users: [],
      conversations: [],
    },
  });

  const { watch, setValue } = form;

  const { filter, users, conversations } = watch();

  const countToForwardMessage = users.length + conversations.length;

  useEffect(() => {
    if (countToForwardMessage === limitAddMember) {
      enqueueSnackbar({
        title: t('forward.warning', { count: limitAddMember }),
        variant: 'info',
        autoHideDuration: AUTO_HIDE_DURATION,
      });
    }
  }, [countToForwardMessage]);

  const forwardMessageMutation = useForwardMessage({
    onSuccess: () => {
      if (countToForwardMessage === 1) {
        if (conversations.length > 0) {
          navigate(conversationsRoutes.thread.detail(conversations[0].id));
        } else {
          openConversation.mutate({ users: [users[0].id] });
        }
      }
      onClose();
    },
  });

  const handleSelect = ({
    conversation,
    user,
  }: {
    conversation?: Channel;
    user?: ConversationUser;
  }) => {
    if (user) {
      const conversationAlreadySelected = conversations.some(
        conv => conv?.user === user.id,
      );
      if (conversationAlreadySelected) {
        setValue(
          'conversations',
          conversations.filter(conv => conv?.user !== user.id),
        );
        return;
      }
      if (users.some(usr => usr.id === user.id)) {
        setValue(
          'users',
          users.filter(u => u.id !== user.id),
        );
      } else {
        setValue('users', [...users, user]);
      }
      return;
    }
    if (conversation) {
      const userAlreadySelected = users.some(
        usr => usr.id === conversation?.user,
      );
      if (userAlreadySelected) {
        setValue(
          'users',
          users.filter(usr => usr.id !== conversation?.user),
        );
        return;
      }
      if (conversations.some(conv => conv.id === conversation.id)) {
        setValue(
          'conversations',
          conversations.filter(c => c.id !== conversation.id),
        );
      } else {
        setValue('conversations', [...conversations, conversation]);
      }
    }
  };

  const submit = (values: ForwardFormValues) => {
    const channelDestinations = values.conversations.map(conv => conv.id);
    const userDestinations = values.users.map(usr => Number(usr.id));

    forwardMessageMutation.mutate({
      source_message_ts: message.hu_data.message_ts,
      source_channel_ts: id || '',
      channel_destinations: channelDestinations,
      user_destinations: userDestinations,
    });
  };

  return (
    <FormProvider {...form}>
      <DialogTitle>
        <Stack
          sx={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
            pt: 1,
            pb: 3,
          }}
        >
          <Typography
            variant="globalS"
            fontWeight="fontWeightSemiBold"
          >
            {title}
          </Typography>
          <IconButton onClick={onClose}>
            <IconX />
          </IconButton>
        </Stack>
        <HuFormSearch
          name="filter"
          inputProps={{
            variant: 'custom',
          }}
        />
      </DialogTitle>
      <Stack sx={{ flex: 1, overflow: 'auto', px: 1 }}>
        <Stack>
          <ConversationsAndUsersList
            withCheckbox
            filter={filter}
            selectedConversations={conversations}
            selectedUsers={users}
            disabledCheckbox={countToForwardMessage >= limitAddMember}
            withInternalDetailsConversations={false}
            onSelect={handleSelect}
          />
        </Stack>
      </Stack>
      <Divider />
      <DialogActions sx={{ p: 3 }}>
        <Stack
          sx={{
            flexDirection: 'row',
            gap: 1,
            alignItems: 'center',
            width: '100%',
            justifyContent: 'space-between',
          }}
        >
          <Stack sx={{ maxWidth: '430px' }}>
            <Typography
              variant="globalXS"
              sx={{
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
              }}
            >
              {getDescriptionToForwardMessage(users, conversations)}
            </Typography>
          </Stack>
          <Button
            variant="primary"
            disabled={
              forwardMessageMutation.isLoading ||
              (!users.length && !conversations.length)
            }
            onClick={form.handleSubmit(submit)}
          >
            {t('forward.forward')}
          </Button>
        </Stack>
      </DialogActions>
    </FormProvider>
  );
};

export default MessageForward;
