import { Button, Group, Switch, Tooltip } from '@mantine/core';
import { IconDeviceFloppy, IconX } from '@tabler/icons-react';

import { useFormerStore } from './Former.store';

export const FormerButtonArea = () => {
  const {
    buttonAreaGroupProps,
    closeButtonProps,
    closeButtonTitle,
    dirty,
    getState,
    keepOpen,
    onClose,
    request,
    save,
    saveButtonProps,
    saveButtonTitle,
    setState,
    showKeepOpenSwitch,
  } = useFormerStore((state) => ({
    buttonAreaGroupProps: state.layout?.buttonAreaGroupProps,
    closeButtonProps: state.layout?.closeButtonProps,
    closeButtonTitle: state.layout?.closeButtonTitle,
    dirty: state.dirty,
    getState: state.getState,
    keepOpen: state.keepOpen,
    onClose: state.onClose,
    request: state.request,
    save: state.save,
    saveButtonProps: state.layout?.saveButtonProps,
    saveButtonTitle: state.layout?.saveButtonTitle,
    setState: state.setState,
    showKeepOpenSwitch: state.layout?.showKeepOpenSwitch,
  }));

  const disabledSave =
    ['select', 'view'].includes(request || '') || (['update'].includes(request || '') && !dirty);

  return (
    <Group
      justify="center"
      p="xs"
      style={{ boxShadow: '2px 2px 5px rgba(47, 47, 47, 0.1)' }}
      w="100%"
      {...buttonAreaGroupProps}
    >
      <Group grow justify="space-evenly">
        {typeof onClose === 'function' && (
          <Button
            color="orange"
            leftSection={<IconX />}
            miw={'8rem'}
            px="md"
            size="sm"
            {...closeButtonProps}
            onClick={() => {
              onClose(getState('values'));
            }}
          >
            {closeButtonTitle || 'Close'}
          </Button>
        )}
        {showKeepOpenSwitch && (
          <Switch
            checked={keepOpen}
            label="Keep Open"
            onChange={(event) => setState('keepOpen', event.currentTarget.checked)}
          />
        )}
        <Tooltip
          label={
            disabledSave ? (
              <p>
                Cannot save in view or select mode, or no changes made. <br />
                Try changing some values.
              </p>
            ) : (
              <p>Save the current record</p>
            )
          }
        >
          <Button
            bg={request === 'delete' ? 'red' : undefined}
            color="green"
            leftSection={<IconDeviceFloppy />}
            miw={'8rem'}
            px="md"
            size="sm"
            {...saveButtonProps}
            disabled={disabledSave}
            onClick={() => save()}
          >
            {saveButtonTitle || 'Save'}
          </Button>
        </Tooltip>
      </Group>
    </Group>
  );
};
