import { imageEditorRef } from '@/componentsRoot/ImageEditor/ImageEditor';

import DataDescription from '../../components/DataDescription';
import DataLabel from '../../components/DataLabel';
import type { ItemDataProps } from '../../types';
import {
  FileDataImageEditActions,
} from './components/FileDataImageEditActions';
import {
  FileDataImageEmptyUpload,
} from './components/FileDataImageEmptyUpload';
import { FileDataImageNoValue } from './components/FileDataImageNoValue';
import ImagePreview from './components/ImagePreview';
import { useFileDataImage } from './hooks/useFileDataImage';

export const FileDataImage = (props: ItemDataProps) => {
  const fd = useFileDataImage(props);
  const readonly = props.onlyShow || !props.structure.editable;

  if (readonly) {
    return (
      <>
        <DataLabel {...props} />
        {fd.hasValue ? <ImagePreview url={fd.url} /> : <FileDataImageNoValue />}
        <DataDescription {...props} />
      </>
    );
  }

  if (fd.hasValue) {
    return (
      <>
        <DataLabel {...props} />
        <div>
          <ImagePreview url={fd.url} />
          <FileDataImageEditActions
            uploading={fd.uploading}
            buttonTitle={fd.buttonTitle}
            isMobile={fd.isMobile}
            col={fd.col}
            onDelete={fd.delFile}
            onUpload={fd.onUploadNewFile}
            onCopyLink={fd.onCopyLink}
            onEdit={() => {
              imageEditorRef.current?.open({
                imageUrl: fd.url,
                onSave: (base64) => {
                  fd.uploadBase64Request(base64);
                },
              });
            }}
          />
        </div>
        <DataDescription {...props} />
      </>
    );
  }

  return (
    <>
      <DataLabel {...props} />
      <FileDataImageEmptyUpload
        uploading={fd.uploading}
        buttonTitle={fd.buttonTitle}
        isMobile={fd.isMobile}
        col={fd.col}
        onUpload={fd.onUploadNewFile}
        onDropFile={fd.uploadRequest}
      />
      <DataDescription {...props} />
    </>
  );
};
