import type { ModalFormProps } from '@ant-design/pro-components';
import { ModalForm } from '@ant-design/pro-components';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { useRef, useState } from 'react';
import Draggable from 'react-draggable';

export type MovableModalFormProps<T = Record<string, any>> = ModalFormProps<T>;

const MovableModalForm = <T extends Record<string, any>>(props: MovableModalFormProps<T>) => {
    const { title, children, modalProps, ...restProps } = props;

    const [disabled, setDisabled] = useState<boolean>(true);
    const draggleRef = useRef<any>();
    const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });
    const onStart = (event: any, uiData: any) => {
        const { clientWidth, clientHeight } = window?.document?.documentElement;
        const targetRect = draggleRef?.current?.getBoundingClientRect();
        setBounds({
            left: -targetRect?.left + uiData?.x,
            right: clientWidth - (targetRect?.right - uiData?.x),
            top: -targetRect?.top + uiData?.y,
            bottom: clientHeight - (targetRect?.bottom - uiData?.y),
        });
    };

    const titleClassName = useEmotionCss(({ token }) => {
        return {
            padding: `${token.padding}px ${token.paddingLG}px`,
            marginTop: -token.marginMD,
            marginLeft: -token.paddingLG,
            marginRight: -token.marginLG,
            ':hover': {
                backgroundColor: 'rgba(0, 0, 0, 0.01)',
                cursor: 'move',
            },
        };
    });

    return (
        <ModalForm<T>
            title={
                <div
                    className={titleClassName}
                    onMouseOver={() => disabled && setDisabled(false)}
                    onMouseOut={() => setDisabled(true)}
                >
                    {title}
                </div>
            }
            modalProps={{
                centered: true,
                ...modalProps,
                modalRender: (modal) => (
                    <Draggable
                        disabled={disabled}
                        bounds={bounds}
                        onStart={(event, uiData) => onStart(event, uiData)}
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                ),
            }}
            {...restProps}
        >
            {children}
        </ModalForm>
    );
};

export default MovableModalForm;
