import React, { useEffect, useState } from 'react';
import {
  Editable,
  EditableInput,
  EditablePreview,
  Flex,
  IconButton,
  Input,
  useEditableControls,
  ButtonGroup,
  Stack,
  useToast,
} from '@chakra-ui/react';
import { CheckIcon, CloseIcon, EditIcon } from '@chakra-ui/icons';
import { useTranslation } from 'react-i18next';

import { useUpdateMasterMutation } from '../../__data__/service/api';

interface EditableWrapperProps {
  value: string;
  as: 'phone' | 'name';
  id: string;
}

const EditableWrapper = ({ value, as, id }: EditableWrapperProps) => {
  const [updateMaster, { isError, isSuccess, error }] =
    useUpdateMasterMutation();

  const { t } = useTranslation('~', {
    keyPrefix: 'dry-wash.arm.master.editable',
  });

  const toast = useToast();
  const [currentValue, setCurrentValue] = useState<string>(value);

  const handleSubmit = async (newValue: string) => {
    if (currentValue === newValue) return;

    await updateMaster({ id, [as]: newValue });

    setCurrentValue(newValue);
  };

  useEffect(() => {
    if (isSuccess) {
      toast({
        title: 'Успешно!',
        description: 'Данные обновлены.',
        status: 'success',
        duration: 2000,
        isClosable: true,
        position: 'top-right',
      });
    }
  }, [isSuccess]);

  useEffect(() => {
    if (isError) {
      toast({
        title: 'Ошибка!',
        description: 'Не удалось обновить данные.',
        status: 'error',
        duration: 2000,
        isClosable: true,
        position: 'top-right',
      });
      console.error('Ошибка при обновлении данных:', error);
    }
  }, [isError, error]);

  function EditableControls() {
    const {
      isEditing,
      getSubmitButtonProps,
      getCancelButtonProps,
      getEditButtonProps,
    } = useEditableControls();

    return isEditing ? (
      <ButtonGroup justifyContent='center' size='sm'>
        <IconButton
          aria-label={t('aria.save')}
          icon={<CheckIcon />}
          {...getSubmitButtonProps()}
        />
        <IconButton
          aria-label={t('aria.cancel')}
          icon={<CloseIcon />}
          {...getCancelButtonProps()}
        />
      </ButtonGroup>
    ) : (
      <Flex justifyContent='center'>
        <IconButton
          aria-label={t('aria.edit')}
          size='sm'
          icon={<EditIcon />}
          {...getEditButtonProps()}
        />
      </Flex>
    );
  }

  return (
    <Editable
      textAlign='center'
      defaultValue={currentValue}
      fontSize='2xl'
      isPreviewFocusable={false}
      onSubmit={handleSubmit}
    >
      <Stack direction={['column', 'row']} spacing='15px'>
        <EditablePreview />
        <Input as={EditableInput} />
        <EditableControls />
      </Stack>
    </Editable>
  );
};

export default EditableWrapper;
