'use client';

import React from "react";
import fetchWithCheck from "@/api-queries/utils/fetch-with-check";
import ValidationError from "@/api-queries/exceptions/validation-error";
import {NotFoundException} from "@/api-queries/exceptions/not-found-exception";

export default function Login() {
    const login = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();

        const token = event.currentTarget.token.value;

        try {
            const response = await fetchWithCheck<{success: boolean}>(`/api/login`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    token,
                }),
            });

            if (response.success) {
                window.location.href = "/";
            }
        } catch (e: unknown) {
            if (e instanceof ValidationError || e instanceof NotFoundException) {
                alert(e.message);

                return;
            }

            console.error(e);
        }
    };

    return <div className="flex items-center justify-center min-h-screen bg-gray-50">
        <form className="bg-white p-6 rounded shadow-md w-full max-w-sm" onSubmit={login}>
            <h1 className="text-2xl font-bold mb-4 text-center">GETIN.RO SCANNER</h1>
            <div className="mb-4">
                <input
                    type="text"
                    id="token"
                    name="token"
                    className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                    placeholder="Enter scanner token"
                />
            </div>
            <div className="flex items-center justify-between">
                <button
                    type="submit"
                    className="w-full bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
                >
                    Login
                </button>
            </div>
        </form>
    </div>;
}
