import {useState} from "react";
import {useSessionStore} from "../../lib/store/sessionStore";
import {useQueryClient} from "@tanstack/react-query";

const LoginForm = () => {
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const [error, setError] = useState("");
    const {setSession} = useSessionStore();
    const queryClient = useQueryClient();

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();
        // console.log("Form data", {username, password});
        try {
            const response = await fetch("/api/auth/login", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({username, password}),
            });

            // if (!response.ok) {
            //     throw new Error("Invalid credentials");
            // }

            const data = await response.json();
            console.log("Response", data.data);
            // Store token in localStorage
            localStorage.setItem("auth_token", data.data.token);

            // Optionally store user info
            // localStorage.setItem("user", JSON.stringify(user));

            setSession(data.data.user, data.data.token);

            // Refetch the session data to reflect the logged-in state
            queryClient.invalidateQueries();

            setUsername("");
            setPassword("");
        } catch (err) {
            setError("Invalid credentials");
        }
    };

    return (
        <form onSubmit={handleLogin}>
            <div>
                <label htmlFor="username">Username</label>
                <input
                    id="username"
                    type="text"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    required
                />
            </div>
            <div>
                <label htmlFor="password">Password</label>
                <input
                    id="password"
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required
                />
            </div>
            {error && <p>{error}</p>}
            <button type="submit">Login</button>
        </form>
    );
};

export default LoginForm;
