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

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

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

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

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

  const showToast = useShowToast();
  const [currentValue, setCurrentValue] = useState<string>(value);

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

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

    setCurrentValue(newValue);
  };

  useEffect(() => {
    if (isSuccess) {
      showToast(t('toast.success'), 'success');
    }
  }, [isSuccess]);

  useEffect(() => {
    if (isError) {
      showToast(t('toast.error.title'), 'error', t('toast.error.description'));
      console.error(t('toast.error.description'), 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;
