"use client";

import { useState } from "react";
import axios from "axios";
import { useRouter } from "next/navigation";
import { Lock, User, Shield } from "lucide-react"; // Tambahan ikon Shield untuk Admin

export default function LoginPage() {
  const router = useRouter();
  
  // State untuk menyimpan input user dan pilihan role
  const [loginRole, setLoginRole] = useState("user"); // "user" atau "admin"
  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 {
      // Tembak API Backend Golang menggunakan IP Laptop
      const response = await axios.post("http://172.17.110.6:8080/api/auth/login", {
        nrp_nip: nrp,
        password: password,
        // role_attempt: loginRole // Buka komentar ini jika backend Golang minta parameter role
      });

      const { token, user } = response.data;
      
      // 1. Simpan di localStorage (untuk dipakai di axios frontend)
      localStorage.setItem("token", token);
      localStorage.setItem("user", JSON.stringify(user));

      // 2. Simpan di Cookie agar bisa dibaca oleh middleware.ts Next.js
      document.cookie = `token=${token}; path=/; max-age=86400; SameSite=Lax`;

      // Redirect berdasarkan role dari backend DAN pilihan di UI
      if (user.role === "admin" && loginRole === "admin") {
        router.push("/admin");
      } else if (user.role !== "admin" && loginRole === "user") {
        router.push("/dashboard"); // Halaman pemesanan kelas biasa
      } else {
        // Mencegah user biasa login lewat tab admin, atau sebaliknya
        setError("Role tidak sesuai dengan tipe akun Anda.");
        localStorage.clear(); // Bersihkan token yang terlanjur masuk
        document.cookie = "token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"; // Hapus cookie
      }

    } catch (err: any) {
      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-6">
          <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>

        {/* --- BAGIAN BARU: Toggle Role --- */}
        <div className="flex justify-center mb-6 bg-gray-100 p-1 rounded-lg">
          <button
            type="button"
            onClick={() => { setLoginRole("user"); setError(""); }}
            className={`w-1/2 py-2 text-sm font-semibold rounded-md transition-all ${
              loginRole === "user" ? "bg-white text-blue-600 shadow-sm" : "text-gray-500 hover:text-gray-700"
            }`}
          >
            Pengguna
          </button>
          <button
            type="button"
            onClick={() => { setLoginRole("admin"); setError(""); }}
            className={`w-1/2 py-2 text-sm font-semibold rounded-md transition-all ${
              loginRole === "admin" ? "bg-white text-blue-600 shadow-sm" : "text-gray-500 hover:text-gray-700"
            }`}
          >
            Administrator
          </button>
        </div>
        {/* ------------------------------- */}

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

          {/* Input NRP / Username dinamis tergantung role */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {loginRole === "admin" ? "Username Admin" : "NRP / NIP"}
            </label>
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                {loginRole === "admin" ? (
                  <Shield className="h-5 w-5 text-gray-400" />
                ) : (
                  <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={loginRole === "admin" ? "Masukkan Username..." : "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 transition-colors
              ${loading ? "bg-blue-400 cursor-not-allowed" : loginRole === "admin" ? "bg-slate-800 hover:bg-slate-900" : "bg-blue-600 hover:bg-blue-700"}`}
          >
            {loading ? "Memproses..." : loginRole === "admin" ? "Login sebagai Admin" : "Masuk Sekarang"}
          </button>
        </form>

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