import { API_URL, decryptData, handleLogin, useQueryParam, WEB_URL } from '@pos/base';
import { LoginForm } from './components';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

const customAxios = axios.create();

export default function LoginPage() {
  const queryParam = useQueryParam();
  const navigate = useNavigate();

  async function handleSubmitLogin(payload: any) {
    const { status, data } = await customAxios({
      url: API_URL.LOGIN,
      method: 'POST',
      data: payload,
    });
    if (status === 201) {
      const user = data?.data;
      const role = user?.role;
      if (role != 'superadmin') {
        throw {
          response: {
            data: {
              error: 'Unauthorized',
              message: 'Gagal! username atau password tidak sesuai',
              statusCode: 401,
            },
          },
        };
      }

      await handleLogin(user);
      if (role === 'tenant') {
        navigate(WEB_URL.APP);
      } else {
        if (queryParam.get('u')) {
          const encPrevUrl = decryptData(decodeURIComponent(queryParam.get('u') as string));
          if (encPrevUrl && encPrevUrl !== '' && !encPrevUrl?.includes('undefined')) {
            const prevUrl = JSON.parse(encPrevUrl);
            navigate(prevUrl, { replace: true });
          } else navigate('/app', { replace: true });
        } else navigate('/app', { replace: true });
      }
    }
  }

  return <LoginForm onSubmit={handleSubmitLogin} />;
}
