import PropTypes from 'prop-types';
import { createContext, useEffect } from 'react';

// third-party
// import { Chance } from 'chance';

// reducer - state management
import { LOGIN, LOGOUT } from 'store/reducers/actions';

// project import
import Loader from 'components/Loader';
// import axios from 'utils/axios';
import axios from 'axios';
import { useDispatch, useSelector } from 'store';
import OpenToast from 'components/third-party/OpenToast';

// const chance = new Chance();

// Store user in localStorage for persistence
const setSession = (user) => {
  if (user) {
    localStorage.setItem('user', JSON.stringify(user)); // on successfull login
  } else {
    localStorage.removeItem('user'); // on logout
  }
};

// ==============================|| JWT CONTEXT & PROVIDER ||============================== //

const JWTContext = createContext(null);

export const JWTProvider = ({ children }) => {
  const dispatch = useDispatch();
  const state = useSelector((state) => state.auth);

  // On app load, check if user is stored in localStorage
  useEffect(() => {
    const init = async () => {
      try {
        // Check if user exists in localStorage (from previous login)
        const storedUser = localStorage.getItem('user');
        if (storedUser) {
          const user = JSON.parse(storedUser);
          // User already logged in, restore session
          dispatch({
            type: LOGIN,
            payload: {
              isLoggedIn: true,
              user
            }
          });
        } else {
          // No user stored, not logged in
          dispatch({
            type: LOGOUT
          });
        }
      } catch (err) {
        console.error(err);
        dispatch({
          type: LOGOUT
        });
      }
    };

    init();
  }, [dispatch]);

  const login = async (email, password) => {
    try {
      // Call your login API
      const response = await axios.post(`${process.env.REACT_APP_URL}/users/tenant/weblogin`, {
        authname: email,
        password,
        configid: 15,
        roleid: 3,
        tenanttoken:
          'fOhT0VSQmPqIGEfKAV-Ln9:APA91bEKjygQP9XvM66WWsETyJ3kMshI4JS_ndOv8RSWpH1hROntiddG81OJT1zLuREKjJ-6Ug9jfsfVux7S2JzOdCUGS8bd1DdovlB49MEFTZOADNIjw6I'
      });

      if (response.data.status) {
        // Extract user from response.details (your API structure)
        const user = response.data.details;

        // Store user in localStorage
        setSession(user);

        // Update Redux state
        dispatch({
          type: LOGIN,
          payload: {
            isLoggedIn: true,
            user
          }
        });
      } else {
        OpenToast(response.data.message, 'error', 2000);
      }
    } catch (error) {
      // Logout on error
      dispatch({ type: LOGOUT });
      console.error('Login error:', error);
      throw error.response?.data?.message || error.message || 'Login failed';
    }
  };

  const register = async (email, password, firstName, lastName) => {
    try {
      const response = await axios.post('/api/account/register', {
        email,
        password,
        firstName,
        lastName
      });

      const { user } = response.data;
      setSession(user);

      dispatch({
        type: LOGIN,
        payload: {
          isLoggedIn: true,
          user
        }
      });
    } catch (error) {
      dispatch({ type: LOGOUT });
      throw error.response?.data?.message || 'Registration failed';
    }
  };

  const logout = () => {
    setSession(null);
    dispatch({ type: LOGOUT });
  };

  const resetPassword = async () => {};

  const updateProfile = () => {};

  if (state.isInitialized !== undefined && !state.isInitialized) {
    return <Loader />;
  }

  return (
    <JWTContext.Provider
      value={{
        ...state,
        login,
        logout,
        register,
        resetPassword,
        updateProfile
      }}
    >
      {children}
    </JWTContext.Provider>
  );
};

JWTProvider.propTypes = {
  children: PropTypes.node
};

export default JWTContext;
