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

const LeadRow = styled.div`
  width: 100%;
  display: block;
  min-width: 0;
  line-height: 0;
`;

const CanvasContainer = styled.div`
  position: relative;
  display: grid;
  grid-template-columns: ${({ $railWidth }) =>
    `${$railWidth}px minmax(0, 1fr)`};
  width: ${({ $width }) => `${$width}px`};
  max-width: 100%;
  min-width: 0;
  height: ${({ $height }) => `${$height}px`};
  border-radius: 18px;
  overflow: hidden;
  background: #ffffff;
  border: 1px solid rgba(177, 99, 255, 0.12);
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.7);
`;

const LeadRail = styled.div`
  position: relative;
  z-index: 2;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
  padding: 12px;
  box-sizing: border-box;
  background: linear-gradient(
    180deg,
    rgba(251, 249, 255, 0.98) 0%,
    #ffffff 100%
  );
  border-right: 1px solid rgba(177, 99, 255, 0.08);
`;

const PlotSurface = styled.div`
  position: relative;
  min-width: 0;
  overflow: hidden;
  background: #ffffff;
`;

const CanvasLayer = styled.canvas`
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  display: block;
`;

const CanvasActions = styled.div`
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
`;

const DerivationIndicator = styled.div`
  min-width: ${({ $compact }) => ($compact ? "46px" : "52px")};
  height: ${({ $compact }) => ($compact ? "28px" : "30px")};
  padding: 0 10px;
  border-radius: 10px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-family: Montserrat;
  font-style: normal;
  font-weight: 600;
  font-size: ${({ repository }) =>
    repository === "frontMulti" ? "18px" : "15px"};
  line-height: 1;
  letter-spacing: -0.03em;
  text-align: center;
  background: rgba(242, 242, 242, 0.9);
  color: #63c7ff;
`;

export const Nav = styled.div`
  position: relative;
  z-index: 0;
`;

const PinButton = styled.button`
  width: ${({ repository }) => (repository === "frontMulti" ? "28px" : "24px")};
  height: ${({ repository }) =>
    repository === "frontMulti" ? "28px" : "24px"};
  border: none;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: transparent;
  cursor: pointer;
`;

const ImgPin = styled.img`
  width: 100%;
  height: 100%;
`;

const PlotOverlay = styled.div`
  position: absolute;
  inset: 0;
  z-index: 4;
  pointer-events: none;

  > * {
    pointer-events: auto;
  }
`;

const ECG = ({
  isPin,
  handlePin,
  derivation,
  dataDerivation,
  label,
  canvasRef,
  width = 500,
  height = 161,
  canPin = true,
  backgroundGrid = true,
  canvasId,
  children,
  repository,
  labelWidth = 72,
  railWidth,
  ...props
}) => {
  const canvasBgRef = useRef();
  const pinImage = isPin ? pinned : pin;
  const isMiniature = canvasId === "dii-miniature";
  const compact = width < 420;
  const resolvedRailWidth = useMemo(() => {
    if (typeof railWidth === "number" && railWidth > 0) {
      return Math.min(Math.max(railWidth, 56), Math.max(width - 160, 56));
    }

    return isMiniature
      ? Math.max(labelWidth + 18, 72)
      : Math.max(labelWidth + (canPin ? 48 : 28), 96);
  }, [canPin, isMiniature, labelWidth, railWidth, width]);
  const plotWidth = Math.max(width - resolvedRailWidth, 1);

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

    return () => {
      const canvasBg = canvasBgRef.current;
      const bgCtx = canvasBg?.getContext("2d");
      bgCtx?.setTransform(1, 0, 0, 1, 0, 0);
      bgCtx?.clearRect(
        0,
        0,
        canvasBg?.canvas?.width || 0,
        canvasBg?.canvas?.height || 0,
      );
    };
  }, [backgroundGrid, plotWidth, height]);

  return (
    <LeadRow {...props}>
      <CanvasContainer
        className="canvas-container"
        $width={width}
        $height={height}
        $railWidth={resolvedRailWidth}
      >
        <LeadRail>
          <CanvasActions>
            <DerivationIndicator repository={repository} $compact={compact}>
              {label || derivation}
            </DerivationIndicator>
            {canPin && (
              <PinButton
                className="pinIcon"
                repository={repository}
                type="button"
                onClick={(event) => {
                  handlePin(event, derivation);
                }}
              >
                <ImgPin repository={repository} src={pinImage} alt="" />
              </PinButton>
            )}
          </CanvasActions>
        </LeadRail>

        <PlotSurface>
          <CanvasLayer
            style={{ zIndex: 1 }}
            ref={canvasBgRef}
            id={`${derivation}-bg`}
            className="canvas-background"
            width={plotWidth}
            height={height}
          />

          <CanvasLayer
            style={{ zIndex: 2 }}
            ref={canvasRef}
            id={canvasId || derivation}
            data-derivation={dataDerivation || derivation}
            className="canvas-content"
            width={plotWidth}
            height={height}
          />

          {children ? <PlotOverlay>{children}</PlotOverlay> : null}
        </PlotSurface>
      </CanvasContainer>
    </LeadRow>
  );
};

export default ECG;
