import {useEffect, useState} from "react";
import {useRequest} from "@witel/webapp-builder";
import {useTranslations} from "next-intl";
import {GET_CITIES_LIST} from "@/core/data/apiRoutes";

const useCities = () => {
    const t = useTranslations();
    const [provinceID, setProvinceID] = useState(null)
    const [cityList, setCityList] = useState([]);
    const [cityTextField, setCityTextField] = useState(t("text_field_city_id"));
    const [isLoadingCityList, setIsLoadingCityList] = useState(false)
    const requestServer = useRequest({auth: true, notification: false})

    useEffect(() => {
        if (provinceID === null) return
        setIsLoadingCityList(true)
        setCityTextField(t("text_field_loading_cities_list"))
        requestServer(`${GET_CITIES_LIST}?province_id=${provinceID}`, "get", {auth: true, notification: false})
            .then(({data}) => {
                const result = data.data;
                const formattedData = result.map((city, index) => ({
                    id: index,
                    name: city.name,
                    value: city.id,
                }));
                setCityList(formattedData);
                setIsLoadingCityList(false)
                setCityTextField(t("text_field_city_id"))
            }).catch(() => {
            setIsLoadingCityList(false)
            setCityTextField(t("text_field_error_fetching_cities"))
        });
    }, [provinceID])


    return {cityTextField, cityList, setProvinceID, isLoadingCityList}
}
export default useCities