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");

  if (isTokenExpired(token)) {
    const refreshed = await refreshToken();
    return refreshed;
  }
  return true;
};

// Function to refresh the access token
const refreshToken = async () => {
  try {
    AuthRepository.refreshToken({
      token: localStorage.getItem("jwtToken"),
      refreshToken: refreshToken,
    })
      .then((response) => {
        localStorage.setItem("jwtToken", response.data.token);
        localStorage.setItem("refreshToken", response.data.refreshToken);
        return true;
      })
      .catch((error) => {
        console.error("Token refresh failed:", error);
      });

    // 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;
