import {
    type ReactNode,
    Fragment
} from "react";
import {
    type ToastContextType,
    type ToastDataType
} from "../types/toast";
import NCoreContext, {
    type ConfigType
} from "ncore-context";
import Toast from "../components/toast";
import {
    uuid
} from "../utils";

class NCoreUIKitToast extends NCoreContext<ToastContextType, ConfigType<ToastContextType>> {
    constructor({
        data = []
    }: {
        data?: Array<ToastDataType>
    }) {
        super({
            close: () => {},
            open: () => "",
            data: data
        }, {
            key: "NCoreUIKit-ToastContext"
        });
    };

    open = (toastData: ToastDataType) => {
        const currentData = this.state.data;

        const toastID = toastData.id ? toastData.id : uuid();

        currentData.push({
            ...toastData,
            id: toastID
        });

        this.setState({
            data: currentData
        });

        return toastID;
    };

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

        if (props && props.id) {
            const keyIndex = currentData.findIndex((toast) => toast.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: ToastDataType) => {
                return <Toast
                    key={`NCoreUIKit-Toast-${item.id}`}
                    {...item}
                    id={item.id as string}
                    onClosed={(props) => {
                        this.close({
                            id: item.id
                        });

                        if(item.onClosed) item.onClosed(props);
                    }}
                />;
            })}
        </Fragment>;
    };
}
export default NCoreUIKitToast;
