summaryrefslogtreecommitdiff
path: root/app/login/page.tsx
blob: 9e0a5feaf929093ae63c644a5fba5d63d61000c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import odooApi from "../lib/api/odooApi";

type LoginStatus = { code?: number; description?: string };
type LoginResult = { token?: string; email?: string; [k: string]: unknown };
type LoginResponse = { status?: LoginStatus; result?: LoginResult };

export default function LoginPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setLoading(true);

    const fd = new FormData(e.currentTarget);

    // Narrowing ke string, bukan File/null
    const rawEmail = fd.get("email");
    const rawPassword = fd.get("password");
    const email = typeof rawEmail === "string" ? rawEmail.trim() : "";
    const password = typeof rawPassword === "string" ? rawPassword : "";

    if (!email || !password) {
      alert("Email dan password wajib diisi.");
      setLoading(false);
      return;
    }

    try {
      const res = (await odooApi("POST", "/api/v1/user/login", {
        email,
        password,
      })) as unknown as LoginResponse;

      if (res?.status?.code === 200) {
        // Jika kamu punya util setAuth(res.result), panggil di sini.
        router.push("/");
      } else {
        alert(res?.status?.description || "Login gagal. Periksa email/password.");
      }
    } catch (err) {
      console.error(err);
      alert("Terjadi kesalahan saat login.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <main className="min-h-screen flex items-center justify-center">
      <form onSubmit={onSubmit} className="w-full max-w-sm p-6 space-y-3 border rounded">
        <h1 className="text-xl font-semibold">Login</h1>

        <input
          name="email"
          type="email"
          placeholder="Email"
          className="w-full border rounded px-3 py-2"
          required
        />

        <input
          name="password"
          type="password"
          placeholder="Password"
          className="w-full border rounded px-3 py-2"
          required
        />

        <button
          type="submit"
          disabled={loading}
          className="w-full bg-red-600 text-white rounded py-2"
        >
          {loading ? "Loading..." : "Login"}
        </button>
      </form>
    </main>
  );
}