import { useMemo } from 'react';

import {
  EdgeLabelRenderer,
  type EdgeProps,
  getSmoothStepPath,
  Position,
} from '@xyflow/react';

import '@xyflow/react/dist/style.css';

import { IconPlus, IconX } from '@material-hu/icons/tabler';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuPills from '@material-hu/components/design-system/Pills';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { type FlowNode, NodeType } from 'src/types/workflows';
import { useLokaliseTranslation } from 'src/utils/i18n';

type CustomEdgeProps = EdgeProps & {
  showSidesheet: (edgeId: string) => void;
  parent?: FlowNode;
};

const getPillColor = (parent?: FlowNode, targetX?: number) => {
  if (!parent || !targetX) return 'neutral';

  if (parent?.data?.type === NodeType.APPROVAL) {
    const isApproval = (parent?.position?.x || 0) > targetX;
    return isApproval ? 'success' : 'error';
  }
  return 'neutral';
};

const CustomEdge = (props: CustomEdgeProps) => {
  const HuGoThemeProvider = useHuGoTheme();
  const { t } = useLokaliseTranslation('workflows');
  const {
    id,
    sourceX,
    sourceY,
    targetX,
    targetY,
    markerEnd,
    label: initialLabel,
    showSidesheet,
    parent,
  } = props;

  const label =
    parent?.data?.type === NodeType.APPROVAL
      ? t(initialLabel?.toString() || '')
      : (initialLabel as React.ReactNode);

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [path, labelX, labelY] = getSmoothStepPath({
    sourceX,
    sourceY,
    sourcePosition: Position.Bottom,
    targetX,
    targetY,
    targetPosition: Position.Top,
    borderRadius: 16,
  });

  // Edge Length calculation for label positioning
  const labelPosition = useMemo(() => {
    const svgPath = document.createElementNS(
      'http://www.w3.org/2000/svg',
      'path',
    );
    svgPath.setAttribute('d', path);
    const point = svgPath.getPointAtLength(svgPath.getTotalLength() * 0.7);
    const diff = Math.abs(labelX - point.x);
    let newLabelX = labelX;
    if (diff > 200) {
      newLabelX = point.x * 1.2;
    } else if (diff > 100) {
      newLabelX = point.x;
    }
    const overlap = Math.floor(labelX) === Math.floor(targetX);

    return { newLabelX, overlap };
  }, [path, labelX, targetX]);

  return (
    <HuGoThemeProvider>
      <path
        id={id}
        d={path}
        className="react-flow__edge-path"
        markerEnd={markerEnd}
        style={{
          fill: 'none',
          stroke: '#AAAABA',
          strokeWidth: 1,
        }}
      />
      <EdgeLabelRenderer>
        {label && (
          <div
            style={{
              position: 'absolute',
              transform: `translate(-50%, -50%) translate(${labelPosition.newLabelX}px, ${labelPosition.overlap ? labelY - 10 : labelY}px)`,
              pointerEvents: 'all',
              zIndex: 1,
            }}
          >
            <HuTooltip
              description={label.toString()}
              disableTooltip={label.toString().length < 16}
            >
              <span>
                <HuPills
                  label={label.toString()}
                  hasIcon={getPillColor(parent, targetX) !== 'neutral'}
                  customIcon={
                    getPillColor(parent, targetX) === 'error'
                      ? IconX
                      : undefined
                  }
                  type={getPillColor(parent, targetX)}
                  sx={{ maxWidth: '150px' }}
                />
              </span>
            </HuTooltip>
          </div>
        )}
        <div
          style={{
            position: 'absolute',
            transform: `translate(-50%, -50%) translate(${label ? targetX : labelX}px, ${label ? labelY + 16 : labelY}px)`,
            transformOrigin: 'center',
            pointerEvents: 'all',
          }}
        >
          <HuTooltip
            description={t('add_component')}
            direction="bottom"
          >
            <Button
              aria-label={t('add_component')}
              sx={{
                height: '26px',
                minWidth: '26px !important',
                padding: 0,
                color: th => th.palette.new.text.neutral.disabled,
                backgroundColor: th => th.palette.new.background.layout.default,
                cursor: 'pointer',
                '&:hover': {
                  backgroundColor: th => th.palette.new.border.neutral.default,
                  color: th => th.palette.new.text.neutral.default,
                },
              }}
              onClick={e => {
                e.stopPropagation();
                showSidesheet(id);
              }}
            >
              <IconPlus size={16} />
            </Button>
          </HuTooltip>
        </div>
      </EdgeLabelRenderer>
    </HuGoThemeProvider>
  );
};

export default CustomEdge;
