"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>
  );
}