"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _native = _interopRequireDefault(require("styled-components/native"));
var _StyledComponents = require("../styled/StyledComponents");
var _Button = _interopRequireDefault(require("../styled/Button"));
var _icons = require("../../assets/icons");
var _auth = require("../../networking/api-requests/auth.api");
var _reactRedux = require("react-redux");
var _useLocalStorage = require("../../hooks/useLocalStorage");
var _chatSettingsSlice = require("../../roomStore/chatSettingsSlice");
var _LOCAL_STORAGE = require("../../helpers/constants/LOCAL_STORAGE");
var _reactNative = require("react-native");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
const LoginForm = ({
  config
}) => {
  const dispatch = (0, _reactRedux.useDispatch)();
  const {
    set
  } = (0, _useLocalStorage.useLocalStorage)(_LOCAL_STORAGE.localStorageConstants.ETHORA_USER);
  const [email, setEmail] = (0, _react.useState)('');
  const [password, setPassword] = (0, _react.useState)('');
  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const [errors, setErrors] = (0, _react.useState)({
    email: '',
    password: ''
  });
  const validateForm = () => {
    let emailError = '';
    let passwordError = '';
    if (!/\S+@\S+\.\S+/.test(email)) {
      emailError = 'Invalid email format';
    }
    if (password.length < 6) {
      passwordError = 'Password must be at least 6 characters long';
    }
    return {
      emailError,
      passwordError
    };
  };
  const handleRegularLogin = (0, _react.useCallback)(async () => {
    setIsLoading(true);
    try {
      const authData = await (0, _auth.loginEmail)(email, password);
      if (authData?.status === 401) {
        setErrors(prev => ({
          ...prev,
          password: 'You entered wrong data. Try again'
        }));
        setIsLoading(false);
        return null;
      }
      const user = {
        ...authData.data.user,
        token: authData.data.token,
        refreshToken: authData.data.refreshToken
      };
      dispatch((0, _chatSettingsSlice.setUser)(user));
      await set((0, _chatSettingsSlice.unpackAndTransform)(user));
    } catch (error) {
      console.error('Login failed:', error);
      setIsLoading(false);
      return null;
    }
    setIsLoading(false);
  }, [email, password, dispatch]);

  // const handleGoogleLogin = async () => {
  //   setIsLoading(true);

  //   const loginType = "google";

  //   try {
  //     const res = await signInWithGoogle();

  //     const emailExist = await checkEmailExist(
  //       res.user?.providerData[0].email || ""
  //     );

  //     if (!emailExist.data.success) {
  //       try {
  //         await registerSocial(
  //           res.idToken || "",
  //           res.credential?.accessToken || "",
  //           "",
  //           loginType
  //         );
  //         const loginRes = await loginSocial(
  //           res.idToken || "",
  //           res.credential?.accessToken || "",
  //           loginType
  //         );
  //         console.log("google log after register res", loginRes);

  //         const user = {
  //           ...loginRes.data.user,
  //           token: loginRes.data.token,
  //           refreshToken: loginRes.data.refreshToken,
  //         };
  //         dispatch(setUser(user));
  //         useLocalStorage(localStorageConstants.ETHORA_USER).set(user);
  //       } catch (error) {
  //         console.log("error registering user viag google");
  //       }
  //     }
  //     if (res.idToken && res.credential && res.credential.accessToken) {
  //       const loginRes = await loginSocial(
  //         res.idToken,
  //         res.credential.accessToken,
  //         loginType
  //       );
  //       console.log("google log res", loginRes);
  //       const user = {
  //         ...loginRes.data.user,
  //         token: loginRes.data.token,
  //         refreshToken: loginRes.data.refreshToken,
  //       };
  //       dispatch(setUser(user));
  //       useLocalStorage(localStorageConstants.ETHORA_USER).set(user);
  //     }
  //   } catch (error) {
  //     console.log(error);
  //   }
  //   setIsLoading(false);
  // };

  const handleSubmit = () => {
    const {
      emailError,
      passwordError
    } = validateForm();
    setErrors({
      email: emailError,
      password: passwordError
    });
    if (!emailError && !passwordError) {
      handleRegularLogin();
    }
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(FormContainer, {
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(Form, {
      children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
        style: {
          height: 40,
          width: '100%',
          display: 'flex',
          gap: 4,
          flexDirection: 'column'
        },
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_StyledComponents.MessageInput, {
          value: email,
          placeholder: "Email",
          onChangeText: text => setEmail(text),
          style: {
            borderWidth: 1,
            borderColor: config ? config.colors?.primary : '#3498db',
            borderRadius: 4
          }
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
          children: errors.email && /*#__PURE__*/(0, _jsxRuntime.jsx)(ErrorMessage, {
            children: errors.email
          })
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
        style: {
          height: 40,
          width: '100%',
          display: 'flex',
          gap: 4,
          flexDirection: 'column'
        },
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_StyledComponents.MessageInput, {
          value: password,
          placeholder: "Password",
          onChangeText: text => setPassword(text),
          style: {
            borderWidth: 1,
            borderColor: config ? config.colors?.primary : '#3498db',
            borderRadius: 4
          }
        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.Text, {
          children: [' ', errors.password && /*#__PURE__*/(0, _jsxRuntime.jsx)(ErrorMessage, {
            children: errors.password
          })]
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default, {
        onPress: handleSubmit,
        text: "Login to Ethora Chat",
        style: {
          width: '100%',
          height: 40,
          backgroundColor: config?.colors?.primary || '#0052CD'
        },
        color: "white",
        disabled: isLoading,
        loading: isLoading
      }), config?.googleLogin?.enabled && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(Delimiter, {
          children: "or"
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.default
        // onPress={handleGoogleLogin}
        , {
          text: "Login with Google",
          EndIcon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.GoogleIcon, {
            style: {
              height: 24
            }
          }),
          disabled: isLoading
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
          children: "Don't have an account? "
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
          style: {
            textDecorationLine: 'underline',
            color: '#0052CD',
            fontSize: 14,
            display: 'flex',
            fontWeight: '400'
          },
          children: "Sign Up to Ethora"
        })]
      })]
    })
  });
};

// Styled Components
const FormContainer = _native.default.View`
  flex: 1;
  justify-content: center;
  align-items: center;
  width: 100%;
  background-color: #f5f5f5;
`;
const Form = _native.default.View`
  flex-direction: column;
  align-items: center;
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  width: 300px;
  gap: 16px;
`;
const ErrorMessage = _native.default.Text`
  color: red;
  font-size: 12px;
  margin-bottom: 10px;
`;
const Delimiter = _native.default.Text`
  text-align: center;
  position: relative;
  width: 100%;
  font-size: 14px;
  color: #999;

  &::before,
  &::after {
    content: "";
    position: absolute;
    top: 50%;
    width: 45%;
    height: 1px;
    background: #ccc;
  }

  &::before {
    left: 0;
  }

  &::after {
    right: 0;
  }
`;
var _default = exports.default = LoginForm;
//# sourceMappingURL=Login.js.map