import React, { useState, useEffect } from "react";
import { Navigate, Outlet } from "react-router-dom";
import { jwtDecode } from "jwt-decode";
import AuthRepository from "../repositories/AuthRepository";

const ProtectedRoute = () => {
  // const isAuthenticated = localStorage.getItem("jwtToken"); // Example authentication check
  // // const isAuthenticated = true;
  // isTokenValid();
  // return isAuthenticated ? <Outlet /> : <Navigate to="/auth/login" />
  
  const [isAuthenticated, setIsAuthenticated] = useState(null);

  useEffect(() => {
    const checkAuth = async () => {
      const valid = await validateToken();
      setIsAuthenticated(valid);
    };

    checkAuth();
  }, []);

  if (isAuthenticated === null) {
    return <div>Loading...</div>; // Show a loader while checking
  }

  return isAuthenticated ? <Outlet /> : <Navigate to="/auth/login" replace />;
};

// Function to check if the token is expired
const isTokenExpired = (token) => {
  if (!token) return true;
  try {
    const { exp } = jwtDecode(token);
    return exp * 1000 < Date.now(); // Check if expired
  } catch (error) {
    return true; // If decoding fails, treat as expired
  }
};

// Function to validate and refresh the token if expired
export const validateToken = async () => {
  const token = localStorage.getItem("jwtToken");
  const refreshTokenStored = localStorage.getItem("refreshToken");
  // If refresh token is absent, cannot proceed
  if (!refreshTokenStored) {
    console.warn("No refresh token available. Redirecting to login.");
    return false;
  }

  // If access token expired, try to refresh
  if (isTokenExpired(token)) {
    return await attemptTokenRefresh(refreshTokenStored);
  }
  return true;
};

// Attempt to refresh the access token
const attemptTokenRefresh = async (storedRefreshToken) => {
  try {
    const response = await AuthRepository.refreshToken({
      token: localStorage.getItem("jwtToken"),
      refreshToken: storedRefreshToken,
    });

    localStorage.setItem("jwtToken", response.data.token);
    localStorage.setItem("refreshToken", response.data.refreshToken);
    return true;
        // api
    //   .post("/api/auth/refresh-token", {
    //     token: localStorage.getItem("jwtToken"),
    //     refreshToken: refreshToken,
    //   })
    //   .then((data) => {
    //     localStorage.setItem("jwtToken", response.data.token);
    //     localStorage.setItem("refreshToken", response.data.refreshToken);
    //     return true;
    //   })
    //   .catch((error) => {
    //     console.error("Token refresh failed:", error);
    //   });

    // const refreshToken = localStorage.getItem("refreshToken");
    // const response = await axiosClient.post(`/api/auth/refresh-token`, {
    //   token: localStorage.getItem("jwtToken"),
    //   refreshToken: refreshToken,
    // });

    // if (response.status === 200) {
    //   localStorage.setItem("jwtToken", response.data.token);
    //   localStorage.setItem("refreshToken", response.data.refreshToken);
    //   return true;
    // }
  } catch (error) {
    console.error("Token refresh failed:", error);
    return false;
  }
};

export default ProtectedRoute;
