import React, {memo, useCallback, useMemo, useRef, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useMutation} from 'react-query';
import {Dialog, InputClassic, Typography, TextInputType} from '@components';
import {MAX_GROUP_DESCRIPTION_LENGTH} from '@modules/chats/constants';
import {updateConversation} from '@modules/chats/services';
import {ConversationsUpdaterService} from '@modules/chats/instances/updaters';
import {useTheme} from '@shared/theme';
import {getUlid, isIos} from '@shared/utils';

import {styles} from './styles';

interface Props {
  isVisible: boolean;
  onClose: () => void;
  currentDescription?: string;
  channel: string;
}

const DIFF_TO_SHOW_WARNING = 50;
const SNAP_POINTS = ['50%'];

function EditDescriptionModal({
  channel,
  isVisible,
  onClose,
  currentDescription,
}: Props) {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const inputRef = useRef<TextInputType>(null);
  const [description, setDescription] = useState(currentDescription ?? '');
  const isSubmitEnable = useMemo(() => {
    return (
      description.length > 0 &&
      description.length <= MAX_GROUP_DESCRIPTION_LENGTH &&
      currentDescription !== description
    );
  }, [description, currentDescription]);
  const {counter, showWarning} = useMemo(() => {
    const diff = MAX_GROUP_DESCRIPTION_LENGTH - description.length;
    return {
      counter: diff,
      showWarning: diff <= DIFF_TO_SHOW_WARNING,
    };
  }, [description]);

  const {mutate, isLoading} = useMutation(updateConversation, {
    onSuccess: response => {
      ConversationsUpdaterService.saveNewConversation(response);
      onClose();
    },
  });

  const onSavePress = useCallback(() => {
    mutate({
      channel,
      description: description.trim(),
      idempotencyKey: getUlid(),
    });
  }, [channel, description, mutate]);

  const onChangeDescription = useCallback((text: string) => {
    setDescription(text);
  }, []);

  const footer = useMemo(() => {
    return {
      primaryButton: {
        text: t('general.save'),
        onPress: onSavePress,
        isLoading,
        disabled: !isSubmitEnable,
      },
      secondaryButton: {
        text: t('general.cancel'),
        onPress: onClose,
      },
      infoText: t('chat.description.hint'),
      InfoTextSufix: (
        <View style={styles.infoTextSufix}>
          {showWarning ? (
            <Typography
              variant="xxs"
              color={
                counter === 0
                  ? theme.graphics.error[500]
                  : theme.text.neutral.disabled
              }
              align="center">
              {counter}
            </Typography>
          ) : null}
        </View>
      ),
    };
  }, [
    counter,
    isLoading,
    isSubmitEnable,
    onClose,
    onSavePress,
    showWarning,
    t,
    theme.graphics.error,
    theme.text.neutral.disabled,
  ]);

  return (
    <Dialog
      isVisible={isVisible}
      onClose={onClose}
      title={t('chat.description.title')}
      footer={footer}
      enableDynamicSizing={!isIos}
      snapPoints={isIos ? SNAP_POINTS : undefined}>
      <View style={styles.container}>
        <InputClassic
          ref={inputRef}
          defaultValue={currentDescription}
          onChangeText={onChangeDescription}
          placeholder={t('chat.description.placeholder')}
          maxLength={MAX_GROUP_DESCRIPTION_LENGTH}
          style={styles.input}
          autoFocus
          useBottomSheetTextInput
          returnKeyType="default"
          autoComplete="off"
          scrollEnabled
          multiline
        />
      </View>
    </Dialog>
  );
}

export default memo(EditDescriptionModal);
