/* eslint-disable no-unused-vars */
import axios, { AxiosResponse } from 'axios';
import {
  createContext,
  type Dispatch,
  type PropsWithChildren,
  type SetStateAction,
  useEffect,
  useState
} from 'react';

import * as authHelper from '../_helpers';
import { type AuthModel, type UserModel } from '@/auth';
import { apiConfig } from '@/config/api.config';
import { doSaveLogActivity } from '@/actions/GlobalActions';

const API_URL = apiConfig.service_dashboard;

export const LOGIN_URL = `${API_URL}/login`;
export const GET_USER_URL = `${API_URL}/user/profile`;

interface AuthContextProps {
  loading: boolean;
  setLoading: Dispatch<SetStateAction<boolean>>;
  auth: AuthModel | undefined;
  saveAuth: (auth: AuthModel | undefined) => void;
  currentUser: UserModel | undefined;
  setCurrentUser: Dispatch<SetStateAction<UserModel | undefined>>;
  login: (email: string, password: string, token?: string) => Promise<void>;
  logout: () => void;
  verify: () => Promise<void>;
}

const AuthContext = createContext<AuthContextProps | null>(null);

const AuthProvider = ({ children }: PropsWithChildren) => {
  const [loading, setLoading] = useState(true);
  const [auth, setAuth] = useState<AuthModel | undefined>(authHelper.getAuth());
  const [currentUser, setCurrentUser] = useState<UserModel | undefined>();

  const saveAuth = (auth: AuthModel | undefined) => {
    setAuth(auth);
    if (auth) {
      authHelper.setAuth(auth);
    } else {
      authHelper.removeAuth();
    }
  };

  const login = async (username: string, password: string, token?: string) => {
    try {
      const { data: auth } = await axios
        .post(LOGIN_URL, { username, password })
        .then((response) => response.data);

      const enhancedAuth: AuthModel = {
        ...auth.token,
        id: auth.userid,
        user: auth.user,
      };     

      saveAuth(enhancedAuth);
      setCurrentUser(auth.user);

      const createActivity = {
        module: 'Login',
        description: `Login`,
        action: 'l'
      };
      doSaveLogActivity(createActivity);
    } catch (error: any) {
      console.error('Login error:', error);
      throw error;
    }
  };

  const getUser = async () => {
    let _axios = await axios
      .get(`${GET_USER_URL}/${authHelper.getAuth()?.user?.id}`)
      .then((response) => response.data.data);

    return { data: _axios };
  };

  const verify = async () => {
    if (auth) {
      try {
        const { data: user } = await getUser();

        // Perbarui auth yang sekarang dengan statusbalance
        saveAuth({
          ...auth,
        });

        const createCacheUser = {
          name: user.name,
          email: user.email,
          username: user.username,
        };

        localStorage.setItem('user', JSON.stringify(createCacheUser));
      } catch {
        saveAuth(undefined);
        setCurrentUser(undefined);
      }
    }
  };

  const logout = async () => {
    const createActivity = {
      module: 'Logout',
      description: `Logout`,
      action: 'O'
    };
    await doSaveLogActivity(createActivity);

    saveAuth(undefined);
    setCurrentUser(undefined);
  };

  return (
    <AuthContext.Provider
      value={{
        loading,
        setLoading,
        auth,
        saveAuth,
        currentUser,
        setCurrentUser,
        login,
        logout,
        verify
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export { AuthContext, AuthProvider };
