import { useTheme } from '@mui/material';
import React, { useRef, useState } from 'react';
import { FlowElement, Handle, Position } from 'react-flow-renderer';
import { Handles } from '../entitypill/entitypill';

import styles from './relationpill.module.scss';

/**
 * Component to render a relation flow element
 * @param { FlowElement<RelationData>} param0 The data of a relation flow element.
 */
export default function RelationRFPill({ data }: { data: any }) {
  const theme = useTheme();

  const minRef = useRef<HTMLInputElement>(null);
  const maxRef = useRef<HTMLInputElement>(null);

  const [readOnlyMin, setReadOnlyMin] = useState(true);
  const [readOnlyMax, setReadOnlyMax] = useState(true);

  const onDepthChanged = (depth: string) => {
    // Don't allow depth above 99
    const limit = 99;
    if (data != undefined) {
      data.depth.min = data.depth.min >= limit ? limit : data.depth.min;
      data.depth.max = data.depth.max >= limit ? limit : data.depth.max;

      // Check for for valid depth: min <= max
      if (depth == 'min') {
        if (data.depth.min > data.depth.max) data.depth.max = data.depth.min;
        setReadOnlyMin(true);
      } else if (depth == 'max') {
        if (data.depth.max < data.depth.min) data.depth.min = data.depth.max;
        setReadOnlyMax(true);
      }

      // Set to the correct width
      if (maxRef.current)
        maxRef.current.style.maxWidth = calcWidth(data.depth.max);
      if (minRef.current)
        minRef.current.style.maxWidth = calcWidth(data.depth.min);
    }
  };

  const isNumber = (x: string) => {
    {
      if (typeof x != 'string') return false;
      return !Number.isNaN(x) && !Number.isNaN(parseFloat(x));
    }
  };

  const calcWidth = (data: number) => {
    return data.toString().length + 0.5 + 'ch';
  };

  return (
    <div className={styles.relation}>
      <div
        className={styles.arrowLeft}
        style={{
          borderRightColor: theme.palette.queryBuilder.relation.background,
        }}
      />
      <div
        className={styles.contentWrapper}
        style={{
          color: theme.palette.queryBuilder.text,
          background: theme.palette.queryBuilder.relation.background,
        }}
      >
        <Handle
          id={Handles.RelationLeft}
          type="source"
          position={Position.Left}
          className={styles.handleLeft}
        />
        <span className={styles.content}>{data.name}</span>
        <Handle
          id={Handles.RelationRight}
          type="target"
          position={Position.Right}
          className={styles.handleRight}
        />
      </div>
      <div
        className={styles.arrowRight}
        style={{
          borderLeftColor: theme.palette.queryBuilder.relation.background,
        }}
      />
    </div>
  );
}