import React, { useState } from "react";
import AUTH_API from "../constants";
//import AdminSite from "../configs/admincfgs";

const Login = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const handleLogin = async () => {
    try {
      // Make a POST request to the external REST API for authentication
      const ditswbsapisite = AUTH_API;
      const response = await fetch(
        ditswbsapisite,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ username, password }),
        },
        { mode: "cors" }
      );

      if (response.ok) {
        const data = await response.json();
        // Store the authentication token in local storage or cookies
        localStorage.setItem("authToken", data.token);
        // Redirect to the authenticated page
        window.location.href = "/dashboard";
      } else {
        // Handle login error (e.g., show error message to the user)
        console.log("Login failed.");
      }
    } catch (error) {
      console.error("Error during login:", error);
    }
  };

  return (
    <div>
      <input
        label="Username"
        type="text"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
      />
      <input
        label="Password"
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button onClick={handleLogin}>Login</button>
    </div>
  );
};

export default Login;
