/**
 *
 * DataVizPreview
 *
 */
import React, { memo } from 'react';
import '../../../styles/global.css';
import Measure from 'react-measure';
import { DataVizPreviewProps } from '../types';
import { MissingVizMessage } from '../../MissingVizMessage';

export const DataVizPreview = memo((props: DataVizPreviewProps) => {
  const { dataViz, geogIdentifier, colorScheme, CurrentViz, error } = props;

  /* Keep track fo dimensions to send to vega charts */
  const [{ width, height }, setDimensions] = React.useState({
    width: 0,
    height: 0,
  });

  return (
    <div className="w-48 relative p-1.5 min-h-0 rounded">
      <Measure
        bounds
        onResize={(contentRect) => {
          if (contentRect.bounds) setDimensions(contentRect.bounds);
        }}
      >
        {({ measureRef }) => (
          <div ref={measureRef}>
            <div
              className="rounded min-h-0"
              aria-label="data presentation preview"
            >
              {!!error && <MissingVizMessage error={error} />}
              {!!CurrentViz && dataViz && !!geogIdentifier && (
                <CurrentViz
                  dataViz={dataViz}
                  geog={geogIdentifier}
                  colorScheme={colorScheme}
                  vizHeight={height - 15}
                  vizWidth={width - 35}
                />
              )}
            </div>
          </div>
        )}
      </Measure>
    </div>
  );
});
