"use client";

import React, { createContext, useState, useContext, ReactNode } from "react";
import { useRouter } from "next/navigation";

interface AuthResponse {
  accessToken: string;
  user: {
    id: string;
    email: string;
  };
}

interface AuthContextType {
  user: AuthResponse["user"] | null;
  token: string | null;
  isLoading: boolean;
  error: string | null;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

const LOGIN_URL = `${process.env.NEXT_PUBLIC_API_BASE_URL}/login`;

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<AuthResponse["user"] | null>(null);
  const [token, setToken] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const router = useRouter();

  // // On initial load, check for a token in localStorage
  // useEffect(() => {
  //   try {
  //     const storedToken = window.localStorage.getItem("authToken");
  //     if (storedToken) {
  //       setToken(storedToken);
  //     }
  //   } catch (error) {
  //     console.error("Could not access localStorage:", error);
  //   }
  // }, []);

  const login = async (email: string, password: string) => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(LOGIN_URL, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });

      const data: AuthResponse = await response.json();

      if (!response.ok) {
        throw new Error((data as any).message || "Login failed.");
      }

      // setToken(data.accessToken);
      // setUser(data.user);

      // window.localStorage.setItem("authToken", data.accessToken);

      router.push("/dashboard"); // Redirect on successful login
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  const logout = () => {
    setUser(null);
    setToken(null);
    window.localStorage.removeItem("authToken");
    router.push("/login"); // Redirect to login page after logout
  };

  const value = { user, token, isLoading, error, login, logout };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

// Custom hook to use the AuthContext
export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
};
