import React, {FC} from "react";
import {Position} from "@xyflow/system";
import {colors} from "./tree/Colors";
import {Handle, NodeProps, useUpdateNodeInternals} from "@xyflow/react";
import {RenderedNodeDataInBranch, useNodesStore, WithSourceNodeId, WithTargetNodeId} from "./tree/store";
import {CalculateHorizontalPositionOptions, CalculateVerticalPositionOptions, Direction} from "./Tree";
import {StepAnchorTieredBase} from "./StepAnchorTieredBase";
import {StepAnchorHandles} from "./StepAnchorHandles";
import {motion} from 'motion/react';
import {useStoreAPI, useTreeNode} from "./tree/TreeHooks";

// Helper function to convert index to alphabetic letter
const indexToLetter = (index: number | undefined): string => {
  if (index === undefined) return '';
  return String.fromCharCode(65 + index); // 65 is ASCII for 'A'
};

export type StepAnchorData = WithSourceNodeId & WithTargetNodeId & {
    renderedNodeType: 'step-anchor',
    isFirst: boolean, // this is calculated ONCE when the node is created using regexes
    /**
     * This means that the branch of the Coupons+ node is a nested branch
     */
    nodeHasMultiNodeBranch?: true, // again here for perf.
    direction?: Direction,
    y?: CalculateHorizontalPositionOptions['y'],
    type?: 'tiered-base' | 'tier-row',
    label?: string
}
export const StepAnchorBranch: FC<NodeProps & {data: StepAnchorData}> = ({id}) => {
    const removeTier = useStoreAPI('removeTier');
    const treeNode = useTreeNode(id)

    return <motion.div layout={true} className={'relative flex items-center justify-center rounded-full w-4 h-4 bg-gray-200 hover:bg-gray-200 hover:scale-125 transition' +
        ' text-gray-500 font-bold text-smaller-3 uppercase group hover:cursor-pointer'} transition={{ duration: 0.5 }} onClick={() => {
            removeTier(id);
    }}>
        <StepAnchorHandles isFirst={treeNode?.getParentBranch()?.isFirstChild(treeNode)!}>
                <div className="group-hover:hidden">{indexToLetter(treeNode?.getParentBranch()?.getChildIndex(treeNode?.id))}</div>
                <div className="hidden group-hover:block">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="min-w-3 max-w-3 min-h-3 max-h-3 text-gray-700">
                        <path fillRule="evenodd" d="M5.47 5.47a.75.75 0 0 1 1.06 0L12 10.94l5.47-5.47a.75.75 0 1 1 1.06 1.06L13.06 12l5.47 5.47a.75.75 0 1 1-1.06 1.06L12 13.06l-5.47 5.47a.75.75 0 0 1-1.06-1.06L10.94 12 5.47 6.53a.75.75 0 0 1 0-1.06Z" clipRule="evenodd" />
                    </svg>
                </div>
        </StepAnchorHandles>
    </motion.div>
}
