import { useNavigation } from '@react-navigation/native';
import cn from 'classnames';
import React, { useState } from 'react';
import { WebView } from 'react-native-webview';

import Loader from '../../components/Loader/Loader';
import { NavProps } from '../../components/Routes/Routes';
import { APP_ID, SERVER_URL } from '../../constants/api';
import { useUserInfo } from '../../hooks/useStorage';
import { LoginItems } from '../../services/api/APIS/UserManagement/types';
import { parseBodyText } from './helpers/bodyParser';

const Login = () => {
  const navigation = useNavigation<NavProps>();
  const [webLoading, setWebLoading] = useState(false);
  const [userInfo, setUserInfo] = useUserInfo();

  const loginWebViewSrc: string = `${SERVER_URL}Login/?appid=${APP_ID}`;
  const jsCode = `
    window.ReactNativeWebView.postMessage(window.location.href + document.body.innerText);
    if (window.location.href.includes('Login/LoggedIn.aspx')) {
      document.body.innerText = '';
    }
  `;

  const storeData = (loginItems: LoginItems) => {
    setUserInfo({
      ...userInfo,
      token: loginItems.skautISToken,
      userName: loginItems.userName,
      userId: loginItems.userID,
      roleId: loginItems.roleID,
      unitId: loginItems.unitID,
    });
  };

  return (
    <>
      <WebView
        className={cn({ hidden: webLoading })}
        source={{ uri: loginWebViewSrc }}
        onLoadStart={() => setWebLoading(true)}
        onLoadEnd={() => setWebLoading(false)}
        injectedJavaScript={jsCode}
        onMessage={event => {
          const msg = event.nativeEvent.data;
          if (msg.startsWith(`${SERVER_URL}Login/LoggedIn.aspx`)) {
            const loginItems = parseBodyText(msg);
            storeData(loginItems);
            navigation.reset({
              index: 0,
              routes: [{ name: 'Tabs' }],
            });
          }
        }}
      />
      {webLoading && <Loader classNames="absolute left-1/2 -translate-x-[18px] transform" />}
    </>
  );
};

export default Login;
