import {
    type ReactNode,
    Fragment
} from "react";
import {
    type ModalContextType,
    type ModalDataType
} from "../types/modal";
import NCoreContext, {
    type ConfigType
} from "ncore-context";
import Modal from "../components/modal";
import {
    uuid
} from "../utils";

class NCoreUIKitModal extends NCoreContext<ModalContextType, ConfigType<ModalContextType>> {
    constructor({
        data = []
    }: {
        data?: Array<ModalDataType>
    }) {
        super({
            close: () => {},
            open: () => {},
            data: data
        }, {
            key: "NCoreUIKit-ModalContext"
        });
    };

    open = (modalData: ModalDataType) => {
        const currentData = this.state.data;

        const modalID = modalData.id ? modalData.id : uuid();

        currentData.push({
            ...modalData,
            id: modalID
        });

        this.setState({
            data: currentData
        });
    };

    close = (props?: {
        index?: number;
        id?: string;
    }) => {
        const currentData = this.state.data;

        if (props && props.id) {
            const keyIndex = currentData.findIndex((modal) => modal.id === props.id);

            if (keyIndex !== -1) {
                currentData.splice(keyIndex, 1);

                this.setState({
                    data: currentData
                });
            }

            return;
        }

        if (props && props.index !== undefined) {
            currentData.splice(props.index, 1);

            this.setState({
                data: currentData
            });

            return;
        }

        currentData.pop();

        this.setState({
            data: currentData
        });
    };

    Render = ({
        children
    }: {
        children: ReactNode;
    }) => {
        const {
            data
        } = this.useContext();

        return <Fragment>
            {children}
            {data.map((item: ModalDataType) => {
                return <Modal
                    key={`NCoreUIKit-Modal-${item.id}`}
                    id={item.id as string}
                    onClosed={() => {
                        if(item.onClosed) item.onClosed({
                            id: item.id as string
                        });

                        if(item.isAutoClose === undefined || item.isAutoClose === true) {
                            this.close({
                                id: item.id
                            });
                        }
                    }}
                    {...item}
                />;
            })}
        </Fragment>;
    };
}
export default NCoreUIKitModal;
