import { type FC } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

import { IconInfoCircle } from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
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 useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { MAX_GROUP_DESCRIPTION_LENGTH } from 'src/pages/dashboard/Conversations/constants';
import { useEditGroup } from 'src/pages/dashboard/Conversations/hooks/useConversationsQueries';
import { type Channel } from 'src/pages/dashboard/Conversations/types';
import { convertMessageToTipTapFormat } from 'src/pages/dashboard/Conversations/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import InputEditor from '../../ConversationsThreadFooter/InputEditor';

type EditDescriptionType = {
  onClose: () => void;
  conversation: Channel;
  description: string | undefined;
  title: string;
};

const EditDescription: FC<EditDescriptionType> = props => {
  const { onClose, conversation, description, title } = props;
  const { t } = useLokaliseTranslation(['chat', 'general']);
  const { enqueueSnackbar } = useHuSnackbar();
  const { mutateAsync: editGroup, isLoading } = useEditGroup();
  const form = useForm({
    defaultValues: {
      description: description || '',
    },
    mode: 'onChange',
  });
  const {
    handleSubmit,
    formState: { isDirty, isSubmitting },
  } = form;

  const submit = async (values: { description: string }) => {
    try {
      await editGroup({
        channelId: conversation.id,
        description: values.description,
      });
      onClose();
    } catch (error) {
      enqueueSnackbar({
        title: t('chat:errors.edit_description'),
        variant: 'error',
      });
    }
  };

  const processedContent = convertMessageToTipTapFormat({
    messageText: description || '',
    t,
  });

  return (
    <Stack sx={{ py: 3 }}>
      <Stack
        sx={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
          pb: 2,
          px: 3,
        }}
      >
        <Typography
          variant="globalS"
          fontWeight="fontWeightSemiBold"
        >
          {title}
        </Typography>
      </Stack>
      <Stack sx={{ px: 3, pt: 2, pb: 3 }}>
        <FormProvider {...form}>
          <InputEditor
            name="description"
            content={processedContent || ''}
            disabled={isSubmitting || isLoading}
            isPopper
            minHeight="120px"
            placeholder="description.placeholder"
            maxLength={MAX_GROUP_DESCRIPTION_LENGTH}
            showCounter
            clearOnSubmit={false}
          />
        </FormProvider>
      </Stack>

      <Divider />
      <Stack
        sx={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
          px: 3,
          pt: 2,
        }}
      >
        <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 0.5 }}>
          <Stack
            sx={{
              alignSelf: 'flex-start',
              alignItems: 'center',
              height: '1lh',
            }}
          >
            <IconInfoCircle
              height={20}
              width={20}
            />
          </Stack>
          <Typography variant="globalXXS">
            {t('chat:description.hint')}
          </Typography>
        </Stack>
        <Stack
          sx={{
            flexDirection: 'row',
            justifyContent: 'flex-end',
            gap: 2,
          }}
        >
          <Button
            variant="tertiary"
            onClick={onClose}
          >
            {t('general:cancel')}
          </Button>
          <Button
            variant="primary"
            disabled={!isDirty}
            loading={isSubmitting}
            onClick={handleSubmit(submit)}
          >
            {t('general:save')}
          </Button>
        </Stack>
      </Stack>
    </Stack>
  );
};

export default EditDescription;
