import { a as __awaiter, _ as __rest } from './tslib.es6-ab63fd84.js';
import React__default, { useReducer, useState, useEffect } from 'react';
import { Stack, Input as Input$1 } from '@mantine/core';
import { I as Input, S as Select } from './index-c3177e04.js';
import '@mantine/dates';
import { g as CDN_ADDRESS } from './index-a8162282.js';
import './index-91c6a49c.js';
import './index-43584299.js';
import './index-4e6b8a2b.js';
import './index-d0a1200e.js';
import './index-f71a880f.js';
import './index-38e03570.js';
import './index.styles-3ba274d2.js';
import { u as useTranslations } from './index-960c3169.js';
import '@mantine/hooks';
import './utils-32d7d5af.js';
import './index-f21110d2.js';
import { M as MAPPED_LOCALE } from './utils-42d7e284.js';
import { L as LOCALE } from './Locale-87b46912.js';

const generateGetAddressDetail = (locale) => {
    return `${CDN_ADDRESS}/cities-data-${MAPPED_LOCALE[locale]}.json`;
};

const initialState = {
    provinceByName: {},
    provinces: [],
    districts: [],
    wards: [],
    selectedProvince: '',
    selectedDistrict: '',
    selectedWard: '',
};
const reducer = (state, action) => {
    switch (action.type) {
        case 'SET_DATA':
            return Object.assign(Object.assign({}, state), action.payload);
        case 'SET_DISTRICTS':
            return Object.assign(Object.assign({}, state), { districts: action.payload });
        case 'SET_WARDS':
            return Object.assign(Object.assign({}, state), { wards: action.payload });
        case 'SELECT_PROVINCE':
            return Object.assign(Object.assign({}, state), { selectedProvince: action.payload, selectedDistrict: '', selectedWard: '' });
        case 'SELECT_DISTRICT':
            return Object.assign(Object.assign({}, state), { selectedDistrict: action.payload, selectedWard: '' });
        case 'SELECT_WARD':
            return Object.assign(Object.assign({}, state), { selectedWard: action.payload });
        default:
            return state;
    }
};
const mappingProvinceId = (provinces, hbProvincesList) => {
    const listById = {};
    for (const [, value] of Object.entries(hbProvincesList)) {
        const { id } = value;
        if (id) {
            listById[id] = value;
        }
    }
    const list = {};
    provinces.map((i) => {
        list[i.name] = listById[i.id];
    });
    return list;
};
const useAddress = ({ provinces: provincesInit }) => {
    const [state, dispatch] = useReducer(reducer, initialState);
    const { provinceByName, provinces, districts, wards, selectedProvince, selectedDistrict, selectedWard, } = state;
    const [addressData, setAddressData] = useState();
    useEffect(() => {
        // Simulating the API call to fetch the address data
        const fetchAddressData = () => __awaiter(void 0, void 0, void 0, function* () {
            var _a, _b, _c;
            try {
                const _addressData = yield fetch(generateGetAddressDetail(process.env.UNIFY_LOCALE || LOCALE.Vietnam)).then((res) => res.json());
                setAddressData(_addressData);
                const { list } = _addressData;
                const provinceByName = provincesInit
                    ? mappingProvinceId(provincesInit, list)
                    : list;
                const provincesData = Object.keys(provinceByName);
                const districtsData = Object.keys(((_a = list[provincesData[0]]) === null || _a === void 0 ? void 0 : _a.list) || {});
                const wardsData = Object.keys(((_c = (_b = list[provincesData[0]]) === null || _b === void 0 ? void 0 : _b[districtsData[0]]) === null || _c === void 0 ? void 0 : _c.list) || {});
                dispatch({
                    type: 'SET_DATA',
                    payload: {
                        provinceByName,
                        provinces: provincesData,
                        districts: districtsData,
                        wards: wardsData,
                    },
                });
            }
            catch (error) {
                console.error('Error fetching address data:', error);
            }
        });
        fetchAddressData();
    }, [process.env.UNIFY_LOCALE]);
    const handleProvinceChange = (_selectedProvince) => {
        var _a;
        const districtsData = Object.keys(((_a = provinceByName[_selectedProvince]) === null || _a === void 0 ? void 0 : _a.list) || {});
        dispatch({ type: 'SET_DISTRICTS', payload: districtsData });
        dispatch({ type: 'SET_WARDS', payload: [] });
        dispatch({ type: 'SELECT_PROVINCE', payload: _selectedProvince });
    };
    const handleDistrictChange = (_selectedDistrict) => {
        var _a, _b;
        const wardsData = Object.keys(((_b = (_a = provinceByName[selectedProvince]) === null || _a === void 0 ? void 0 : _a.list[_selectedDistrict]) === null || _b === void 0 ? void 0 : _b.list) || {});
        dispatch({ type: 'SET_WARDS', payload: wardsData });
        dispatch({ type: 'SELECT_DISTRICT', payload: _selectedDistrict });
    };
    const handleWardChange = (_selectedWard) => {
        dispatch({ type: 'SELECT_WARD', payload: _selectedWard });
    };
    return {
        provinces,
        districts,
        wards,
        selectedProvince,
        selectedDistrict,
        selectedWard,
        handleProvinceChange,
        handleDistrictChange,
        handleWardChange,
    };
};

const AddressInput = (_a) => {
    var { error, provinces: provincesInit, placeholder } = _a, props = __rest(_a, ["error", "provinces", "placeholder"]);
    const { t } = useTranslations();
    const { provinces, districts, wards, selectedProvince, selectedDistrict, selectedWard, handleProvinceChange, handleDistrictChange, handleWardChange, } = useAddress({ provinces: provincesInit });
    const [extraInfo, setExtraInfo] = useState('');
    useEffect(() => {
        if (selectedProvince && selectedDistrict && selectedWard && extraInfo) {
            props.onChange({
                selectedProvince,
                selectedDistrict,
                selectedWard,
                extraInfo,
            });
        }
        else {
            props.onChange(null);
        }
    }, [selectedProvince, selectedDistrict, selectedWard, extraInfo]);
    return (React__default.createElement(Input.Wrapper, Object.assign({ withAsterisk: true }, props),
        React__default.createElement(Stack, null,
            React__default.createElement(Select, { placeholder: (placeholder === null || placeholder === void 0 ? void 0 : placeholder.province) || t('onboarding.similac.input.city'), data: provincesInit ? provinces : provinces.sort(), searchable: true, onChange: handleProvinceChange, value: selectedProvince }),
            React__default.createElement(Select, { placeholder: (placeholder === null || placeholder === void 0 ? void 0 : placeholder.district) || t('onboarding.similac.input.district'), data: districts.sort(), searchable: true, onChange: handleDistrictChange, value: selectedDistrict, disabled: !selectedProvince }),
            React__default.createElement(Select, { placeholder: (placeholder === null || placeholder === void 0 ? void 0 : placeholder.ward) || t('onboarding.similac.input.ward'), searchable: true, data: wards.sort(), value: selectedWard, onChange: handleWardChange, disabled: !selectedProvince || !selectedDistrict }),
            React__default.createElement(Input, { placeholder: (placeholder === null || placeholder === void 0 ? void 0 : placeholder.address) || t('onboarding.similac.input.no'), disabled: !selectedProvince || !selectedDistrict || !selectedWard, value: extraInfo, onChange: setExtraInfo, style: { marginBottom: 0 } })),
        React__default.createElement(Input$1.Error, { size: "md" }, error)));
};

export { AddressInput as A };
