import React from 'react';
import styled from 'styled-components';
import { useEffect, useRef } from "react";
import { drawReferenceLines } from "../ecg/bg-functions";
import pin from '../assets/images/pin.svg'
import "./styles.css";

const CanvasContainer = styled.div`
  position: relative;
  ${props => props.width ? `width:${props.width}px;` : `width:909px;`}
  ${props => props.height ? `height:${props.height}px;` : `height: 161px;`}
  
`

const CanvasActions = styled.div`
  position: absolute;
  top:0;
  left:0;
  z-index:2;
  display:flex;
  align-items:center;
`

const DerivationIndicator = styled.div`
  font-family: Montserrat;
  font-size: 21px;
  font-style: normal;
  font-weight: 600;
  line-height: 35px;
  letter-spacing: -0.04em;
  text-align: center;
  background: #F2F2F2B3;
  width: 48px;
  height: 35px;
  color: #63C7FF;

  margin-right:11px;

`


const ECG = ({ derivation, dataDerivation, label, canvasRef, width = 909, height = 161, canPin = true, backgroundGrid = true, canvasId, children, ...props }) => {

  const canvasBgRef = useRef();

  useEffect(() => {
    if (canvasBgRef.current && backgroundGrid) {
      drawReferenceLines(canvasBgRef.current, "#F2F2F2");
    }

    /* Retornar algo para hacer un clean del canvas en el unmount? */
    return () => {
      const canvasBg = canvasBgRef.current;
      const bgCtx = canvasBg?.getContext("2d");
      bgCtx.clearRect(0, 0, canvasBg?.canvas?.width, canvasBg?.canvas?.height)
    }

  }, [])

  return (

    <div className="canvas-wrapper" {...props}>
      <CanvasContainer
        className="canvas-container"
        width={width}
        height={height}
      >
        <CanvasActions>
          <DerivationIndicator>
            {label || derivation}
          </DerivationIndicator>
          {canPin && (
            <div className="pinIcon">
              <img src={pin} alt="" />
            </div>
          )}
        </CanvasActions>

        <canvas
          ref={canvasRef}
          id={canvasId || derivation}
          data-derivation={dataDerivation || derivation}
          className="canvas-content"
          width={width - 80}
          height={height}
        ></canvas>

        <canvas
          ref={canvasBgRef}
          id={`${derivation}-bg`}
          className="canvas-background"
          width={width}
          height={height}
        ></canvas>

        {children}
      </CanvasContainer>
    </div>

  )
}
export default ECG;
