"use client";

import { useState } from "react";
import axios from "axios";
import { useRouter } from "next/navigation";
import { Lock, User } from "lucide-react"; // Ikon cantik

export default function LoginPage() {
  const router = useRouter();
  
  // State untuk menyimpan input user
  const [nrp, setNrp] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  // Fungsi saat tombol Login ditekan
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError("");

    try {
      // 1. Tembak API Backend
      const response = await axios.post("http://localhost:8080/api/auth/login", {
        nrp_nip: nrp,
        password: password,
      });

      // 2. Jika sukses, simpan Token & Data User ke LocalStorage (Browser)
      const { token, user } = response.data;
      localStorage.setItem("token", token);
      localStorage.setItem("user", JSON.stringify(user));

      // 3. Pindah ke halaman Dashboard (Nanti kita buat)
      //alert("Login Berhasil! Selamat datang " + user.full_name); // Alert boleh dimatikan kalau mau
      if (user.role === "admin") {
        router.push("/admin");
      } else {
        router.push("/dashboard");
      }

    } catch (err: any) {
      // Jika gagal, tampilkan pesan error dari backend
      setError(err.response?.data?.error || "Gagal terhubung ke server");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-100">
      <div className="w-full max-w-md bg-white p-8 rounded-2xl shadow-lg">
        {/* Header / Logo */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-blue-600 mb-2">S-CLASS</h1>
          <p className="text-gray-500">Smart Classroom Booking System</p>
        </div>

        {/* Form Login */}
        <form onSubmit={handleLogin} className="space-y-6">
          
          {/* Pesan Error jika ada */}
          {error && (
            <div className="bg-red-100 text-red-600 p-3 rounded-lg text-sm text-center">
              {error}
            </div>
          )}

          {/* Input NRP */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">NRP / NIP</label>
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <User className="h-5 w-5 text-gray-400" />
              </div>
              <input
                type="text"
                required
                className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500"
                placeholder="Masukkan NRP..."
                value={nrp}
                onChange={(e) => setNrp(e.target.value)}
              />
            </div>
          </div>

          {/* Input Password */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Password</label>
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <Lock className="h-5 w-5 text-gray-400" />
              </div>
              <input
                type="password"
                required
                className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500"
                placeholder="••••••"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
            </div>
          </div>

          {/* Tombol Login */}
          <button
            type="submit"
            disabled={loading}
            className={`w-full flex justify-center py-3 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white 
              ${loading ? "bg-blue-400 cursor-not-allowed" : "bg-blue-600 hover:bg-blue-700 focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"}`}
          >
            {loading ? "Memproses..." : "Masuk Sekarang"}
          </button>
        </form>

        {/* Footer Kecil */}
        <div className="mt-6 text-center text-xs text-gray-400">
          © 2026 Skripsi S-CLASS Project
        </div>
      </div>
    </div>
  );
}