import React, {FC} from "react";
import {useMeasure} from "react-use";
import classNames from "classnames";
import {ColorOption, ColorOptionWithCustomTint, ColorWithCustomTint, request} from "./Color";
import {CardRenderer, CardRendererContext} from "./CardRenderers";
import {EmulatedButton} from "./EmulatedButton";

export type CardItemProps = ColorOptionWithCustomTint & {
    position: 'first' | 'last' | 'middle' | 'first last' | 'single',
    cardRenderer: CardRenderer,
    colors?: {
        background?: ColorWithCustomTint,
        icon?: {
            background?: ColorWithCustomTint,
            color?: ColorWithCustomTint,
            close?: {
                background?: ColorWithCustomTint,
                color?: ColorWithCustomTint,
            }
        },
    },
    verticalDistance?: string,
    context?: CardRendererContext,
    onClick?: React.MouseEventHandler<HTMLButtonElement> | undefined,
    onRemoveClick?: React.MouseEventHandler<HTMLButtonElement> | undefined,
    dynamicRemoveButton?: boolean,
    active?: boolean,
    customPadding?: string,
    topConnectorMarker?: React.ReactNode,
    topConnectorMarkerCenterOffset?: number,
    onMeasuredHeightChange?: (height: number) => void,
    className?: string,
}

export const CardItem: FC<CardItemProps> = ({
                                                position,
                                                cardRenderer,
                                                color,
                                                colors,
                                                verticalDistance,
                                                context = '',
                                                onClick,
                                                onRemoveClick,
                                                active = false,
                                                dynamicRemoveButton,
                                                customPadding,
                                                topConnectorMarker,
                                                topConnectorMarkerCenterOffset,
                                                onMeasuredHeightChange,
                                                className,
                                            }) => {
    const [ref, {height}] = useMeasure<HTMLButtonElement>();
    const isFirst = position === 'first'
    const isMiddle = position === 'middle'
    const isLast = position === 'last'
    const isSingle = position === 'single' || (position.includes('first') && position.includes('last'))
    const isClickable = !!onClick
    const connectorPadding = 6 * 2
    const connectorTopHeight = !isSingle && !isFirst
        ? (isMiddle ? (height + connectorPadding) / 2 : height / 2)
        : 0
    const connectorBottomHeight = !isSingle && !isLast
        ? (isMiddle ? (height + connectorPadding) / 2 : height / 2)
        : 0
    const resolvedTopConnectorMarkerCenterOffset = topConnectorMarkerCenterOffset ?? (connectorTopHeight / 2)

    if (!cardRenderer || typeof cardRenderer?.icon === 'undefined' || !cardRenderer.ComputedValue) {
        return <></>;
    }

    const removeButtonRef = React.useRef<HTMLDivElement>(null);

    React.useEffect(() => {
        if (height > 0) {
            onMeasuredHeightChange?.(height)
        }
    }, [height, onMeasuredHeightChange])

    return <EmulatedButton ref={ref}
                           className={classNames(`group flex space-x-2 items-center w-full border-b-px ${request(color).get('border.light.primary')} border-opacity-50 last:border-none transition-all ${request(colors?.background ?? color, 'card-background').get('background.light')}`, className, {
                                'py-[6px] pl-[6px] pr-3': !customPadding,
                                [customPadding ?? '--no-custom-padding']: customPadding,
                                'pointer-events-none': !isClickable,
                                [request(colors?.background ?? color, 'card-background-active').get('background.extra')]: active,
                            })}
                           onClick={onClick}
                           onMouseDownCapture={(event) => {
                               // Check if the click target is the remove button or its children
                               if (removeButtonRef.current && (removeButtonRef.current === event.target || removeButtonRef.current.contains(event.target as Node))) {
                                   return false;
                               }
                           }}>
        {cardRenderer.icon && <div
            ref={removeButtonRef}
            className={classNames(`relative z-10 flex items-center justify-center min-w-5 min-h-5 max-w-5 max-h-5 rounded-4 ${request(colors?.icon?.background ?? color, 'icon-background').get('background.dark')}`, {
                'group-hover:rounded-full transition duration-300 hover:scale-[1.08] active:scale-[.98]': dynamicRemoveButton,
            })} onClick={(event) => {
            // @ts-ignore
            onRemoveClick?.(event)
        }}>
            {!isSingle && connectorTopHeight > 0 && <div
                className={`absolute left-1/2 -translate-x-1/2 w-px ${request(color).get('background.dark')} bg-opacity-40`}
                style={{
                    height: `${connectorTopHeight}px`,
                    top: `-${connectorTopHeight}px`,
                }}
            ></div>}
            {!isSingle && connectorBottomHeight > 0 && <div
                className={`absolute left-1/2 -translate-x-1/2 w-px ${request(color).get('background.dark')} bg-opacity-40`}
                style={{
                    height: `${connectorBottomHeight}px`,
                    top: '100%',
                }}
            ></div>}
            {topConnectorMarker && connectorTopHeight > 0 && <div
                className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 pointer-events-none z-20"
                style={{
                    marginTop: `-${resolvedTopConnectorMarkerCenterOffset}px`,
                }}
            >
                {topConnectorMarker}
            </div>}
            <cardRenderer.icon
                className={classNames(`relative z-10 min-w-3 max-w-3 min-h-3 max-h-3 transition duration-500  ${request(colors?.icon?.color ?? color, 'icon-color').text(10)}`, {
                    'scale-100 group-hover:scale-0': dynamicRemoveButton,
                })}
                context={'card'}/>
            {dynamicRemoveButton && <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"
                                         className="min-w-4 min-h-4 max-w-4 max-h-4 scale-0 group-hover:scale-100 absolute top-1/2 left-1/2 translate-x-[-50%] translate-y-[-50%] transition duration-400 text-gray-100">
                <path
                    d="M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z"/>
            </svg>}
        </div>
        }        <div className="w-full flex items-center space-x-2 justify-between">
            <div className={classNames('font-medium text-left', {
                'space-y-[2px]': !verticalDistance,
                [verticalDistance || 'default-vertical-distance']: verticalDistance
            })}>
                {cardRenderer.AboveComputedValue && <cardRenderer.AboveComputedValue color={color} context={context}/>}
                <cardRenderer.ComputedValue color={color} context={context}/>
                {cardRenderer.BelowComputedValue && <cardRenderer.BelowComputedValue color={color} context={context}/>}
            </div>
            {false && onRemoveClick && <button
                className={`group min-w-4 min-h-4 max-w-4 max-h-4 rounded-full ${request(colors?.icon?.close?.background ?? color, 'card-remove-button-background').get('background.lightDarker')}`}
                onClick={onRemoveClick ?? undefined}>
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"
                     className={`hidden group-hover:block ${request(colors?.icon?.close?.color ?? color, 'card-remove-button-icon').get('text.dark.primary')}`}>
                    <path
                        d="M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z"/>
                </svg>
            </button>}
        </div>
    </EmulatedButton>;
}
