"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } }

var _chunkWWW27UB2js = require('./chunk-WWW27UB2.js');


var _chunkX5NIWGMVjs = require('./chunk-X5NIWGMV.js');


var _chunkYBG6IXTEjs = require('./chunk-YBG6IXTE.js');


var _chunkEYXYZEIPjs = require('./chunk-EYXYZEIP.js');



var _chunkWO63JU7Bjs = require('./chunk-WO63JU7B.js');



var _chunkAGGKOHRFjs = require('./chunk-AGGKOHRF.js');

// tmp-babel/profiles/native/ProfileSettingsComponent/index.js
var _react = require('react');
var _buttons = require('@baseapp-frontend/design-system/components/native/buttons');
var _icons = require('@baseapp-frontend/design-system/components/native/icons');
var _inputs = require('@baseapp-frontend/design-system/components/native/inputs');
var _views = require('@baseapp-frontend/design-system/components/native/views');
var _native = require('@baseapp-frontend/design-system/hooks/native');
var _native3 = require('@baseapp-frontend/design-system/providers/native');
var _utils = require('@baseapp-frontend/utils');
var _zod = require('@hookform/resolvers/zod');
var _expofilesystem = require('expo-file-system'); var FileSystem = _interopRequireWildcard(_expofilesystem);
var _reacthookform = require('react-hook-form');
var _reactnative = require('react-native');
var _reactnativegesturehandler = require('react-native-gesture-handler');
var _reactrelay = require('react-relay');
var _jsxruntime = require('react/jsx-runtime');
function _typeof(o) {
  "@babel/helpers - typeof";
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof(o);
}
function ownKeys(e, r) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r && (o = o.filter(function(r2) {
      return Object.getOwnPropertyDescriptor(e, r2).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread(e) {
  for (var r = 1; r < arguments.length; r++) {
    var t = null != arguments[r] ? arguments[r] : {};
    r % 2 ? ownKeys(Object(t), true).forEach(function(r2) {
      _defineProperty(e, r2, t[r2]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) {
      Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
    });
  }
  return e;
}
function _regenerator() {
  var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag";
  function i(r2, n2, o2, i2) {
    var c2 = n2 && n2.prototype instanceof Generator ? n2 : Generator, u2 = Object.create(c2.prototype);
    return _regeneratorDefine2(u2, "_invoke", function(r3, n3, o3) {
      var i3, c3, u3, f2 = 0, p = o3 || [], y = false, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d2(t2, r4) {
        return i3 = t2, c3 = 0, u3 = e, G.n = r4, a;
      } };
      function d(r4, n4) {
        for (c3 = r4, u3 = n4, t = 0; !y && f2 && !o4 && t < p.length; t++) {
          var o4, i4 = p[t], d2 = G.p, l = i4[2];
          r4 > 3 ? (o4 = l === n4) && (u3 = i4[(c3 = i4[4]) ? 5 : (c3 = 3, 3)], i4[4] = i4[5] = e) : i4[0] <= d2 && ((o4 = r4 < 2 && d2 < i4[1]) ? (c3 = 0, G.v = n4, G.n = i4[1]) : d2 < l && (o4 = r4 < 3 || i4[0] > n4 || n4 > l) && (i4[4] = r4, i4[5] = n4, G.n = l, c3 = 0));
        }
        if (o4 || r4 > 1) return a;
        throw y = true, n4;
      }
      return function(o4, p2, l) {
        if (f2 > 1) throw TypeError("Generator is already running");
        for (y && 1 === p2 && d(p2, l), c3 = p2, u3 = l; (t = c3 < 2 ? e : u3) || !y; ) {
          i3 || (c3 ? c3 < 3 ? (c3 > 1 && (G.n = -1), d(c3, u3)) : G.n = u3 : G.v = u3);
          try {
            if (f2 = 2, i3) {
              if (c3 || (o4 = "next"), t = i3[o4]) {
                if (!(t = t.call(i3, u3))) throw TypeError("iterator result is not an object");
                if (!t.done) return t;
                u3 = t.value, c3 < 2 && (c3 = 0);
              } else 1 === c3 && (t = i3["return"]) && t.call(i3), c3 < 2 && (u3 = TypeError("The iterator does not provide a '" + o4 + "' method"), c3 = 1);
              i3 = e;
            } else if ((t = (y = G.n < 0) ? u3 : r3.call(n3, G)) !== a) break;
          } catch (t2) {
            i3 = e, c3 = 1, u3 = t2;
          } finally {
            f2 = 1;
          }
        }
        return { value: t, done: y };
      };
    }(r2, o2, i2), true), u2;
  }
  var a = {};
  function Generator() {
  }
  function GeneratorFunction() {
  }
  function GeneratorFunctionPrototype() {
  }
  t = Object.getPrototypeOf;
  var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function() {
    return this;
  }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
  function f(e2) {
    return Object.setPrototypeOf ? Object.setPrototypeOf(e2, GeneratorFunctionPrototype) : (e2.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e2, o, "GeneratorFunction")), e2.prototype = Object.create(u), e2;
  }
  return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function() {
    return this;
  }), _regeneratorDefine2(u, "toString", function() {
    return "[object Generator]";
  }), (_regenerator = function _regenerator2() {
    return { w: i, m: f };
  })();
}
function _regeneratorDefine2(e, r, n, t) {
  var i = Object.defineProperty;
  try {
    i({}, "", {});
  } catch (e2) {
    i = 0;
  }
  _regeneratorDefine2 = function _regeneratorDefine(e2, r2, n2, t2) {
    if (r2) i ? i(e2, r2, { value: n2, enumerable: !t2, configurable: !t2, writable: !t2 }) : e2[r2] = n2;
    else {
      var o = function o2(r3, n3) {
        _regeneratorDefine2(e2, r3, function(e3) {
          return this._invoke(r3, n3, e3);
        });
      };
      o("next", 0), o("throw", 1), o("return", 2);
    }
  }, _regeneratorDefine2(e, r, n, t);
}
function _defineProperty(e, r, t) {
  return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e;
}
function _toPropertyKey(t) {
  var i = _toPrimitive(t, "string");
  return "symbol" == _typeof(i) ? i : i + "";
}
function _toPrimitive(t, r) {
  if ("object" != _typeof(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r || "default");
    if ("object" != _typeof(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r ? String : Number)(t);
}
function asyncGeneratorStep(n, t, e, r, o, a, c) {
  try {
    var i = n[a](c), u = i.value;
  } catch (n2) {
    return void e(n2);
  }
  i.done ? t(u) : Promise.resolve(u).then(r, o);
}
function _asyncToGenerator(n) {
  return function() {
    var t = this, e = arguments;
    return new Promise(function(r, o) {
      var a = n.apply(t, e);
      function _next(n2) {
        asyncGeneratorStep(a, r, o, _next, _throw, "next", n2);
      }
      function _throw(n2) {
        asyncGeneratorStep(a, r, o, _next, _throw, "throw", n2);
      }
      _next(void 0);
    });
  };
}
function _slicedToArray(r, e) {
  return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(r, a) {
  if (r) {
    if ("string" == typeof r) return _arrayLikeToArray(r, a);
    var t = {}.toString.call(r).slice(8, -1);
    return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
  }
}
function _arrayLikeToArray(r, a) {
  (null == a || a > r.length) && (a = r.length);
  for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  return n;
}
function _iterableToArrayLimit(r, l) {
  var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  if (null != t) {
    var e, n, i, u, a = [], f = true, o = false;
    try {
      if (i = (t = t.call(r)).next, 0 === l) {
        if (Object(t) !== t) return;
        f = false;
      } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = true) ;
    } catch (r2) {
      o = true, n = r2;
    } finally {
      try {
        if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a;
  }
}
function _arrayWithHoles(r) {
  if (Array.isArray(r)) return r;
}
var ProfileSettingsComponent = function ProfileSettingsComponent2(_ref) {
  var profileRef = _ref.profile;
  var theme = _native3.useTheme.call(void 0, );
  var styles = _chunkX5NIWGMVjs.createStyles.call(void 0, theme);
  var profile = _reactrelay.useFragment.call(void 0, _chunkEYXYZEIPjs.ProfileComponentFragment, profileRef);
  var bottomDrawerRef = _react.useRef.call(void 0, void 0);
  var _useProfileMutation = _chunkYBG6IXTEjs.useProfileMutation.call(void 0, ), _useProfileMutation2 = _slicedToArray(_useProfileMutation, 2), commitMutation = _useProfileMutation2[0], isMutationInFlight = _useProfileMutation2[1];
  var _useState = _react.useState.call(void 0, "image"), _useState2 = _slicedToArray(_useState, 2), fieldType = _useState2[0], setFieldType = _useState2[1];
  var _useNotification = _utils.useNotification.call(void 0, ), sendToast = _useNotification.sendToast;
  var formReturn = _reacthookform.useForm.call(void 0, {
    defaultValues: _chunkWO63JU7Bjs.getProfileDefaultValues.call(void 0, {
      profile
    }),
    // @ts-ignore TODO: check typing issue with zodResolver
    resolver: _zod.zodResolver.call(void 0, _chunkAGGKOHRFjs.DEFAULT_PROFILE_FORM_VALIDATION),
    mode: "onBlur"
  });
  var uploadFile = /* @__PURE__ */ function() {
    var _ref2 = _asyncToGenerator(/* @__PURE__ */ _regenerator().m(function _callee(fileUri, fieldName) {
      var _bottomDrawerRef$curr, authToken, fileInfo, response, _t;
      return _regenerator().w(function(_context) {
        while (1) switch (_context.n) {
          case 0:
            _context.p = 0;
            authToken = _utils.getToken.call(void 0, _utils.ACCESS_KEY_NAME);
            _context.n = 1;
            return FileSystem.getInfoAsync(fileUri);
          case 1:
            fileInfo = _context.v;
            if (!fileInfo.exists) {
              sendToast("File does not exist", {
                type: "error"
              });
            }
            (_bottomDrawerRef$curr = bottomDrawerRef.current) === null || _bottomDrawerRef$curr === void 0 || _bottomDrawerRef$curr.close();
            _context.n = 2;
            return FileSystem.uploadAsync(process.env.EXPO_PUBLIC_RELAY_ENDPOINT, fileUri, {
              httpMethod: "POST",
              uploadType: FileSystem.FileSystemUploadType.MULTIPART,
              fieldName,
              parameters: {
                // TODO: see if we can reuse the query from the mutation
                query: "mutation ProfileUpdateMutation($input: ProfileUpdateInput!) {\n              profileUpdate(input: $input) {\n                profile {\n                  id\n                }\n                errors {\n                  field\n                  messages\n                }\n              }\n            }",
                variables: JSON.stringify({
                  input: _defineProperty({
                    id: profile.id
                  }, fieldName, fileUri)
                })
              },
              headers: {
                "Content-Type": "multipart/form-data",
                Authorization: "Bearer ".concat(authToken)
              }
            });
          case 2:
            response = _context.v;
            if (response.status !== 200) {
              formReturn.setError(fieldName, {
                message: "Failed to upload file"
              });
            }
            _context.n = 4;
            break;
          case 3:
            _context.p = 3;
            _t = _context.v;
            formReturn.setError(fieldName, {
              message: "Failed to upload file"
            });
          case 4:
            return _context.a(2);
        }
      }, _callee, null, [[0, 3]]);
    }));
    return function uploadFile2(_x, _x2) {
      return _ref2.apply(this, arguments);
    };
  }();
  var control = formReturn.control, handleSubmit = formReturn.handleSubmit, reset = formReturn.reset, watch = formReturn.watch, setValue = formReturn.setValue, clearErrors = formReturn.clearErrors, _formReturn$formState = formReturn.formState, isDirty = _formReturn$formState.isDirty, dirtyFields = _formReturn$formState.dirtyFields;
  var watchImage = watch(_chunkAGGKOHRFjs.PROFILE_FORM_VALUE.image);
  var watchBannerImage = watch(_chunkAGGKOHRFjs.PROFILE_FORM_VALUE.bannerImage);
  var imageUrl = _chunkWO63JU7Bjs.getImageUrl.call(void 0, watchImage);
  var bannerImageUrl = _chunkWO63JU7Bjs.getImageUrl.call(void 0, watchBannerImage);
  var hasChanged = isDirty || Object.keys(dirtyFields).length > 0;
  var onSubmit = /* @__PURE__ */ function() {
    var _ref3 = _asyncToGenerator(/* @__PURE__ */ _regenerator().m(function _callee2(data) {
      var dirtyValues, id;
      return _regenerator().w(function(_context2) {
        while (1) switch (_context2.n) {
          case 0:
            dirtyValues = _utils.filterDirtyValues.call(void 0, {
              values: data,
              dirtyFields
            });
            id = data.id;
            if (!dirtyValues.image) {
              _context2.n = 2;
              break;
            }
            _context2.n = 1;
            return uploadFile(dirtyValues.image, "image");
          case 1:
            delete dirtyValues.image;
          case 2:
            if (!dirtyValues.bannerImage) {
              _context2.n = 4;
              break;
            }
            _context2.n = 3;
            return uploadFile(dirtyValues.bannerImage, "bannerImage");
          case 3:
            delete dirtyValues.bannerImage;
          case 4:
            commitMutation({
              variables: {
                input: _objectSpread({
                  id
                }, dirtyValues)
              },
              onCompleted: function onCompleted(response) {
                var _response$profileUpda;
                var errors = response === null || response === void 0 || (_response$profileUpda = response.profileUpdate) === null || _response$profileUpda === void 0 ? void 0 : _response$profileUpda.errors;
                if (errors) {
                  sendToast("Something went wrong", {
                    type: "error"
                  });
                  _utils.setFormRelayErrors.call(void 0, formReturn, errors);
                } else {
                  sendToast("Profile updated", {
                    type: "success"
                  });
                }
              }
            });
            reset({}, {
              keepValues: true
            });
          case 5:
            return _context2.a(2);
        }
      }, _callee2);
    }));
    return function onSubmit2(_x3) {
      return _ref3.apply(this, arguments);
    };
  }();
  function handleSave(data) {
    onSubmit(data);
  }
  var _useViewPhotoLibrary = _native.useViewPhotoLibrary.call(void 0, {
    allowsEditing: _reactnative.Platform.OS === "android",
    isBase64: false,
    onResult: function onResult(image) {
      var imageUri = image === null || image === void 0 ? void 0 : image.uri;
      setValue(fieldType, imageUri, {
        shouldValidate: true,
        shouldDirty: true
      });
    },
    onFinally: function onFinally() {
      var _bottomDrawerRef$curr2;
      (_bottomDrawerRef$curr2 = bottomDrawerRef.current) === null || _bottomDrawerRef$curr2 === void 0 || _bottomDrawerRef$curr2.close();
    },
    type: fieldType
  }), handleViewPhotoLibrary = _useViewPhotoLibrary.handleViewPhotoLibrary, handleTakePhoto = _useViewPhotoLibrary.handleTakePhoto;
  var handleRemoveImage = function handleRemoveImage2(type) {
    clearErrors(type === "image" ? "image" : "bannerImage");
    setValue(type === "image" ? "image" : "bannerImage", void 0, {
      shouldValidate: false,
      shouldDirty: true,
      shouldTouch: true
    });
  };
  var handlePresentModalPress = _react.useCallback.call(void 0, function() {
    var _bottomDrawerRef$curr3;
    (_bottomDrawerRef$curr3 = bottomDrawerRef.current) === null || _bottomDrawerRef$curr3 === void 0 || _bottomDrawerRef$curr3.present();
  }, []);
  var handleSheetChanges = _react.useCallback.call(void 0, function(index) {
    console.log("index", index);
  }, []);
  var handleEditBanner = function handleEditBanner2() {
    setFieldType("bannerImage");
    handlePresentModalPress();
  };
  var handleEditProfile = function handleEditProfile2() {
    setFieldType("image");
    handlePresentModalPress();
  };
  var hasErrorImage = imageUrl.includes("error");
  var hasErrorBanner = bannerImageUrl.includes("error");
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _reactnativegesturehandler.ScrollView, {
    style: styles.scrollViewContainer,
    children: /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _views.View, {
      style: styles.container,
      children: [/* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _views.View, {
        style: styles.headerContainer,
        children: [/* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _views.View, {
          style: styles.bannerContainer,
          children: [/* @__PURE__ */ _jsxruntime.jsx.call(void 0, _reactnative.Image, {
            source: {
              uri: bannerImageUrl
            },
            style: [styles.bannerImage, hasErrorBanner ? styles.errorBorder : {}]
          }), /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _reactnative.Pressable, {
            style: styles.editIconContainer,
            onPress: handleEditBanner,
            children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _icons.CameraIcon, {
              width: 20,
              height: 20,
              color: theme.colors.surface["default"]
            })
          })]
        }), /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _views.View, {
          style: styles.profileContainer,
          children: [imageUrl ? /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _reactnative.Image, {
            source: {
              uri: imageUrl
            },
            style: [styles.profileImage, hasErrorImage ? styles.errorBorder : {}]
          }) : /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _icons.ImageIcon, {
            width: 33,
            height: 33,
            color: theme.colors.object.disabled,
            style: hasErrorImage ? styles.errorBorder : {}
          }), /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _reactnative.Pressable, {
            style: [styles.editIconContainer, {
              bottom: 0,
              right: 0
            }],
            onPress: handleEditProfile,
            children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _icons.CameraIcon, {
              width: 20,
              height: 20,
              color: theme.colors.surface["default"]
            })
          })]
        })]
      }), /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _views.View, {
        style: styles.formContainer,
        children: [/* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _views.View, {
          style: styles.formGroup,
          children: [/* @__PURE__ */ _jsxruntime.jsx.call(void 0, _inputs.TextInput, {
            label: "Name",
            name: _chunkAGGKOHRFjs.PROFILE_FORM_VALUE.name,
            control,
            mode: "outlined",
            outlineStyle: styles.input
          }), /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _inputs.TextInput, {
            label: "Username",
            name: _chunkAGGKOHRFjs.PROFILE_FORM_VALUE.urlPath,
            control,
            mode: "outlined",
            outlineStyle: styles.input
          }), /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _inputs.TextInput, {
            label: "Phone Number",
            name: _chunkAGGKOHRFjs.PROFILE_FORM_VALUE.phoneNumber,
            control,
            mode: "outlined",
            outlineStyle: styles.input
          })]
        }), /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _views.View, {
          style: styles.formGroup,
          children: [/* @__PURE__ */ _jsxruntime.jsx.call(void 0, _inputs.TextInput, {
            label: "Bio",
            name: _chunkAGGKOHRFjs.PROFILE_FORM_VALUE.biography,
            control,
            mode: "outlined",
            multiline: true,
            numberOfLines: 4,
            style: styles.bioInput,
            outlineStyle: styles.input
          }), /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _views.View, {
            style: styles.saveButtonContainer,
            children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _buttons.Button, {
              onPress: handleSubmit(handleSave),
              size: "medium",
              loading: isMutationInFlight,
              contentStyle: hasChanged ? styles.saveButton : styles.saveButtonDisabled,
              labelStyle: styles.saveButtonLabel,
              disabled: isMutationInFlight || !hasChanged,
              children: isMutationInFlight ? "" : "Save Changes"
            })
          })]
        })]
      }), /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkWWW27UB2js.BottomDrawer_default, {
        bottomDrawerRef,
        handleSheetChanges,
        type: fieldType,
        handleViewPhotoLibrary,
        handleTakePhoto,
        handleRemoveImage
      })]
    })
  });
};
var ProfileSettingsComponent_default = ProfileSettingsComponent;



exports.ProfileSettingsComponent_default = ProfileSettingsComponent_default;
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
//# sourceMappingURL=chunk-NY2TMRJC.js.map