'use strict';

var tslib_es6 = require('./tslib.es6-2c2ed574.js');
var React = require('react');
var core = require('@mantine/core');
var index$2 = require('./index-1e5e2223.js');
require('@mantine/dates');
var index = require('./index-6ce6e395.js');
require('./index-da3b86cd.js');
require('./index-b0ce6f8f.js');
require('./index-024542ed.js');
require('./index-a31ed3e1.js');
require('./index-3d563586.js');
require('./index-59a9827e.js');
require('./index.styles-691de58f.js');
var index$1 = require('./index-3643ff1b.js');
require('@mantine/hooks');
require('./utils-b92a8b1c.js');
require('./index-eba09ec0.js');
var utils = require('./utils-7210e0bb.js');
var Locale = require('./Locale-fbe01177.js');

function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefault(React);

const generateGetAddressDetail = (locale) => {
    return `${index.CDN_ADDRESS}/cities-data-${utils.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] = React.useReducer(reducer, initialState);
    const { provinceByName, provinces, districts, wards, selectedProvince, selectedDistrict, selectedWard, } = state;
    const [addressData, setAddressData] = React.useState();
    React.useEffect(() => {
        // Simulating the API call to fetch the address data
        const fetchAddressData = () => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
            var _a, _b, _c;
            try {
                const _addressData = yield fetch(generateGetAddressDetail(process.env.UNIFY_LOCALE || 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 = tslib_es6.__rest(_a, ["error", "provinces", "placeholder"]);
    const { t } = index$1.useTranslations();
    const { provinces, districts, wards, selectedProvince, selectedDistrict, selectedWard, handleProvinceChange, handleDistrictChange, handleWardChange, } = useAddress({ provinces: provincesInit });
    const [extraInfo, setExtraInfo] = React.useState('');
    React.useEffect(() => {
        if (selectedProvince && selectedDistrict && selectedWard && extraInfo) {
            props.onChange({
                selectedProvince,
                selectedDistrict,
                selectedWard,
                extraInfo,
            });
        }
        else {
            props.onChange(null);
        }
    }, [selectedProvince, selectedDistrict, selectedWard, extraInfo]);
    return (React__default["default"].createElement(index$2.Input.Wrapper, Object.assign({ withAsterisk: true }, props),
        React__default["default"].createElement(core.Stack, null,
            React__default["default"].createElement(index$2.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["default"].createElement(index$2.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["default"].createElement(index$2.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["default"].createElement(index$2.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["default"].createElement(core.Input.Error, { size: "md" }, error)));
};

exports.AddressInput = AddressInput;
