import { useSelector, useDispatch } from 'react-redux';
import { setUser, initialState } from '@/store/auth/userSlice';
import { apiSignIn, apiSignOut, apiSignUp } from '@/services/AuthService';
import { onSignInSuccess, onSignOutSuccess } from '@/store/auth/sessionSlice';
import appConfig from '@/configs/app.config';
// import { REDIRECT_URL_KEY } from '@/constants/app.constant';
import { useNavigate } from 'react-router-dom';
// import useQuery from './useQuery';
import { apiGetAccountSettingData } from '@/services/AccountServices';

function useAuth() {
  const dispatch = useDispatch();

  const navigate = useNavigate();

  // const query = useQuery();

  const { token, signedIn } = useSelector((state) => state.auth.session);

  const signIn = async (values) => {
    try {
      const resp = await apiSignIn(values);
      const result = resp.data.result;
      if (result) {
        const { token } = result;
        dispatch(onSignInSuccess(token));
        try {
          const respUser = await apiGetAccountSettingData();
          const userResult = respUser.data.result;
          if (userResult) {
            const userResp = {
              id: userResult.id,
              avatar: '',
              userName: userResult.email,
              authority: [userResult.role],
              email: userResult.email,
              fullName: userResult.fullName,
              mobileNo: userResult.mobileNo,
              createdDate: userResult.createdDate,
              updatedDate: userResult.updatedDate,
              commercialNameArabic: userResult.commercialNameArabic,
              commercialNameEnglish: userResult.commercialNameEnglish,
              countryCode: userResult.countryCode,
              stakeholderId: userResult.stakeholderId,
              gateName: userResult.gateName,
              laneName: userResult.laneName,
            };
            dispatch(setUser(userResp));
          }
        } catch (userError) {
          console.error('Error fetching user data:', userError);
        }

        // const redirectUrl = query.get(REDIRECT_URL_KEY);
        // navigate(redirectUrl || appConfig.authenticatedEntryPath);

        return {
          status: 'success',
          message: result,
        };
      }
    } catch (errors) {
      console.error('Error signing in:', errors);
      return {
        status: 'failed',
        message: errors?.response?.data?.errorCodes || errors.toString(),
      };
    }
  };

  const signUp = async (values, locale) => {
    try {
      const resp = await apiSignUp(values, locale);
      if (resp.data) {
        const { token } = resp.data;
        dispatch(onSignInSuccess(token));
        if (resp.data.user) {
          dispatch(
            setUser(
              resp.data.user || {
                avatar: '',
                userName: 'Anonymous',
                authority: ['USER'],
                email: '',
              },
            ),
          );
        }
        /*  navigate(
                  const redirectUrl = query.get(REDIRECT_URL_KEY)
                    redirectUrl ? redirectUrl : appConfig.authenticatedEntryPath
                )*/
        return {
          status: 'success',
          message: '',
        };
      }
    } catch (errors) {
      return {
        status: 'failed',
        message: errors?.response?.data?.errorCodes || errors.toString(),
      };
    }
  };

  const handleSignOut = () => {
    dispatch(onSignOutSuccess());
    dispatch(setUser(initialState));
    navigate(appConfig.unAuthenticatedEntryPath);
  };

  const signOut = async () => {
    await apiSignOut();
    handleSignOut();
  };

  return {
    authenticated: token && signedIn,
    signIn,
    signUp,
    signOut,
  };
}

export default useAuth;
