import {
    type ReactNode,
    Fragment
} from "react";
import {
    type BottomSheetContextType,
    type BottomSheetDataType
} from "../types/bottomSheet";
import NCoreContext, {
    type ConfigType
} from "ncore-context";
import BottomSheet from "../components/bottomSheet";
import {
    uuid
} from "../utils";

class NCoreUIKitBottomSheet extends NCoreContext<BottomSheetContextType, ConfigType<BottomSheetContextType>> {
    constructor({
        data = []
    }: {
        data?: Array<BottomSheetDataType>
    }) {
        super({
            close: () => {},
            open: () => "",
            data: data
        }, {
            key: "NCoreUIKit-BottomSheetContext"
        });
    };

    open = (dialogData: BottomSheetDataType) => {
        const currentData = this.state.data;

        const dialogID = dialogData.id ? dialogData.id : uuid();

        currentData.push({
            ...dialogData,
            id: dialogID
        });

        this.setState({
            data: currentData
        });

        return dialogID;
    };

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

        if (props && props.id) {
            const keyIndex = currentData.findIndex((bottomSheet) => bottomSheet.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: BottomSheetDataType) => {
                return <BottomSheet
                    key={`NCoreUIKit-BottomSheet-${item.id}`}
                    id={item.id as string}
                    isActive={true}
                    onClosed={() => {
                        if(item.onClosed) {
                            item.onClosed({
                                id: item.id as string
                            });
                        }

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