import {
    type ReactNode,
    Fragment
} from "react";
import {
    type SnackBarContextType,
    type SnackBarDataType
} from "../types/snackBar";
import NCoreContext, {
    type ConfigType
} from "ncore-context";
import SnackBar from "../components/snackBar";
import {
    uuid
} from "../utils";

class NCoreUIKitSnackBar extends NCoreContext<SnackBarContextType, ConfigType<SnackBarContextType>> {
    constructor({
        data = []
    }: {
        data?: Array<SnackBarDataType>
    }) {
        super({
            close: () => {},
            open: () => "",
            data: data
        }, {
            key: "NCoreUIKit-SnackBarContext"
        });
    };

    open = (snackBarData: SnackBarDataType) => {
        const currentData = this.state.data;

        const snackBarID = snackBarData.id ? snackBarData.id : uuid();

        currentData.push({
            ...snackBarData,
            id: snackBarID
        });

        this.setState({
            data: currentData
        });

        return snackBarID;
    };

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

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

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