import {  createSlice } from '@reduxjs/toolkit';

import {  signInWithPassword } from '../context/jwt';
import axios  from 'axios';
import { setUserData } from './userSlice';
import { ApiResponse } from '../types/api';
import { User } from '../types/user';


interface SignInParams {
  email: string;
  password: string;
}

export const submitLogin =
  ({ email, password }: SignInParams) =>
  async (dispatch: any) => {
    // setSession(token,xToken);
    try {
      // Panggil API login baru
      await signInWithPassword({ email, password });

        const token = localStorage.getItem('jwt_access_token');
        const xToken = localStorage.getItem('x-token'); 

        // Ambil data user dari response API
        const res = await axios.post<ApiResponse<{ user: User }>>(
        'https://nodesandbox.pajakexpress.id:1837/sandbox/userinfo',
        null,
        {
            headers: {
            Authorization: `Bearer ${token}`, 
            'x-token': xToken,                
            'Content-Type': 'application/x-www-form-urlencoded',
            },
        }
        );

      const userInfo = res.data?.data?.user;
      console.log(userInfo)

      if (!userInfo) throw new Error('User data not found');

      // Mapping user API ke Redux state
      const mappedUser = {
        role: [userInfo.access_level === 1 ? 'admin' : 'user'],
        data: {
          id: userInfo.id,
          customer_name: userInfo.customer_name || userInfo.company_name,
          email: userInfo.email,
          npwp_trial: userInfo.npwp_trial,
          company_name: userInfo.company_name,
          phone: userInfo.phone,
          quota: userInfo.quota,
          start_date: userInfo.start_date,
          end_date: userInfo.end_date,
          updated_at:userInfo.updated_at,
          x_token: userInfo.x_token,
          signer_npwp:userInfo.signer_npwp,
          signer:userInfo.signer,
          created_at:userInfo.created_at,
          address:userInfo.address
        },
        loginRedirectUrl: '/dashboard',
      };

      dispatch(setUserData(mappedUser));
      console.log("User state updated:", mappedUser);

      return dispatch(loginSuccess(mappedUser));
    } catch (error) {
      console.error(error);
    //   return dispatch(loginError(error));
      dispatch(loginError(error));
      throw error;
    }
  };

const initialState = {
  success: false,
  errors: [],
};

const loginSlice = createSlice({
  name: 'auth/login',
  initialState,
  reducers: {
    loginSuccess: (state, action) => {
      state.success = action.payload;
      state.errors = [];
    },
    loginError: (state, action) => {
      state.success = false;
      state.errors = [];
    },
  },
//   extraReducers: {},
});

export const { loginSuccess, loginError } = loginSlice.actions;

export default loginSlice.reducer;
