import { useEffect, useState } from 'react';
import { jwtDecode } from 'jwt-decode';
import { api } from '../services/api';

interface AuthHook {
  user: User | null;
  login: (username: string, password: string) => Promise<User>;
  logout: () => void;
}

type DecodedToken = {
  tenantId: string;
};

type Token = {
  user: {
    id: number;
    name: string;
  };
  roles: string[];
  exp: number;
  iat: number;
};

const useAuth = (): AuthHook => {
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      setUser(JSON.parse(storedUser));
    }
  }, []);

  const login = async (username: string, password: string): Promise<User> => {
    const response = await api('post', '/login', { username, password });
    const user = response;

    const decodedToken: DecodedToken = jwtDecode(user.data.token);
    user.data.tenantId = decodedToken.tenantId;

    localStorage.setItem('user', JSON.stringify(user.data));
    setUser(user.data.data);
    return user.data;
  };

  const logout = (): void => {
    localStorage.removeItem('user');
    localStorage.removeItem('connectionId');
    setUser(null);
  };

  return { user, login, logout };
};

export const getExpirationDateFromToken = (token: string) => {
  const decoded: Token = jwtDecode(token);

  if (decoded && decoded.exp) {
    const expirationTimestamp = decoded.exp;
    // Convert to miliseconds, Date constructs using miliseconds
    return new Date(expirationTimestamp * 1000);
  }
  return null;
};

export { useAuth };
