import { useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { toast } from "sonner";
import { Loader2 } from "lucide-react";

const API = `${process.env.REACT_APP_BACKEND_URL}/api`;

export default function AdminLogin() {
  const navigate = useNavigate();
  const [form, setForm] = useState({ username: "", password: "" });
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      const { data } = await axios.post(`${API}/auth/login`, form);
      localStorage.setItem("admin_token", data.token);
      localStorage.setItem("admin_username", form.username);
      toast.success("Welcome back, Admin");
      navigate("/admin/dashboard");
    } catch (err) {
      toast.error(err.response?.data?.detail || "Invalid credentials");
    }
    setLoading(false);
  };

  const inputCls = "w-full h-11 px-4 bg-[#1E1E1E] border border-[#2A2A2A] rounded-sm text-[14px] text-white placeholder:text-[#666] focus:outline-none focus:border-[#3B82F6] transition-colors";

  return (
    <div className="min-h-screen bg-[#0B0B0B] flex items-center justify-center">
      <div className="w-full max-w-sm mx-auto px-4">
        <div className="text-center mb-8">
          <p className="text-[15px] font-extrabold tracking-[-0.03em] text-white uppercase mb-2">
            QUEEN CITY<span className="text-[#3B82F6] ml-1">AUTO</span>
          </p>
          <h1 className="text-2xl font-bold tracking-[-0.03em] text-white">Admin Portal</h1>
          <p className="text-[13px] text-[#666] mt-2">Internal access only</p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-[11px] font-semibold uppercase tracking-[0.08em] text-[#9A9A9A] mb-1.5">Username</label>
            <input data-testid="admin-username-input" value={form.username} onChange={e => setForm({...form, username: e.target.value})} className={inputCls} required />
          </div>
          <div>
            <label className="block text-[11px] font-semibold uppercase tracking-[0.08em] text-[#9A9A9A] mb-1.5">Password</label>
            <input data-testid="admin-password-input" type="password" value={form.password} onChange={e => setForm({...form, password: e.target.value})} className={inputCls} required />
          </div>
          <button data-testid="admin-login-btn" type="submit" disabled={loading} className="w-full h-12 bg-[#3B82F6] hover:bg-[#2563EB] text-white text-[14px] font-bold uppercase tracking-wide rounded transition-colors flex items-center justify-center">
            {loading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null}
            Sign In
          </button>
        </form>
      </div>
    </div>
  );
}
