import {FC, forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState} from "react";
import {BottomSheetModal} from "@gorhom/bottom-sheet";
import {disableDim, enableDim} from "../../../features/interface/interfaceSlice";
import {StyleSheet, View} from "react-native";
import BasicButton from "../../BasicButton/BasicButton";
import {useDispatch, useSelector} from "react-redux";
import {RFPercentage} from "react-native-responsive-fontsize";
import RadioGroup from 'react-native-radio-buttons-group';
import {responsiveHeight, responsiveWidth} from "react-native-responsive-dimensions";
import {blue} from "../../../css/colors";
import {Picker} from "@react-native-picker/picker";
import DateTimePicker from '@react-native-community/datetimepicker';
import {RootState} from "../../../redux/store";
import {
    closeOrdersFilterModal,
    orderStatuses, setCity,
    setDesc,
    setOrderBy, setShipmentDate, setShippingWarehouse, setStatus
} from "../../../features/ordersFilter/ordersFilterSlice";
import ShippingWarehouseSelect from "../../ShippingWarehouseSelect/ShippingWarehouseSelect";
import CitySelect from "../../CitySelect/CitySelect";

export type SortingModalHandles = {
    present: () => void;
    dismiss: () => void;
}

export type SortingModalElement = {
    id: string;
    label: string;
    value: string;
}


const createRadioButton = (element: SortingModalElement) => {
    return {
        id: element.id,
        label: element.label,
        value: element.value,
        size: RFPercentage(5),
        color: blue,
        labelStyle: {
            fontSize: responsiveWidth(3),
            fontWeight: "500" as const
        },
        borderSize: RFPercentage(0.5)
    };
}

const SortingModal = () => {
    const state = useSelector((state: RootState) => state.ordersFilter);
    const shipmentWarehouseSelectorState = useSelector((state: RootState) => state.shippingWarehouseSelect);
    const citySelectorState = useSelector((state: RootState) => state.citySelect);

    const elements = [
        {id: 'createdOnAsc', value: 'createdOnAsc', label: 'Дата создания по возрастанию'},
        {id: 'createdOnDesc', value: 'createdOnDesc', label: 'Дата создания по убыванию'},
        {id: 'shipmentDateAsc', value: 'shipmentDateAsc', label: 'Дата отгрузки по возрастанию'},
        {id: 'shipmentDateDesc', value: 'shipmentDateDesc', label: 'Дата отгрузки по убыванию'},
    ];
    const [showShipmentPicker, setShowShipmentPicker] = useState(false);
    const snapPoints = useMemo(() => ['60%', '60%'], []);
    const dispatch = useDispatch();
    const modalRef = useRef<BottomSheetModal>(null);
    const dismiss = () => {
        if (!modalRef.current) return;
        dispatch(disableDim());
        modalRef.current.dismiss();
    }
    const present = () => {
        if (!modalRef.current) return;
        modalRef.current.present();
        dispatch(enableDim());
    }
    useEffect(() => {
        if (state.isVisible) present();
        else dismiss();
    }, [state.isVisible]);
    useEffect(() => {
        dispatch(setShippingWarehouse(shipmentWarehouseSelectorState.selectedShippingWarehouse));
    }, [shipmentWarehouseSelectorState.selectedShippingWarehouse]);
    useEffect(() => {
        dispatch(setCity(citySelectorState.selectedCity));
    }, [citySelectorState.selectedCity]);
    return (
        <BottomSheetModal
            ref={modalRef}
            snapPoints={snapPoints}
            onDismiss={() => {
                dispatch(disableDim());
                dispatch(closeOrdersFilterModal())
            }}>
            <View style={styles.container}>
                <View style={styles.content}>
                    <RadioGroup selectedId={state.orderBy + (state.desc ? "Desc" : "Asc")}
                                onPress={(event) => {
                                    const orderRegex = /(Asc|Desc)$/;
                                    const orderMatch = event.match(orderRegex);
                                    if (!orderMatch) return;
                                    const isDesc = orderMatch[0] === 'Desc';
                                    const orderByField = event.replace(orderRegex, '');
                                    if (!["createdOn", "shipmentDate"].includes(orderByField)) return
                                    dispatch(setDesc(isDesc));
                                    dispatch(setOrderBy(orderByField as "createdOn" | "shipmentDate"));

                                }}
                                containerStyle={styles.radioButtons}
                                radioButtons={elements.map(createRadioButton)}/>


                    <View style={styles.selectors}>
                        {/*<View style={styles.selector}>*/}
                        {/*    <Picker selectedValue={state.status}*/}
                        {/*            onValueChange={(value, event) => dispatch(setStatus(value))}>*/}
                        {/*        {orderStatuses.map((status) => {*/}
                        {/*            return (*/}
                        {/*                <Picker.Item*/}
                        {/*                    key={status.key}*/}
                        {/*                    label={status.label}*/}
                        {/*                    value={status.key}*/}
                        {/*                    style={{fontSize: responsiveWidth(3)}}*/}
                        {/*                />*/}
                        {/*            )*/}
                        {/*        })}*/}
                        {/*    </Picker>*/}
                        {/*</View>*/}

                        <ShippingWarehouseSelect/>
                        <CitySelect/>
                    </View>

                    {/*<BasicButton onPress={() => setShowShipmentPicker(oldValue => !oldValue)}*/}
                    {/*             label={"Выбрать дату отгрузки"}/>*/}
                    {/*{showShipmentPicker &&*/}
                    {/*    <DateTimePicker value={new Date(state.shipmentDate)}*/}
                    {/*                    onChange={(event) => {*/}
                    {/*                        if (!event.nativeEvent.timestamp) return;*/}
                    {/*                        setShowShipmentPicker(false);*/}
                    {/*                        if (event.type === 'set') {*/}
                    {/*                            const selectedDate = new Date(event.nativeEvent.timestamp);*/}
                    {/*                            dispatch(setShipmentDate(selectedDate.toISOString()));*/}
                    {/*                        }*/}
                    {/*                    }}/>}*/}
                </View>


                <BasicButton label={"Закрыть"} style={styles.button} onPress={() => {
                    dispatch(closeOrdersFilterModal());
                }}/>

            </View>
        </BottomSheetModal>
    )
};
const styles = StyleSheet.create({
    container: {
        width: "100%",
        height: "100%",
        flex: 1,
        padding: RFPercentage(3),
        flexDirection: "column",
        justifyContent: "space-between",
        rowGap: responsiveHeight(1)
    },
    radioButtons: {
        alignItems: "flex-start"
    },
    content: {
        rowGap: responsiveHeight(1)
    },
    button: {

        marginTop: "auto"
    },
    selectors: {
        rowGap: responsiveHeight(1)
    },
    selector: {
        borderWidth: responsiveWidth(0.1),
        borderRadius: responsiveWidth(1)
    }
});


export default SortingModal;
