import React, { useRef } from 'react';
import { cn, withRef } from '@udecode/cn';
import { PlateElement, withHOC } from '@udecode/plate-common';

import {
  AttachmentImage,
  ELEMENT_ATTACHMENT_IMAGE,
  useAttachmentState,
} from '../logic';
import { AttachmentPopover } from './attachment-popover';
import {
  mediaResizeHandleVariants,
  Resizable,
  ResizeHandle,
} from './components/resizable';
import { ResizableProvider } from './components/resizable/src';

export const AttachmentImageElement = withHOC(
  ResizableProvider,
  withRef<typeof PlateElement>(
    ({ className, children, nodeProps, ...props }, ref) => {
      const { readOnly, focused, selected, element } = useAttachmentState();

      const { align = 'left', width, bordered } = element;

      const elementRef = useRef<HTMLDivElement>(null);

      return (
        <AttachmentPopover
          align={align}
          pluginkey={ELEMENT_ATTACHMENT_IMAGE}
          elementRef={elementRef}
        >
          <PlateElement
            ref={ref}
            className={cn('py-2.5', className)}
            {...props}
          >
            <figure className="group relative m-0" contentEditable={false}>
              <Resizable
                align={align}
                options={{
                  align,
                  readOnly,
                  dynamicWidth: width,
                }}
              >
                <ResizeHandle
                  options={{ direction: 'left' }}
                  className={cn(
                    mediaResizeHandleVariants({ direction: 'left' }),
                    readOnly && 'hidden'
                  )}
                />
                <AttachmentImage
                  ref={elementRef}
                  className={cn(
                    'block w-full max-w-full cursor-pointer object-cover px-0',
                    'rounded-sm',
                    //TODO: bordered style
                    ((focused && selected) || bordered) &&
                      'ring-2 ring-ring ring-offset-1'
                  )}
                  alt=""
                  {...nodeProps}
                />
                <ResizeHandle
                  options={{ direction: 'right' }}
                  className={cn(
                    mediaResizeHandleVariants({ direction: 'right' }),
                    readOnly && 'hidden'
                  )}
                />
              </Resizable>
            </figure>

            {children}
          </PlateElement>
        </AttachmentPopover>
      );
    }
  )
);
