import { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import { Search, User, Menu, X, ShoppingBag, LayoutDashboard } from "lucide-react";
import axios from "axios";
import { toast } from "sonner";

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

export default function Navbar() {
  const [isOpen, setIsOpen] = useState(false);
  const [vin, setVin] = useState("");
  const [vinLoading, setVinLoading] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const navigate = useNavigate();
  const isLoggedIn = !!localStorage.getItem("user_token");
  const isAdmin = !!localStorage.getItem("admin_token");

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const handleVinSearch = async (e) => {
    e.preventDefault();
    if (!vin || vin.length < 11) { toast.error("Enter a valid VIN"); return; }
    setVinLoading(true);
    try {
      const { data } = await axios.get(`${API}/vin-decode/${vin}`);
      navigate(`/inventory?vin=${vin}&year=${data.year || ""}&make=${data.make || ""}&model=${data.model || ""}`);
      setVin("");
    } catch { toast.error("VIN decode failed"); }
    setVinLoading(false);
  };

  const NAV = [
    { to: "/", label: "Home" },
    { to: "/inventory", label: "Parts" },
    { to: "/find-part", label: "Request" },
    { to: "/how-it-works", label: "How It Works" },
  ];

  return (
    <nav data-testid="main-navbar" className={`fixed top-0 left-0 right-0 z-50 transition-all duration-200 ${scrolled ? "bg-[#0B0B0B]/95 backdrop-blur-sm border-b border-[#2A2A2A]" : "bg-[#0B0B0B] border-b border-[#2A2A2A]/50"}`}>
      <div className="max-w-[1400px] mx-auto px-4 lg:px-6">
        <div className="flex items-center justify-between h-16">
          {/* LEFT: Logo */}
          <Link to="/" data-testid="nav-logo" className="flex-shrink-0 flex items-center gap-2">
            <span className="text-[15px] font-extrabold tracking-[-0.03em] text-white uppercase">
              QUEEN CITY<span className="text-[#3B82F6] ml-1">AUTO</span>
            </span>
          </Link>

          {/* CENTER: VIN Search */}
          <form onSubmit={handleVinSearch} className="hidden md:flex items-center flex-1 max-w-md mx-8">
            <div className="relative w-full">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-[#9A9A9A]" />
              <input
                data-testid="nav-vin-search"
                type="text"
                value={vin}
                onChange={e => setVin(e.target.value.toUpperCase())}
                maxLength={17}
                placeholder="Search by VIN..."
                className="w-full h-9 pl-10 pr-20 bg-[#1E1E1E] border border-[#2A2A2A] rounded text-[13px] text-white placeholder:text-[#666] focus:outline-none focus:border-[#3B82F6] transition-colors font-mono"
              />
              <button
                type="submit"
                disabled={vinLoading}
                data-testid="nav-vin-submit"
                className="absolute right-1 top-1/2 -translate-y-1/2 h-7 px-3 bg-[#3B82F6] hover:bg-[#2563EB] text-white text-[11px] font-semibold uppercase tracking-wide rounded-sm transition-colors"
              >
                {vinLoading ? "..." : "Search"}
              </button>
            </div>
          </form>

          {/* RIGHT: Nav links + actions */}
          <div className="hidden lg:flex items-center gap-1">
            {NAV.map(n => (
              <Link key={n.to} to={n.to} className="px-3 py-1.5 text-[13px] font-medium text-[#9A9A9A] hover:text-white transition-colors">
                {n.label}
              </Link>
            ))}
            <div className="w-px h-5 bg-[#2A2A2A] mx-2" />
            {isLoggedIn ? (
              <Link to="/dashboard" data-testid="nav-dashboard-btn" className="flex items-center gap-1.5 px-3 py-1.5 text-[13px] font-medium text-[#9A9A9A] hover:text-white transition-colors">
                <LayoutDashboard className="h-4 w-4" /> Dashboard
              </Link>
            ) : (
              <Link to="/account" data-testid="nav-account-btn" className="flex items-center gap-1.5 px-3 py-1.5 text-[13px] font-medium text-[#9A9A9A] hover:text-white transition-colors">
                <User className="h-4 w-4" /> Login
              </Link>
            )}
            {isAdmin && (
              <Link to="/admin/dashboard" data-testid="nav-admin-btn" className="flex items-center gap-1.5 h-8 px-3 bg-[#1E1E1E] border border-[#2A2A2A] hover:border-[#3B82F6] text-[11px] font-semibold text-[#9A9A9A] hover:text-white uppercase tracking-wide transition-colors rounded-sm">
                Admin
              </Link>
            )}
          </div>

          {/* MOBILE: hamburger */}
          <button onClick={() => setIsOpen(!isOpen)} className="lg:hidden text-white p-1.5">
            {isOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
          </button>
        </div>

        {/* MOBILE: VIN search */}
        <div className="md:hidden pb-3">
          <form onSubmit={handleVinSearch} className="flex gap-2">
            <input
              type="text"
              value={vin}
              onChange={e => setVin(e.target.value.toUpperCase())}
              maxLength={17}
              placeholder="Search by VIN..."
              className="flex-1 h-9 px-3 bg-[#1E1E1E] border border-[#2A2A2A] rounded text-[13px] text-white placeholder:text-[#666] focus:outline-none focus:border-[#3B82F6] font-mono"
            />
            <button type="submit" disabled={vinLoading} className="h-9 px-4 bg-[#3B82F6] hover:bg-[#2563EB] text-white text-[11px] font-semibold uppercase rounded-sm">
              <Search className="h-4 w-4" />
            </button>
          </form>
        </div>
      </div>

      {/* MOBILE MENU */}
      {isOpen && (
        <div className="lg:hidden bg-[#0B0B0B] border-t border-[#2A2A2A] animate-fade-in">
          {NAV.map(n => (
            <Link key={n.to} to={n.to} onClick={() => setIsOpen(false)} className="block px-6 py-3 text-[14px] font-medium text-[#9A9A9A] hover:text-white border-b border-[#1E1E1E]">
              {n.label}
            </Link>
          ))}
          {isLoggedIn ? (
            <Link to="/dashboard" onClick={() => setIsOpen(false)} className="block px-6 py-3 text-[14px] font-medium text-white">
              Dashboard
            </Link>
          ) : (
            <Link to="/account" onClick={() => setIsOpen(false)} className="block px-6 py-3 text-[14px] font-medium text-white">
              Login / Register
            </Link>
          )}
          <Link to="/admin/login" onClick={() => setIsOpen(false)} className="block px-6 py-3 text-[12px] text-[#666]">
            Admin Portal
          </Link>
        </div>
      )}
    </nav>
  );
}
