import { API_BASE } from "../config";

import { useState } from "react";

export default function Login({ onLogin }) {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  async function handleSubmit(e) {
    e.preventDefault();
    setError("");

    const device_id = "147ac10b-58cc-4372-a567-0e02b2c3d479";

    try {
      const res = await fetch(`${API_BASE}/auth/create_refresh`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "User-Agent": "react-app",
        },
        credentials: "include",
        body: JSON.stringify({ username, password, device_id }),
      });

      if (!res.ok) {
        setError("Invalid credentials or server error.");
        return;
      }

      //const data = await res.json(); // server returns short-lived token
      //localStorage.setItem("access_token", data.access_token);

      if (onLogin) onLogin(); // notify App to show MainApp

    } catch (err) {
      console.error(err);
      setError("Network error.");
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Username"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
      />
      <input
        type="password"
        placeholder="Password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button type="submit">Login</button>
      {error && <p style={{ color: "red" }}>{error}</p>}
    </form>
  );
}
