import {
    useState,
    useRef
} from "react";
import {
    TouchableOpacity,
    View
} from "react-native";
import type IDateTimeSheetProps from "./type";
import stylesheet, {
    useStyles
} from "./stylesheet";
import {
    NCoreUIKitLocalize,
    NCoreUIKitTheme
} from "../../core/hooks";
import type {
    IDateSelectorRef
} from "../dateSelector/type";
import type {
    IMonthSelectorRef
} from "../monthSelector/type";
import type {
    IYearSelectorRef
} from "../yearSelector/type";
import MonthSelector from "../monthSelector";
import DateSelector from "../dateSelector";
import TimeSelector from "../timeSelector";
import YearSelector from "../yearSelector";
import BottomSheet from "../bottomSheet";
import CheckBox from "../checkBox";
import Loading from "../loading";
import Button from "../button";
import Text from "../text";

const DateTimeSheet = ({
    isTimeSelectWorksWithCenterWhenTimePicker,
    dateCalendarType: dateCalendarTypeProp,
    multipleSelectMinimumRequiredDayCount,
    localeBasedFirstDayOfWeek = true,
    multipleSelectMinimumRequireMS,
    isShowTodayIndicator = true,
    dayOfWeekLength = "short",
    isShowCalenderChangerTool,
    LoadingIconComponentProp,
    multipleSelectMaximumMS,
    multipleSelectDayLimit,
    monthOfYearLengthType,
    selectMultipleObject,
    isShowTools = true,
    isWorkWithRealtime,
    dateTimePickerKey,
    isWorkWithSeconds,
    bottomSheetProps,
    bottomSheetRef,
    customLocalize,
    selectObject,
    customTheme,
    setIsActive,
    pickerType,
    dateRange,
    isLoading,
    maxChoice,
    minChoice,
    dateRule,
    isActive,
    maxDate,
    minDate,
    variant,
    cancel,
    clean,
    title,
    date,
    ok
}: IDateTimeSheetProps) => {
    const {
        radiuses,
        borders,
        spaces,
        colors
    } = NCoreUIKitTheme.useContext(customTheme);

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

    const [
        isSheetContentReady,
        setIsSheetContentReady
    ] = useState(false);

    const [
        dateCalendarType,
        setDateCalendarType
    ] = useState(dateCalendarTypeProp ?? "day");

    const monthCalendarRef = useRef<IMonthSelectorRef>(null);
    const yearCalendarRef = useRef<IYearSelectorRef>(null);
    const dayCalendarRef = useRef<IDateSelectorRef>(null);

    const {
        calendarChangerToolContainer: calendarChangerToolContainerDynamicStyle,
        calendarChangerToolButton: calendarChangerToolButtonDynamicStyle,
        contentContainer: contentContainerDynamicStyle,
        loadingContainer: loadingContainerDynamicStyle,
        bottomContainer: bottomContainerDynamicStyle,
        headerContainer: headerContainerDynamicStyle,
        toolsContainer: toolsContainerDynamicStyle,
        cancelButton: cancelButtonDynamicStyle,
        headerTitle: headerTitleDynamicStyle,
        okButton: okButtonDynamicStyle
    } = useStyles({
        radiuses,
        borders,
        spaces,
        colors
    });

    const renderCalenderChangerTool = () => {
        if(!isShowCalenderChangerTool) {
            return null;
        }

        if(dateCalendarTypeProp) {
            return null;
        }

        return <View
            style={[
                stylesheet.calendarChangerToolContainer,
                calendarChangerToolContainerDynamicStyle
            ]}
        >
            <TouchableOpacity
                style={[
                    stylesheet.calendarChangerToolButton,
                    calendarChangerToolButtonDynamicStyle,
                    dateCalendarType === "day" ? {
                        backgroundColor: colors.content.container.primary
                    } : null
                ]}
                onPress={() => {
                    setDateCalendarType("day");
                }}
            >
                <Text
                    color={dateCalendarType === "day" ? "onPrimary" : undefined}
                >
                    {localize("daily")}
                </Text>
            </TouchableOpacity>
            <TouchableOpacity
                style={[
                    stylesheet.calendarChangerToolButton,
                    calendarChangerToolButtonDynamicStyle,
                    dateCalendarType === "month" ? {
                        backgroundColor: colors.content.container.primary
                    } : null
                ]}
                onPress={() => {
                    setDateCalendarType("month");
                }}
            >
                <Text
                    color={dateCalendarType === "month" ? "onPrimary" : undefined}
                >
                    {localize("monthly")}
                </Text>
            </TouchableOpacity>
            <TouchableOpacity
                style={[
                    stylesheet.calendarChangerToolButton,
                    calendarChangerToolButtonDynamicStyle,
                    dateCalendarType === "year" ? {
                        backgroundColor: colors.content.container.primary
                    } : null
                ]}
                onPress={() => {
                    setDateCalendarType("year");
                }}
            >
                <Text
                    color={dateCalendarType === "year" ? "onPrimary" : undefined}
                >
                    {localize("yearly")}
                </Text>
            </TouchableOpacity>
        </View>;
    };

    const renderDateCalendar = () => {
        if(pickerType === "time") {
            return null;
        }

        if(dateCalendarType === "month") {
            return <MonthSelector
                multipleSelectMinimumRequiredDayCount={multipleSelectMinimumRequiredDayCount}
                setIsSheetContentReady={setIsSheetContentReady}
                multipleSelectDayLimit={multipleSelectDayLimit}
                monthOfYearLengthType={monthOfYearLengthType}
                selectMultipleObject={selectMultipleObject}
                isShowTodayIndicator={isShowTodayIndicator}
                selectObject={selectObject}
                ref={monthCalendarRef}
                dateRange={dateRange}
                maxDate={maxDate}
                minDate={minDate}
                variant={variant}
                date={date}
            />;
        }

        if(dateCalendarType === "year") {
            return <YearSelector
                multipleSelectMinimumRequiredDayCount={multipleSelectMinimumRequiredDayCount}
                setIsSheetContentReady={setIsSheetContentReady}
                multipleSelectDayLimit={multipleSelectDayLimit}
                selectMultipleObject={selectMultipleObject}
                isShowTodayIndicator={isShowTodayIndicator}
                selectObject={selectObject}
                dateRange={dateRange}
                ref={yearCalendarRef}
                maxDate={maxDate}
                minDate={minDate}
                variant={variant}
                date={date}
            />;
        }

        return <DateSelector
            multipleSelectMinimumRequiredDayCount={multipleSelectMinimumRequiredDayCount}
            localeBasedFirstDayOfWeek={localeBasedFirstDayOfWeek}
            setIsSheetContentReady={setIsSheetContentReady}
            multipleSelectDayLimit={multipleSelectDayLimit}
            selectMultipleObject={selectMultipleObject}
            isShowTodayIndicator={isShowTodayIndicator}
            dayOfWeekLength={dayOfWeekLength}
            selectObject={selectObject}
            dateRange={dateRange}
            ref={dayCalendarRef}
            maxDate={maxDate}
            minDate={minDate}
            variant={variant}
            date={date}
        />;
    };

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

        return <View
            style={[
                stylesheet.contentContainer,
                contentContainerDynamicStyle
            ]}
        >
            {renderCalenderChangerTool()}
            {renderDateCalendar()}
            {
                pickerType === "date" ?
                    null
                :
                    <TimeSelector
                        isTimeSelectWorksWithCenterWhenTimePicker={isTimeSelectWorksWithCenterWhenTimePicker}
                        multipleSelectMinimumRequireMS={multipleSelectMinimumRequireMS}
                        multipleSelectMaximumMS={multipleSelectMaximumMS}
                        setIsSheetContentReady={setIsSheetContentReady}
                        selectMultipleObject={selectMultipleObject}
                        isWorkWithSeconds={isWorkWithSeconds}
                        selectObject={selectObject}
                        pickerType={pickerType}
                        dateRange={dateRange}
                        maxDate={maxDate}
                        minDate={minDate}
                        variant={variant}
                        date={date}
                    />
            }
        </View>;
    };

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

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

        let isAnySelected = false;

        if(variant === "single" && date) {
            isAnySelected = true;
        }

        if(variant === "range" && dateRange && (dateRange.start || dateRange.end)) {
            isAnySelected = true;
        }

        if(variant === "rrule" && dateRule) {
            isAnySelected = true;
        }

        return <View
            style={[
                stylesheet.toolsContainer,
                toolsContainerDynamicStyle
            ]}
        >
            {
                !minChoice ?
                    <CheckBox
                        isChecked={isAnySelected ? "checked" : null}
                        title={localize("clean-selection")}
                        spreadBehaviour="free"
                        onPress={() => {
                            clean();
                        }}
                    />
                :
                    null
            }
            <Button
                onPress={() => {
                    if(monthCalendarRef.current) monthCalendarRef.current.changeCurrentYear(new Date());
                    if(yearCalendarRef.current) yearCalendarRef.current.changeCurrentView(new Date());
                    if(dayCalendarRef.current) dayCalendarRef.current.changeCurrentMonth(new Date());
                }}
                title={localize("go-to-today")}
                spreadBehaviour="free"
                size="small"
            />
        </View>;
    };

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

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

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

    return <BottomSheet
        {...bottomSheetProps}
        key={`${dateTimePickerKey}-bottomsheet`}
        renderBottom={() => {
            return renderBottomSheetBottom();
        }}
        renderHeader={() => {
            return renderBottomSheetHeader();
        }}
        isContentReady={isSheetContentReady}
        customKey={dateTimePickerKey}
        onClosed={() => {
            setIsActive(false);
        }}
        ref={bottomSheetRef}
        isAutoHeight={true}
        isActive={isActive}
    >
        {renderBottomSheetContent()}
    </BottomSheet>;
};
export default DateTimeSheet;
