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 TimeSelector from "../timeSelector";
import YearSelector from "../yearSelector";
import DateSelector from "../dateSelector";
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,
    isShowCalenderChangerTool,
    dayOfWeekLength = "short",
    LoadingIconComponentProp,
    multipleSelectMaximumMS,
    multipleSelectDayLimit,
    monthOfYearLengthType,
    selectMultipleObject,
    isWorkWithRealtime,
    isShowTools = true,
    isWorkWithSeconds,
    dateTimePickerKey,
    bottomSheetProps,
    bottomSheetRef,
    customLocalize,
    selectObject,
    customTheme,
    setIsActive,
    pickerType,
    dateRange,
    maxChoice,
    minChoice,
    isLoading,
    isActive,
    dateRule,
    variant,
    maxDate,
    minDate,
    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,
        loadingContainer: loadingContainerDynamicStyle,
        contentContainer: contentContainerDynamicStyle,
        headerContainer: headerContainerDynamicStyle,
        bottomContainer: bottomContainerDynamicStyle,
        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
                        variant="titleMediumSize"
                        style={[
                            headerTitleDynamicStyle
                        ]}
                    >
                        {title}
                    </Text>
                :
                    null
            }
            {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>;
    };

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