'use client'
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
var yup = require('yup');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
var utils = require('@dynamic-labs/utils');
var MockContext = require('../../../context/MockContext/MockContext.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react/jsx-runtime');
require('../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
var index = require('../../../shared/utils/functions/getValueByKey/index.cjs');
require('../../constants/colors.cjs');
require('../../constants/values.cjs');
var index$1 = require('../../../shared/consts/index.cjs');
var useFields = require('../../../views/CollectUserDataView/useFields.cjs');

// Hook that returns the prepared data to work with the formik
// In order to update or display user information
const useUserDataForm = ({ onSubmit, onError, userProfile, shouldEnforcePolicies = true, fields, }) => {
    var _a;
    const { mockedSDK } = MockContext.useMockContext();
    const [fetch, setFetch] = React.useState(false);
    const { fieldsConfig } = useFields.useFields();
    const enforcePolicies = shouldEnforcePolicies &&
        ((_a = fields.find((setting) => setting.name === 'policiesConsent')) === null || _a === void 0 ? void 0 : _a.enabled);
    const requiredTitleCase = (name) => `${name.charAt(0).toUpperCase() + name.slice(1)} is required`;
    const formikValidationSchema = React.useMemo(() => yup.object().shape(Object.fromEntries(fields.map(({ name, required, type, validationType, validationRules }) => {
        let schema = type === sdkApiCore.KycFieldType.Custom
            ? index.getValueByKey(useFields.customFieldValidationMap, validationType)
            : index.getValueByKey(fieldsConfig, name).validation;
        if (type === sdkApiCore.KycFieldType.Custom &&
            validationRules &&
            (validationType === sdkApiCore.CustomFieldType.Select ||
                validationType === sdkApiCore.CustomFieldType.Text)) {
            schema = schema;
            if (validationRules.validOptions) {
                schema = schema.oneOf(validationRules.validOptions.map((option) => option.label), 'Select a valid option');
            }
            else if (validationRules.regex) {
                schema = schema.matches(new RegExp(validationRules.regex), 'Invalid field format');
            }
        }
        return [
            name,
            required ? schema.required(requiredTitleCase(name)) : schema,
        ];
    }))), [fields]);
    const formikInitialValues = React.useMemo(() => Object.fromEntries(fields.map(({ name, type, validationRules, validationType }) => {
        var _a, _b, _c, _d;
        const info = (userProfile !== null && userProfile !== void 0 ? userProfile : {});
        if (type === sdkApiCore.KycFieldType.Custom) {
            let defaultValue = '';
            if (validationType === sdkApiCore.CustomFieldType.Select &&
                (validationRules === null || validationRules === void 0 ? void 0 : validationRules.validOptions))
                defaultValue = (_a = validationRules.validOptions[0].label) !== null && _a !== void 0 ? _a : '';
            return [
                name,
                (() => {
                    var _a;
                    const value = info.metadata
                        ? index.getValueByKey(info.metadata, name)
                        : undefined;
                    return Array.isArray(value)
                        ? value
                        : (_a = value === null || value === void 0 ? void 0 : value.toString()) !== null && _a !== void 0 ? _a : defaultValue;
                })(),
            ];
        }
        const mapNameToDefaultValue = {
            country: index$1.countryCodes[0].code,
            policiesConsent: false,
            tShirtSize: index$1.tShirtSizes[0],
            team: index$1.teamNames[0],
        };
        const defaultValue = (_b = mapNameToDefaultValue[name]) !== null && _b !== void 0 ? _b : '';
        return [name, (_d = (_c = index.getValueByKey(info, name)) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : defaultValue];
    })) || {}, [fields, userProfile]);
    const onFormSubmit = React.useCallback((values, formikHelper) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const metadata = {};
        const uniqueMetadata = {};
        if (mockedSDK)
            return;
        try {
            if (!(userProfile === null || userProfile === void 0 ? void 0 : userProfile.environmentId))
                throw new utils.DynamicError('Invalid environment ID', 'invalid_environment_id');
            setFetch(true);
            let updatedUserFields = values;
            // all kyc fields including custom are in the object, move custom fields to the object.metadata
            Object.entries(updatedUserFields).forEach(([fieldName, fieldValue]) => {
                const field = fields.find((f) => f.name === fieldName && f.type === sdkApiCore.KycFieldType.Custom);
                if (field) {
                    metadata[fieldName] = fieldValue;
                    delete updatedUserFields[fieldName];
                    if (field.unique)
                        uniqueMetadata[fieldName] = fieldValue;
                }
            });
            if (Object.keys(metadata).length > 0)
                updatedUserFields.metadata = metadata;
            if (enforcePolicies) {
                updatedUserFields = Object.assign(Object.assign({}, updatedUserFields), { policiesConsent: true });
                delete updatedUserFields.policiesConsentArray;
            }
            yield (onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(updatedUserFields));
        }
        catch (e) {
            logger.logger.error(e);
            onError === null || onError === void 0 ? void 0 : onError(e);
            if (e instanceof utils.EmailAlreadyExistsError) {
                formikHelper.setErrors({ email: 'Email already exists' });
            }
            else if (e instanceof utils.CustomFieldNotUniqueError) {
                // clear all non error fields because user has to edit them anyways for the validation to pass, not sure why
                formikHelper.setFormikState((state) => (Object.assign(Object.assign({}, state), { errors: Object.fromEntries(Object.entries(uniqueMetadata).map(([customFieldName]) => [
                        customFieldName,
                        Object.entries(uniqueMetadata).length > 1
                            ? 'One or more fields are already tied to another user'
                            : `${customFieldName} is already tied to another user`,
                    ])), touched: Object.fromEntries(Object.entries(uniqueMetadata).map(([fieldName]) => [
                        fieldName,
                        true,
                    ])), values: Object.assign(Object.assign({}, formikInitialValues), uniqueMetadata) })));
            }
            else if (e instanceof utils.TooManyEmailVerificationsError) {
                formikHelper.setErrors({
                    email: 'Too many email verification attempts.',
                });
            }
            else if (e instanceof utils.UsernameAlreadyExistsError) {
                formikHelper.setErrors({ username: 'Username already exists' });
            }
            else if (e instanceof utils.InvalidPhoneNumberError) {
                formikHelper.setErrors({ phoneNumber: e.message });
            }
            else {
                formikHelper.setErrors({
                    api: 'Something went wrong. Please try again.',
                });
            }
        }
        finally {
            setFetch(false);
        }
    }), [
        mockedSDK,
        userProfile === null || userProfile === void 0 ? void 0 : userProfile.environmentId,
        enforcePolicies,
        onSubmit,
        fields,
        onError,
        formikInitialValues,
    ]);
    return {
        enforcePolicies,
        fetch,
        formikInitialValues,
        formikValidationSchema,
        onFormSubmit,
    };
};

exports.useUserDataForm = useUserDataForm;
