import React, { createContext, useContext, useState } from "react";

interface User {
  user_id: number;
  user_name: string;
  user_email: string;
  user_role: string;
}

interface AuthContextType {
  user: User | null;
  isAuthenticated: boolean;
  logout: () => Promise<void>;
}

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

const getInitialAuthState = () => {
  const root = document.getElementById("root");
  const authStatus = root?.getAttribute("data-authenticated") === "true";
  const userData = root?.getAttribute("data-user");

  let user = null;
  if (userData) {
    try {
      user = JSON.parse(userData);
    } catch (e) {
      console.error("Failed to parse user data", e);
    }
  }

  return { user, isAuthenticated: authStatus };
};

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const initialState = getInitialAuthState();
  const [user] = useState<User | null>(initialState.user);
  const [isAuthenticated] = useState(initialState.isAuthenticated);

  const logout = async () => {
    try {
      const response = await fetch("/logout", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
        },
      });

      if (response.ok) {
        window.location.href = "/signin";
      }
    } catch (error) {
      console.error("Logout failed", error);
    }
  };

  return (
    <AuthContext.Provider value={{ user, isAuthenticated, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
};
