import { useState, useMemo } from 'react';

import { useDimensions } from 'src/hooks/useDimensions';
import { Dimensions, defaultDimensions } from 'src/hooks/useDimensions';

export type PdfDimensionsOptions = Partial<{
  fitWidth: boolean;
  fitHeight: boolean;
}>;

export const usePdfDimensions = (options: PdfDimensionsOptions = {}) => {
  const { fitWidth = false, fitHeight = false } = options;

  const [pageDimensions, setPageDimensions] =
    useState<Dimensions>(defaultDimensions);

  const { ref, dimensions: wrapperDimensions } = useDimensions();

  const handleLoadPage = page => {
    setPageDimensions({
      width: page.width as number,
      height: page.height as number,
    });
  };

  const dimensions = useMemo(() => {
    if (fitWidth || fitHeight) {
      return {
        width: fitWidth ? wrapperDimensions.width : null,
        height: fitHeight ? wrapperDimensions.height : null,
      };
    }

    const widthRatio = pageDimensions.width / wrapperDimensions.width;
    const heightRatio = pageDimensions.height / wrapperDimensions.height;

    const fitHorizontal = widthRatio >= heightRatio;

    return {
      width: fitHorizontal ? wrapperDimensions.width : null,
      height: fitHorizontal ? wrapperDimensions.height : null,
    };
  }, [pageDimensions, wrapperDimensions]);

  return {
    ref,
    dimensions,
    handleLoadPage,
  };
};

export default usePdfDimensions;
