import React, {useEffect} from 'react'
import {ScreenshotEditor} from "./ScreenshotEditor";
import {toJpeg} from "html-to-image";
import { takeScreenshot, checkIfBrowserSupported } from "@xata.io/screenshot";
import {Feedback} from "./types/feedback";

interface ScreenshotProps {
  onSuccess: (data: Screenshot.Data) => void
  onError: (error: Error) => void
  config: Feedback.Config
}

export default function Screenshot ({
  config,
  onSuccess,
  onError
}: ScreenshotProps) {

  const takeScreenshotHtml2Image = () => {
    const body = document.getElementsByTagName('body')[0]
    toJpeg(body, {
      filter: (node: HTMLElement) => {
        const exclusionClasses = ['screenshot-hide'];
        return !exclusionClasses.some((classname) => node.classList?.contains(classname));
      },
      backgroundColor: 'white',
      quality: 0.75,
      pixelRatio: 1
    }).then((image) => {
      ScreenshotEditor
        .run(image)
        .then((data) => {
          onSuccess(data);
        })
        .catch((error) => {
          onError(error)
        })
    }).catch((error) => {
      onError(error)
    })
  }

  const takeScreenshotXata = () => {
    takeScreenshot().then((image) => {
      ScreenshotEditor
        .run(image)
        .then((data) => {
          onSuccess(data);
        })
        .catch((error) => {
          onError(error)
        })
    });
  }

  useEffect(() => {
    setTimeout(() => {
      const forceHtml2Image = 'forceHtml2Image' in config && config.forceHtml2Image === true

      if (checkIfBrowserSupported() && !forceHtml2Image) {
        takeScreenshotXata()
      } else {
        takeScreenshotHtml2Image()
      }
    }, 10)

  }, [])



  return null
}
