import { useState } from "react";
import axios from "axios";

export const useLogin = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [user, setUser] = useState(() => {
    // Cargar el user desde localStorage si existe
    const savedUser = localStorage.getItem("user");
    return savedUser ? JSON.parse(savedUser) : null;
  });

  const login = async (username) => {
    setLoading(true);
    setError(null);

    try {
      const { data } = await axios.post(
        "https://acoplasticos.com.co:3000/api/v2/login-marketresearch",
        { username },
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      );

      // Guardar todo el objeto en localStorage
      localStorage.setItem("loginResponse", JSON.stringify(data));
      localStorage.setItem("user", JSON.stringify(data.user));

      setUser(data.user);
      return data;
    } catch (err) {
      console.error("Error en login:", err);
      setError(
        err.response?.data?.error || "Error al conectar con el servidor"
      );
      return null;
    } finally {
      setLoading(false);
    }
  };

  const logout = () => {
    localStorage.removeItem("loginResponse");
    localStorage.removeItem("user");
    setUser(null);
  };

  return { login, logout, loading, error, user };
};
