"use client";

import { FormEvent, useState } from "react";
import { useRouter } from "next/navigation";

export default function AdminLoginPage() {
  const router = useRouter();

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    setError("");
    setLoading(true);

    try {
      const response = await fetch("/api/admin/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          username,
          password,
        }),
      });

      const result = await response.json();

      if (!response.ok || !result.success) {
        setError(result.message || "Username atau password salah.");
        return;
      }

      // Sementara untuk tahap pengujian.
      // Nanti akan diganti dengan HTTP-only cookie/session.
      
      router.push("/secure-panel");
      router.refresh();
    } catch (error) {
      console.error("LOGIN ERROR:", error);
      setError("Tidak dapat terhubung ke server.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <main className="min-vh-100 d-flex align-items-center justify-content-center bg-body-tertiary px-3 py-5">
      <div className="w-100" style={{ maxWidth: "430px" }}>
        <div className="text-center mb-4">
          <div
            className="bg-success text-white rounded-4 d-inline-flex align-items-center justify-content-center shadow-sm mb-3"
            style={{
              width: "64px",
              height: "64px",
            }}
          >
            <i className="bi bi-shield-lock-fill fs-3"></i>
          </div>

          <h1 className="fw-bold mb-2">
            Admin Login
          </h1>

          <p className="text-secondary mb-0">
            Masuk ke Admin Control Center GloVaTech.
          </p>
        </div>

        <div className="card border-0 shadow-sm rounded-4">
          <div className="card-body p-4 p-md-5">
            <form onSubmit={handleSubmit}>
              {/* USERNAME */}
              <div className="mb-3">
                <label
                  htmlFor="username"
                  className="form-label fw-semibold"
                >
                  Username
                </label>

                <div className="input-group">
                  <span className="input-group-text bg-body">
                    <i className="bi bi-person"></i>
                  </span>

                  <input
                    id="username"
                    type="text"
                    className="form-control"
                    value={username}
                    onChange={(event) =>
                      setUsername(event.target.value)
                    }
                    placeholder="Masukkan username"
                    autoComplete="username"
                    disabled={loading}
                    required
                  />
                </div>
              </div>

              {/* PASSWORD */}
              <div className="mb-3">
                <label
                  htmlFor="password"
                  className="form-label fw-semibold"
                >
                  Password
                </label>

                <div className="input-group">
                  <span className="input-group-text bg-body">
                    <i className="bi bi-key"></i>
                  </span>

                  <input
                    id="password"
                    type="password"
                    className="form-control"
                    value={password}
                    onChange={(event) =>
                      setPassword(event.target.value)
                    }
                    placeholder="Masukkan password"
                    autoComplete="current-password"
                    disabled={loading}
                    required
                  />
                </div>
              </div>

              {/* ERROR */}
              {error && (
                <div
                  className="alert alert-danger d-flex align-items-center gap-2 py-2"
                  role="alert"
                >
                  <i className="bi bi-exclamation-triangle-fill"></i>
                  <span>{error}</span>
                </div>
              )}

              {/* LOGIN BUTTON */}
              <button
                type="submit"
                className="btn btn-success w-100 py-2 fw-semibold"
                disabled={loading}
              >
                {loading ? (
                  <>
                    <span
                      className="spinner-border spinner-border-sm me-2"
                      aria-hidden="true"
                    ></span>
                    Memproses...
                  </>
                ) : (
                  <>
                    <i className="bi bi-box-arrow-in-right me-2"></i>
                    Login Admin
                  </>
                )}
              </button>
            </form>
          </div>
        </div>

        {/* BACK TO WEBSITE */}
        <div className="text-center mt-4">
          <a
            href="/"
            className="text-secondary text-decoration-none small"
          >
            <i className="bi bi-arrow-left me-1"></i>
            Kembali ke website
          </a>
        </div>
      </div>
    </main>
  );
}


