"use client";

import { useEffect, useState, ReactNode } from "react";
import { useRouter, useSearchParams } from "next/navigation";

const TOKEN_EXPIRY = 15 * 60 * 1000;

export interface AuthState {
  accessToken: string | null;
  refreshToken: string | null;
  user: any | null;
  isAuthenticated: boolean;
  isLoading: boolean;
}

export function useAuthApi() {
  const [auth, setAuth] = useState<AuthState>({
    accessToken: null,
    refreshToken: null,
    user: null,
    isAuthenticated: false,
    isLoading: true,
  });

  useEffect(() => {
    const access = localStorage.getItem("access_token");
    const refresh = localStorage.getItem("refresh_token");
    if (access) {
      setAuth((prev) => ({
        ...prev,
        accessToken: access,
        refreshToken: refresh,
        isAuthenticated: true,
        isLoading: false,
      }));
    } else {
      setAuth((prev) => ({ ...prev, isLoading: false }));
    }
  }, []);

  const logout = () => {
    localStorage.removeItem("access_token");
    localStorage.removeItem("refresh_token");
    setAuth({
      accessToken: null,
      refreshToken: null,
      user: null,
      isAuthenticated: false,
      isLoading: false,
    });
  };

  const apiFetch = async (url: string, options: RequestInit = {}) => {
    const baseURL = process.env.NEXT_PUBLIC_API_URL;
    const fullUrl = url.startsWith("http") ? url : `${baseURL}${url}`;

    const headers = new Headers(options.headers);
    headers.set("Content-Type", "application/json");

    if (auth.accessToken) {
      headers.set("Authorization", `Bearer ${auth.accessToken}`);
    }

    let res = await fetch(fullUrl, { ...options, headers });
    return res;
  };

  return { auth, setAuth, apiFetch, logout };
}
