import {FC, useEffect} from "react";
import {useDispatch, useSelector} from "react-redux";
import {RootState} from "../../redux/store";
import {Picker} from "@react-native-picker/picker";
import generalApi from "../../api/generalApi";

import {responsiveWidth} from "react-native-responsive-dimensions";
import {View} from "react-native";
import {initializeCitySelect, selectCity} from "../../features/citySelect/citySelectSlice";

const CitySelect: FC = () => {
    const state = useSelector((state: RootState) => state.citySelect);
    const dispatch = useDispatch();
    useEffect(() => {
        if (state.initialized) return;
        generalApi.getCities().then(cities =>
            dispatch(initializeCitySelect(cities)))
    }, []);
    return (
        <View style={{
            borderWidth: responsiveWidth(0.1),
            borderRadius: responsiveWidth(1)
        }}>
            <Picker
                selectedValue={state.selectedCity?.id}
                onValueChange={(value, event) => dispatch(selectCity({cityId: value}))}
            >
                {state.cities.map(city => (
                    <Picker.Item
                        key={city.id}
                        label={city.name}
                        value={city.id}
                        style={{fontSize: responsiveWidth(3)}}
                    />
                ))}
            </Picker>
        </View>

    )
}

export default CitySelect;