import React, { useCallback, useContext, useEffect, useState } from 'react';
import { Texture } from 'fabric-texture';
import { Code, CodePreview, TextSwitch } from 'docs/components';
import { DocsContext } from 'docs/docs';
import styles from './style.less';

const ChangeRenderOptions = () => {
  const { placeholder } = useContext(DocsContext);

  const [preview, setPreview] = useState<string>();
  const [showGrid, setShowGrid] = useState<boolean>(false);
  const [showGridDot, setShowGridDot] = useState<boolean>(false);
  const [showTexture, setShowTexture] = useState<boolean>(true);

  const render = useCallback(async () => {
    if (!placeholder) return;
    const { naturalWidth, naturalHeight } = placeholder;

    const canvas = document.createElement('canvas');
    canvas.width = naturalWidth;
    canvas.height = naturalHeight;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    ctx.drawImage(placeholder, 0, 0);

    const texture = new Texture(canvas);

    texture
      .setSplitUnit(0.05)
      .setInputLimitSize({ width: 400 })
      .setRenderOptions({
        showGrid,
        showGridDot,
        showTexture,
      })
      .setBoundCoords(0, 0, 'top', [
        { x: 0, y: 0 },
        { x: naturalWidth / 3, y: naturalHeight * 0.2 },
        { x: naturalWidth * (2 / 3), y: naturalHeight * 0.2 },
        { x: naturalWidth, y: 0 },
      ])
      .setBoundCoords(0, 0, 'bottom', [
        { x: 0, y: naturalHeight },
        { x: naturalWidth / 3, y: naturalHeight * 0.8 },
        { x: naturalWidth * (2 / 3), y: naturalHeight * 0.8 },
        { x: naturalWidth, y: naturalHeight },
      ]);

    setPreview(texture.create().toDataURL());
  }, [placeholder, showGrid, showGridDot, showTexture]);

  useEffect(() => {
    render();
  }, [render]);

  return (
    <div className={styles.demo}>
      {placeholder && preview && <CodePreview className={styles.preview} src={preview} />}
      <Code
        className={styles.code}
        link="sections/more-configuration/codes/change-render-options-demo.ts"
      >
        {(key) => {
          switch (key) {
            case 'show-grid':
              return <TextSwitch value={showGrid} onChange={setShowGrid} />;
            case 'show-grid-dot':
              return <TextSwitch value={showGridDot} onChange={setShowGridDot} />;
            case 'show-texture':
              return <TextSwitch value={showTexture} onChange={setShowTexture} />;
          }
        }}
      </Code>
    </div>
  );
};

export default ChangeRenderOptions;
