import {
    TouchableOpacity,
    View
} from "react-native";
import {
    type SelectedItem
} from "./type";
import type ISelectSheetProps from "./type";
import stylesheet, {
    useStyles
} from "./stylesheet";
import {
    NCoreUIKitLocalize,
    NCoreUIKitTheme
} from "../../core/hooks";
import {
    CheckIcon
} from "lucide-react-native";
import BottomSheet from "../bottomSheet";
import TextInput from "../textInput";
import Loading from "../loading";
import Button from "../button";
import Text from "../text";
import CheckBox from "../checkBox";

function SelectSheet<T>({
    LoadingIconComponentProp,
    isWorkWithRealtime,
    isShowTools = true,
    mainSelectedItems,
    moreLoadThreshold,
    isMultipleSelect,
    setIsMoreLoading,
    renderOptionIcon,
    bottomSheetProps,
    bottomSheetRef,
    customLocalize,
    setSearchText,
    isMoreLoading,
    selectBoxKey,
    setIsLoading,
    selectObject,
    keyExtractor,
    searchedData,
    isSearchable,
    customTheme,
    setIsActive,
    onMoreLoad,
    renderItem,
    searchText,
    maxChoice,
    minChoice,
    isLoading,
    selectAll,
    cleanAll,
    isActive,
    cancel,
    title,
    data,
    ok
}: ISelectSheetProps<T>) {
    const {
        radiuses,
        colors,
        spaces
    } = NCoreUIKitTheme.useContext(customTheme);

    const {
        localize
    } = NCoreUIKitLocalize.useContext(customLocalize);

    const {
        moreLoadingContainer: moreLoadingContainerDynamicStyle,
        checkIconContainer: checkIconContainerDynamicStyle,
        loadingContainer: loadingContainerDynamicStyle,
        contentContainer: contentContainerDynamicStyle,
        headerContainer: headerContainerDynamicStyle,
        bottomContainer: bottomContainerDynamicStyle,
        toolsContainer: toolsContainerDynamicStyle,
        itemContainer: itemContainerDynamicStyle,
        cancelButton: cancelButtonDynamicStyle,
        headerTitle: headerTitleDynamicStyle,
        okButton: okButtonDynamicStyle
    } = useStyles({
        isSearchable,
        radiuses,
        spaces,
        colors
    });

    const renderBottomSheetContent = () => {
        if(isLoading) {
            return <View
                style={[
                    stylesheet.loadingContainer,
                    loadingContainerDynamicStyle
                ]}
            >
                {LoadingIconComponentProp ? <LoadingIconComponentProp
                    color="emphasized"
                    size={20}
                /> : <Loading/>}
            </View>;
        }

        const currentData = searchText && searchText.length ? searchedData : data;

        return <View
            style={[
                contentContainerDynamicStyle
            ]}
        >
            {
                currentData.map((item: T & SelectedItem | SelectedItem, index: number) => {
                    const isSelected = mainSelectedItems.findIndex((sI: SelectedItem) => {
                        return sI.__key === item.__key;
                    }) !== -1;

                    if(renderItem) {
                        return renderItem({
                            key: keyExtractor(item as T & SelectedItem, index),
                            onSelect: (sItem) => {
                                selectObject(sItem);
                            },
                            selectedItems: mainSelectedItems,
                            setIsMoreLoading,
                            setIsLoading,
                            isSelected,
                            searchText,
                            index,
                            item,
                            data
                        });
                    }

                    let isDisabled = false;

                    if(isMultipleSelect && !isSelected && maxChoice !== -1) {
                        if(!maxChoice) {
                            throw new Error("If you want to use the \"isMultipleSelect\" prop, you must be provide \"maxChoice\" prop.");
                        }

                        if(mainSelectedItems.length >= maxChoice) {
                            isDisabled = true;
                        }
                    }

                    return <TouchableOpacity
                        key={keyExtractor(item as T & SelectedItem, index)}
                        disabled={isDisabled}
                        style={[
                            stylesheet.itemContainer,
                            itemContainerDynamicStyle,
                            {
                                marginTop: index === 0 ? 0 : spaces.spacingSm,
                                position: "relative"
                            }
                        ]}
                        onPress={() => {
                            if(isDisabled) {
                                return;
                            }

                            selectObject(item);
                        }}
                    >
                        <View
                            style={[
                                stylesheet.itemContentContainer,
                                {
                                    zIndex: 99999
                                }
                            ]}
                        >
                            {renderOptionIcon ? renderOptionIcon({
                                item,
                                index
                            }) : null}
                            <Text
                                color={isSelected ? "emphasized" : undefined}
                            >{item.__title}</Text>
                        </View>
                        <View
                            style={[
                                stylesheet.checkIconContainer,
                                checkIconContainerDynamicStyle
                            ]}
                        >
                            {isSelected ?
                                <CheckIcon
                                    color={colors.content.icon.emphasized}
                                    size={24}
                                /> : null}
                        </View>
                        {isDisabled ? <View
                            style={[
                                {
                                    backgroundColor: colors.system.disabled.content,
                                    borderRadius: radiuses.actions,
                                    position: "absolute",
                                    zIndex: 99998,
                                    bottom: 0,
                                    right: 0,
                                    left: 0,
                                    top: 0
                                }
                            ]}
                        /> : null}
                    </TouchableOpacity>;
                })
            }
            {renderMoreLoading()}
        </View>;
    };

    const renderBottomSheetSearchInput = () => {
        if(!isSearchable) {
            return null;
        }

        return <TextInput
            key={`${selectBoxKey}-searchInput`}
            placeholder={localize("search")}
            spreadBehaviour="stretch"
            onChangeText={(text: string) => {
                setSearchText(text);
            }}
        />;
    };

    const renderTools = () => {
        if(!isShowTools) {
            return null;
        }

        if(!isMultipleSelect) {
            return null;
        }

        if(minChoice && maxChoice !== -1) {
            return null;
        }

        return <View
            style={[
                stylesheet.toolsContainer,
                toolsContainerDynamicStyle
            ]}
        >
            {!minChoice ? <CheckBox
                isChecked={mainSelectedItems.length === 0 ? "checked" : null}
                title={localize("clean-all")}
                spreadBehaviour="free"
                onPress={() => {
                    cleanAll();
                }}
            /> : null}
            {maxChoice === -1 ? <CheckBox
                isChecked={data.length === mainSelectedItems.length ? "checked" : mainSelectedItems.length ? "partially" : null}
                title={localize("select-all")}
                spreadBehaviour="free"
                isFlip={!minChoice}
                onPress={() => {
                    selectAll();
                }}
            /> : null}
        </View>;
    };

    const renderBottomSheetHeader = () => {
        return <View
            style={[
                stylesheet.headerContainer,
                headerContainerDynamicStyle
            ]}
        >
            <Text
                variant="titleMediumSize"
                style={[
                    headerTitleDynamicStyle
                ]}
            >
                {title}
            </Text>
            {renderBottomSheetSearchInput()}
            {renderTools()}
        </View>;
    };

    const renderBottomSheetBottom = () => {
        if(isWorkWithRealtime) {
            return null;
        }

        return <View
            style={[
                stylesheet.bottomContainer,
                bottomContainerDynamicStyle
            ]}
        >
            <Button
                title={localize("cancel")}
                spreadBehaviour="stretch"
                variant="outline"
                type="neutral"
                onPress={() => {
                    cancel();
                }}
                style={{
                    ...cancelButtonDynamicStyle
                }}
            />
            <Button
                spreadBehaviour="stretch"
                title={localize("ok")}
                onPress={() => {
                    ok();
                }}
                style={{
                    ...okButtonDynamicStyle
                }}
            />
        </View>;
    };

    const renderMoreLoading = () => {
        if(!isMoreLoading) {
            return null;
        }

        return <View
            style={[
                stylesheet.moreLoadingContainer,
                moreLoadingContainerDynamicStyle
            ]}
        >
            <Loading/>
        </View>;
    };

    return <BottomSheet
        {...bottomSheetProps}
        scrollEndThreshold={moreLoadThreshold}
        key={`${selectBoxKey}-bottomsheet`}
        customKey={selectBoxKey}
        ref={bottomSheetRef}
        isAutoHeight={true}
        isActive={isActive}
        onScrollEnd={() => {
            if(onMoreLoad) onMoreLoad({
                selectedItems: mainSelectedItems,
                setIsMoreLoading,
                setIsLoading,
                searchText,
                data
            });
        }}
        renderBottom={() => {
            return renderBottomSheetBottom();
        }}
        renderHeader={() => {
            return renderBottomSheetHeader();
        }}
        onClose={() => {
            setIsActive(false);
        }}
    >
        {renderBottomSheetContent()}
    </BottomSheet>;
};
export default SelectSheet;
