import { jwtDecode } from 'jwt-decode';

import { paths } from 'src/routes/paths';

import axios from 'src/lib/axios';

import { JWT_STORAGE_KEY } from './constant';

// import axios from 'axios';

/**
 * Set or clear session tokens in localStorage and Axios headers.
 *
 * @param access_token - JWT access token (nullable)
 * @param xToken - Optional additional token (nullable)
 * @returns A promise resolving to 'success'
 */

// ----------------------------------------------------------------------

// export function jwtDecode(token: string) {
//   try {
//     if (!token) return null;

//     const parts = token.split('.');
//     if (parts.length < 2) {
//       throw new Error('Invalid token!');
//     }

//     const base64Url = parts[1];
//     const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
//     const decoded = JSON.parse(atob(base64));

//     return decoded;
//   } catch (error) {
//     console.error('Error decoding token:', error);
//     throw error;
//   }
// }

// ----------------------------------------------------------------------

// export function isValidToken(accessToken: string) {
//   if (!accessToken) {
//     return false;
//   }

//   try {
//     const decoded = jwtDecode(accessToken);

//     if (!decoded || !('exp' in decoded)) {
//       return false;
//     }

//     const currentTime = Date.now() / 1000;

//     return decoded.exp > currentTime;
//   } catch (error) {
//     console.error('Error during token validation:', error);
//     return false;
//   }
// }

interface JwtPayload {
  exp: number;
  [key: string]: any;
}

export function isValidToken(accessToken: string): boolean {
  if (!accessToken) {
    console.log('Token is missing');
    return false;
  }

  try {
    const decoded = jwtDecode<JwtPayload>(accessToken); // <-- tentukan tipe

    if (!decoded || typeof decoded.exp !== 'number') {
      console.log('Token has no exp field');
      return false;
    }

    const currentTime = Date.now() / 1000;

    const valid = decoded.exp > currentTime;

    return valid;
  } catch (error) {
    console.error('Error during token validation:', error);
    return false;
  }
}

// ----------------------------------------------------------------------

export function tokenExpired(exp: number) {
  const currentTime = Date.now();
  const timeLeft = exp * 1000 - currentTime;

  setTimeout(() => {
    try {
      alert('Token expired!');
      sessionStorage.removeItem(JWT_STORAGE_KEY);
      window.location.href = paths.auth.jwt.signIn;
    } catch (error) {
      console.error('Error during token expiration:', error);
      throw error;
    }
  }, timeLeft);
}

export const setSession = async (
  access_token: string | null,
  xToken?: string | null
): Promise<'success'> => {
  if (access_token) {
    // Encode token before storing
    // const encodedToken = window.btoa(access_token);

    // Save tokens to localStorage
    localStorage.setItem('jwt_access_token', access_token);
    if (xToken) {
      localStorage.setItem('x-token', xToken);
    }

    // Set global Authorization header for Axios
    axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`;
    axios.defaults.headers.common['x-token'] = xToken || '';
  } else {
    // Clear tokens
    localStorage.clear();
    delete axios.defaults.headers.common['Authorization'];
    delete axios.defaults.headers.common['x-token'];
  }

  return 'success';
};
