import React, { useState } from "react";
import { Lock, Mail, ShieldAlert, ArrowRight, Loader2 } from "lucide-react";
import { motion } from "motion/react";

interface AdminLoginProps {
  lang: "en" | "id";
  onAdminLoginSuccess: (admin: { email: string; role: string }) => void;
  onBackToHome: () => void;
}

export default function AdminLogin({ lang, onAdminLoginSuccess, onBackToHome }: AdminLoginProps) {
  const isEn = lang === "en";
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState("");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMsg("");

    if (!email || !password) {
      setErrorMsg(isEn ? "Administrator email and password are required." : "Email dan kata sandi administrator wajib diisi.");
      return;
    }

    setLoading(true);

    try {
      const response = await fetch("/api/auth/login-admin", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password })
      });

      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || (isEn ? "Verification error. Access denied." : "Sistem gagal memverifikasi kredensial administrator."));
      }

      // Valid admin
      localStorage.setItem("luniar_admin_session", JSON.stringify(data.admin));
      onAdminLoginSuccess(data.admin);
    } catch (err: any) {
      setErrorMsg(err.message || (isEn ? "Validation failed. Check credentials." : "Verifikasi gagal. Silakan periksa kembali kredensial Anda."));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-md mx-auto my-16 font-sans text-[#1A1A1A] animate-fade-in" id="admin-login-module">
      <div className="bg-[#1A1A1A] text-white border border-[#333333] p-8 md:p-10 shadow-2xl relative">
        {/* Secure Glowing Indicator Red Line for Admin Portal */}
        <div className="absolute top-0 left-0 w-full h-[3px] bg-[#C5A572]"></div>

        <div className="text-center space-y-3 mb-10">
          <div className="inline-flex items-center justify-center p-3 rounded-full bg-[#C5A572]/10 text-[#C5A572] mb-1">
            <Lock size={20} />
          </div>
          <span className="font-sans text-[9px] font-bold uppercase tracking-[0.3em] text-[#C5A572] block">
            {isEn ? "ADMINISTRATOR ARCHIVES" : "ARSIP ADMINISTRATOR"}
          </span>
          <h2 className="font-serif text-2xl font-light tracking-wide text-white">
            {isEn ? "Curatorial Main Desk" : "Konsol Kurasi Utama"}
          </h2>
          <p className="font-sans text-[10px] text-gray-400">
            {isEn 
              ? "Access requires authorized system clearance validations." 
              : "Akses konsol memerlukan otorisasi sistem kunci keamanan terverifikasi."}
          </p>
        </div>

        {errorMsg && (
          <motion.div 
            initial={{ opacity: 0, scale: 0.98 }}
            animate={{ opacity: 1, scale: 1 }}
            className="mb-8 p-4 bg-red-950/40 border border-red-900/50 text-red-300 text-xs flex items-start gap-2.5 text-left"
          >
            <ShieldAlert size={16} className="mt-0.5 shrink-0 text-[#C5A572]" />
            <div>{errorMsg}</div>
          </motion.div>
        )}

        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="space-y-2 text-left">
            <label className="block text-[9px] font-bold uppercase tracking-widest text-[#C5A572]">
              {isEn ? "ADMIN EMAIL ADDRESS" : "ALAMAT EMAIL ADM"}
            </label>
            <div className="relative">
              <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-gray-500">
                <Mail size={14} />
              </span>
              <input
                type="email"
                required
                placeholder="admin@luniarestate.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="w-full pl-10 pr-4 py-3.5 bg-neutral-900 border border-neutral-800 focus:border-[#C5A572] outline-none text-xs transition-all duration-300 text-white rounded-none placeholder-gray-600"
              />
            </div>
            {email === "" && (
              <p className="text-[10px] text-neutral-500 italic leading-normal">
                {isEn 
                  ? "Default: admin@luniarestate.com (pass: luniarsystem2026)" 
                  : "Nilai bawaan: admin@luniarestate.com (sandi: luniarsystem2026)"}
              </p>
            )}
          </div>

          <div className="space-y-2 text-left">
            <label className="block text-[9px] font-bold uppercase tracking-widest text-[#C5A572]">
              {isEn ? "SYSTEM PASSWORD" : "KATA SANDI SISTEM"}
            </label>
            <div className="relative">
              <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-gray-500">
                <Lock size={14} />
              </span>
              <input
                type="password"
                required
                placeholder="••••••••••••"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="w-full pl-10 pr-4 py-3.5 bg-neutral-900 border border-neutral-800 focus:border-[#C5A572] outline-none text-xs transition-all duration-300 text-white rounded-none placeholder-gray-600"
              />
            </div>
          </div>

          <div className="pt-2">
            <button
              type="submit"
              disabled={loading}
              className="w-full bg-[#C5A572] hover:bg-white hover:text-[#1A1A1A] text-[#1A1A1A] py-4 text-[10px] font-bold uppercase tracking-[0.25em] transition-all duration-500 inline-flex items-center justify-center gap-2 cursor-pointer rounded-none disabled:opacity-50"
            >
              {loading ? (
                <>
                  <Loader2 size={12} className="animate-spin" />
                  <span>{isEn ? "VALIDATING..." : "MEMPROSES VERIFIKASI..."}</span>
                </>
              ) : (
                <>
                  <span>{isEn ? "ENTER CONSOLE" : "MASUK KE KONSOL"}</span>
                  <ArrowRight size={12} />
                </>
              )}
            </button>
          </div>
        </form>

        <div className="text-center mt-8">
          <button
            onClick={onBackToHome}
            className="text-[9px] text-[#C5A572] hover:text-white uppercase tracking-[0.2em] transition-all duration-200 cursor-pointer focus:outline-none"
          >
            {isEn ? "← BACK TO MAIN HOME" : "← KEMBALI KE LAMAN UTAMA"}
          </button>
        </div>
      </div>
    </div>
  );
}
