import { Overlay } from './Overlay'
import './Bleed.scss'
import { PT_TO_MM, PageSizeUnits, convertToMM, detectStandardPaperSizeUnit, parsePageSize as parsePageSizeUtil } from '$themeservices'
import themeContext from '$ustoreinternal/services/themeContext'

export const Bleed = ({ viewerState, canvasSize, product }) => {
  const assetPrefix = themeContext && themeContext.get().hasOwnProperty('assetPrefix') ? themeContext.get().assetPrefix : ''
  const scissors = `${assetPrefix}/assets/icons/Scissors.svg`
  const { metaData } = viewerState
  const { DocumentBoxes, Height, Width } = metaData
  const { Trim, Media } = DocumentBoxes

  const showBleed = !(Trim && (Trim.Top === Media.Top || Trim.Bottom === Media.Bottom || Trim.Left === Media.Left || Trim.Right === Media.Right))

  const parsePageSize = (pageSize) => parsePageSizeUtil(pageSize, product)

  const calculateContentPosition = () => {
    if (!viewerState.pageSize || !metaData) {
      return null
    }

    const originalWidth = metaData.Width
    const originalHeight = metaData.Height

    let sheetWidth, sheetHeight
    if (viewerState.pageSize === 'Auto') {
      sheetWidth = originalWidth
      sheetHeight = originalHeight
    } else {
      const parsed = parsePageSize(viewerState.pageSize)
      const widthMM = convertToMM(parsed.width, parsed.unit)
      const heightMM = convertToMM(parsed.height, parsed.unit)
      sheetWidth = widthMM / PT_TO_MM
      sheetHeight = heightMM / PT_TO_MM
      
      if (viewerState.orientation === 'landscape') {
        [sheetWidth, sheetHeight] = [sheetHeight, sheetWidth]
      }
    }

    if (canvasSize?.width && canvasSize?.height) {
      const contentWidthPercent = canvasSize.width
      const contentHeightPercent = canvasSize.height
      
      const contentWidth = (sheetWidth * contentWidthPercent) / 100
      const contentHeight = (sheetHeight * contentHeightPercent) / 100
      
      const contentLeft = (sheetWidth - contentWidth) / 2
      const contentTop = (sheetHeight - contentHeight) / 2
      
      const scaleX = contentWidth / originalWidth
      const scaleY = contentHeight / originalHeight
      const scale = Math.min(scaleX, scaleY)

      return {
        contentLeft,
        contentTop,
        contentWidth,
        contentHeight,
        sheetWidth,
        sheetHeight,
        scaleX,
        scaleY,
        scale
      }
    }

    const scaleX = sheetWidth / originalWidth
    const scaleY = sheetHeight / originalHeight
    const scale = Math.min(scaleX, scaleY)

    const contentWidth = originalWidth * scale
    const contentHeight = originalHeight * scale

    const contentLeft = (sheetWidth - contentWidth) / 2
    const contentTop = (sheetHeight - contentHeight) / 2

    return {
      contentLeft,
      contentTop,
      contentWidth,
      contentHeight,
      sheetWidth,
      sheetHeight,
      scaleX,
      scaleY,
      scale
    }
  }

  const wrapperStyles = () => {
    const bleedLeft = Math.abs(Trim.Left - Media.Left)
    const bleedRight = Math.abs(Trim.Right - Media.Right)
    const bleedTop = Math.abs(Trim.Top - Media.Top)
    const bleedBottom = Math.abs(Trim.Bottom - Media.Bottom)

    if (viewerState.FitMode === 'Fit' && viewerState.pageSize && viewerState.pageSize !== 'Auto') {
      const parsed = parsePageSize(viewerState.pageSize)
      const widthMM = convertToMM(parsed.width, parsed.unit)
      const heightMM = convertToMM(parsed.height, parsed.unit)
      let sheetWidth = widthMM / PT_TO_MM
      let sheetHeight = heightMM / PT_TO_MM

      if (viewerState.orientation === 'landscape') {
        [sheetWidth, sheetHeight] = [sheetHeight, sheetWidth]
      }

      const scaleX = sheetWidth / Width
      const scaleY = sheetHeight / Height

      const totalWidth = sheetWidth + bleedLeft * scaleX + bleedRight * scaleX
      const totalHeight = sheetHeight + bleedTop * scaleY + bleedBottom * scaleY

      const docAR = Width / Height
      const containerAR = totalWidth / totalHeight

      let canvasW, canvasH, canvasLeft, canvasTop
      if (docAR >= containerAR) {
        canvasW = totalWidth
        canvasH = totalWidth / docAR
        canvasLeft = 0
        canvasTop = (totalHeight - canvasH) / 2
      } else {
        canvasH = totalHeight
        canvasW = totalHeight * docAR
        canvasLeft = (totalWidth - canvasW) / 2
        canvasTop = 0
      }

      const leftTrim = canvasLeft + (bleedLeft / Width) * canvasW
      const topTrim = canvasTop + (bleedTop / Height) * canvasH
      const rightInset = (totalWidth - canvasLeft - canvasW) + (bleedRight / Width) * canvasW
      const bottomInset = (totalHeight - canvasTop - canvasH) + (bleedBottom / Height) * canvasH

      return {
        left: `${(leftTrim / totalWidth) * 100}%`,
        right: `${(rightInset / totalWidth) * 100}%`,
        top: `${(topTrim / totalHeight) * 100}%`,
        bottom: `${(bottomInset / totalHeight) * 100}%`,
      }
    }

    const contentPos = calculateContentPosition()
    
    if (!contentPos) {
      return {
        bottom: `${(bleedBottom / Height) * 100}%`,
        left: `${(bleedLeft / Width) * 100}%`,
        top: `${(bleedTop / Height) * 100}%`,
        right: `${(bleedRight / Width) * 100}%`,
      }
    }

    const { contentLeft, contentTop, contentWidth, contentHeight, sheetWidth, sheetHeight, scale } = contentPos

    const scaledBleedLeft = bleedLeft * scale
    const scaledBleedRight = bleedRight * scale
    const scaledBleedTop = bleedTop * scale
    const scaledBleedBottom = bleedBottom * scale

    const bleedLeftFromSheet = contentLeft + scaledBleedLeft
    const bleedRightFromSheet = contentLeft + contentWidth - scaledBleedRight
    const bleedTopFromSheet = contentTop + scaledBleedTop
    const bleedBottomFromSheet = contentTop + contentHeight - scaledBleedBottom

    return {
      left: `${(bleedLeftFromSheet / sheetWidth) * 100}%`,
      right: `${((sheetWidth - bleedRightFromSheet) / sheetWidth) * 100}%`,
      top: `${(bleedTopFromSheet / sheetHeight) * 100}%`,
      bottom: `${((sheetHeight - bleedBottomFromSheet) / sheetHeight) * 100}%`,
    }
  }

  const getScissorsStyles = () => {
    const borderPosition = wrapperStyles()
    return {
      bottom: {
        bottom: `calc(${borderPosition.bottom} - 9px)`,
        transform: 'rotate(180deg)',
      },
      left: {
        left: `calc(${borderPosition.left} - 12px)`,
        transform: 'rotate(270deg)'
      },
      top: {
        top: `calc(${borderPosition.top} - 9px)`,
      },
      right: {
        right: `calc(${borderPosition.right} - 12px)`,
        transform: 'rotate(90deg)'
      }

    }
  }

  return showBleed && <Overlay type="bleed">
    <img className="scissors-top" alt="scissors" src={scissors} style={getScissorsStyles().top}/>
    <img className="scissors-righ" alt="scissors" src={scissors} style={getScissorsStyles().right}/>
    <img className="scissors-bottom" alt="scissors" src={scissors} style={getScissorsStyles().bottom}/>
    <img className="scissors-left" alt="scissors" src={scissors} style={getScissorsStyles().left}/>
    <div className="bleed-wrapper" style={wrapperStyles()}/>
  </Overlay>

}
