import { createContext, useState } from "react";

export const UserContext = createContext();

const UserProvider = ({ children }) => {
  const [token, setToken] = useState(localStorage.getItem("loginToken"));
  const [email, setEmail] = useState(null);

  const storeData = (email, token) => {
    setEmail(email);
    setToken(token);
    localStorage.setItem("loginToken", token);
  };
  const login = async (user, password) => {
    const res = await fetch("http://localhost:5000/api/auth/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email: user, password }),
    });
    if (!res.ok) {
      throw new Error("Error al iniciar sesión");
    }
    const data = await res.json();
    storeData(email, data.token);
  };
  const register = async (user, password) => {
    const res = await fetch("http://localhost:5000/api/auth/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email: user, password }),
    });
    if (!res.ok) {
      throw new Error("Error al registrarse");
    }
    const data = await res.json();
    storeData(email, data.token);
  };
  const logout = () => {
    localStorage.removeItem("loginToken");
    setToken(null);
    setEmail(null);
  };
  const getProfile = async () => {
    const res = await fetch("http://localhost:5000/api/auth/me", {
      headers: { Authorization: `Bearer ${token}` },
    });
    if (!res.ok) {
      throw new Error("Error al obtener perfil", res.status);
    }
    const data = await res.json();
    return data;
  };
  return (
    <UserContext.Provider
      value={{
        token,
        setToken,
        email,
        setEmail,
        login,
        register,
        getProfile,
        logout,
      }}
    >
      {children}
    </UserContext.Provider>
  );
};

export default UserProvider;
