import React, {FC, useState} from "react";
import {RemoveButton, RemoveButtonProps} from "./RemoveButton";
import {useNodesStore} from "./store";
import {TargetedConfirmDialog} from "../TargetedConfirmDialog";
import {__} from "../globals";

export type TestableCompositeRemoveButtonProps = {
    show: boolean,
    onRemove?: () => void,
} & Pick<RemoveButtonProps, 'onRequestToUnHighlight'|'onRequestToHighlight'|'entityID'>;

/**
 * A separate component so that when the HoveredContextIDAtom state changes, the entire TestableComposite doesn't re-render
 */
export const TestableCompositeRemoveButton: FC<TestableCompositeRemoveButtonProps> = ({show, onRequestToUnHighlight, onRequestToHighlight, entityID, onRemove}) => {
    const removeTestable = useNodesStore(store => store.removeTestable)
    const isRootTestable = useNodesStore(store => !store.testableRelations.some(relation => relation.children.includes(entityID)))
    const [isConfirmOpen, setIsConfirmOpen] = useState(false)
    const [originRect, setOriginRect] = useState<DOMRect | null>(null)

    const onConfirm = () => {
        removeTestable(entityID)
        setIsConfirmOpen(false)
        onRemove?.()
    }

    return <div>
        <RemoveButton entityID={entityID}
                      onClick={(event) => {
                          setOriginRect(event.currentTarget.getBoundingClientRect())
                          setIsConfirmOpen(true)
                      }}
                      show={show}
                      positionX={'right-corner'}
                      onRequestToHighlight={onRequestToHighlight}
                      onRequestToUnHighlight={onRequestToUnHighlight}
        />
        <TargetedConfirmDialog
            isOpen={isConfirmOpen}
            originRect={originRect}
            title={isRootTestable ? __('Delete this tree?') : __('Delete this group?')}
            description={isRootTestable
                ? __('This will remove all product filters and offers from this tree.')
                : __('Are you sure you want to delete this testable group?')}
            confirmLabel={__('Yes')}
            cancelLabel={__('No')}
            onConfirm={onConfirm}
            onCancel={() => setIsConfirmOpen(false)}
        />
    </div>;
}
