import { useState, useEffect } from "react";
import { Link, useSearchParams } from "react-router-dom";
import axios from "axios";
import { Search, SlidersHorizontal, X } from "lucide-react";

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

export default function Inventory() {
  const [searchParams] = useSearchParams();
  const [inventory, setInventory] = useState([]);
  const [filtered, setFiltered] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState(searchParams.get("q") || "");
  const [filters, setFilters] = useState({
    condition: "",
    category: "",
    maxPrice: "",
    year: searchParams.get("year") || "",
    make: searchParams.get("make") || "",
    model: searchParams.get("model") || "",
  });
  const [showFilters, setShowFilters] = useState(false);

  const vinYear = searchParams.get("year");
  const vinMake = searchParams.get("make");
  const vinModel = searchParams.get("model");

  useEffect(() => {
    axios.get(`${API}/inventory`).then(r => {
      setInventory(r.data || []);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, []);

  useEffect(() => {
    let items = [...inventory];
    const q = search.toLowerCase();
    if (q) items = items.filter(i => `${i.name} ${i.category} ${i.make} ${i.model} ${i.vehicle_year}`.toLowerCase().includes(q));
    if (filters.condition) items = items.filter(i => i.condition === filters.condition);
    if (filters.category) items = items.filter(i => i.category === filters.category);
    if (filters.maxPrice) items = items.filter(i => i.price <= parseFloat(filters.maxPrice));
    if (filters.year) items = items.filter(i => String(i.vehicle_year).includes(filters.year));
    if (filters.make) items = items.filter(i => (i.make || "").toLowerCase().includes(filters.make.toLowerCase()));
    if (filters.model) items = items.filter(i => (i.model || "").toLowerCase().includes(filters.model.toLowerCase()));
    setFiltered(items);
  }, [inventory, search, filters]);

  const conditions = [...new Set(inventory.map(i => i.condition))].filter(Boolean);
  const categories = [...new Set(inventory.map(i => i.category))].filter(Boolean);
  const hasActiveFilters = filters.condition || filters.category || filters.maxPrice || filters.year || filters.make || filters.model;
  const clearFilters = () => setFilters({ condition: "", category: "", maxPrice: "", year: "", make: "", model: "" });

  const selectCls = "h-9 px-3 bg-[#1E1E1E] border border-[#2A2A2A] rounded-sm text-[13px] text-white focus:outline-none focus:border-[#3B82F6] appearance-none";

  return (
    <div data-testid="inventory-page" className="min-h-screen bg-[#0B0B0B] pt-24 pb-16">
      <div className="max-w-[1400px] mx-auto px-4 lg:px-6">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold tracking-[-0.03em] text-white">Parts Inventory</h1>
          {vinMake && <p className="text-[14px] text-[#3B82F6] mt-2 font-medium">Showing results for {vinYear} {vinMake} {vinModel}</p>}
          <p className="text-[14px] text-[#9A9A9A] mt-1">{filtered.length} parts available</p>
        </div>

        {/* Search + Filter bar */}
        <div className="flex flex-col sm:flex-row gap-3 mb-6">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-[#666]" />
            <input
              data-testid="inventory-search"
              type="text"
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Search parts by name, category, vehicle..."
              className="w-full h-10 pl-10 pr-4 bg-[#1E1E1E] border border-[#2A2A2A] rounded-sm text-[13px] text-white placeholder:text-[#666] focus:outline-none focus:border-[#3B82F6] transition-colors"
            />
          </div>
          <button data-testid="toggle-filters" onClick={() => setShowFilters(!showFilters)} className={`h-10 px-4 border rounded-sm text-[12px] font-semibold uppercase tracking-wide flex items-center gap-2 transition-colors ${showFilters ? "bg-[#3B82F6] border-[#3B82F6] text-white" : "bg-[#1E1E1E] border-[#2A2A2A] text-[#9A9A9A] hover:border-[#3B82F6]"}`}>
            <SlidersHorizontal className="h-3.5 w-3.5" /> Filters
            {hasActiveFilters && <span className="w-1.5 h-1.5 bg-[#3B82F6] rounded-full" />}
          </button>
        </div>

        {/* Filters */}
        {showFilters && (
          <div data-testid="filter-panel" className="bg-[#121212] border border-[#2A2A2A] rounded-sm p-4 mb-6 flex flex-wrap gap-3 items-end animate-fade-in">
            <div>
              <label className="block text-[10px] font-semibold uppercase tracking-[0.1em] text-[#666] mb-1">Condition</label>
              <select value={filters.condition} onChange={e => setFilters({...filters, condition: e.target.value})} className={selectCls}>
                <option value="">All</option>
                {conditions.map(c => <option key={c} value={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-[10px] font-semibold uppercase tracking-[0.1em] text-[#666] mb-1">Category</label>
              <select value={filters.category} onChange={e => setFilters({...filters, category: e.target.value})} className={selectCls}>
                <option value="">All</option>
                {categories.map(c => <option key={c} value={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-[10px] font-semibold uppercase tracking-[0.1em] text-[#666] mb-1">Max Price</label>
              <input type="number" placeholder="$" value={filters.maxPrice} onChange={e => setFilters({...filters, maxPrice: e.target.value})} className="h-9 w-24 px-3 bg-[#1E1E1E] border border-[#2A2A2A] rounded-sm text-[13px] text-white focus:outline-none focus:border-[#3B82F6]" />
            </div>
            <div>
              <label className="block text-[10px] font-semibold uppercase tracking-[0.1em] text-[#666] mb-1">Year</label>
              <input placeholder="2020" value={filters.year} onChange={e => setFilters({...filters, year: e.target.value})} className="h-9 w-20 px-3 bg-[#1E1E1E] border border-[#2A2A2A] rounded-sm text-[13px] text-white focus:outline-none focus:border-[#3B82F6]" />
            </div>
            <div>
              <label className="block text-[10px] font-semibold uppercase tracking-[0.1em] text-[#666] mb-1">Make</label>
              <input placeholder="Toyota" value={filters.make} onChange={e => setFilters({...filters, make: e.target.value})} className="h-9 w-24 px-3 bg-[#1E1E1E] border border-[#2A2A2A] rounded-sm text-[13px] text-white focus:outline-none focus:border-[#3B82F6]" />
            </div>
            <div>
              <label className="block text-[10px] font-semibold uppercase tracking-[0.1em] text-[#666] mb-1">Model</label>
              <input placeholder="Camry" value={filters.model} onChange={e => setFilters({...filters, model: e.target.value})} className="h-9 w-24 px-3 bg-[#1E1E1E] border border-[#2A2A2A] rounded-sm text-[13px] text-white focus:outline-none focus:border-[#3B82F6]" />
            </div>
            {hasActiveFilters && (
              <button onClick={clearFilters} className="h-9 px-3 text-[11px] text-[#9A9A9A] hover:text-white flex items-center gap-1 transition-colors">
                <X className="h-3.5 w-3.5" /> Clear
              </button>
            )}
          </div>
        )}

        {/* Product Grid */}
        {loading ? (
          <div className="flex justify-center py-20"><div className="w-6 h-6 border-2 border-[#3B82F6] border-t-transparent rounded-full animate-spin" /></div>
        ) : (
          <div data-testid="inventory-grid" className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {filtered.map(item => (
              <div key={item.id} data-testid={`inventory-card-${item.id}`} className="bg-[#1E1E1E] border border-[#2A2A2A] rounded overflow-hidden hover:border-[#3B82F6]/40 transition-all duration-200 group">
                <div className="h-44 bg-[#121212] flex items-center justify-center">
                  {item.image_url ? (
                    <img src={item.image_url} alt={item.name} className="w-full h-full object-cover" loading="lazy" />
                  ) : (
                    <div className="text-[#2A2A2A]">
                      <svg className="h-10 w-10" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z" /></svg>
                    </div>
                  )}
                </div>
                <div className="p-4">
                  <div className="flex items-center gap-2 mb-2">
                    <span className={`px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider rounded-sm ${item.condition === "New" ? "bg-[#28A745]/15 text-[#28A745]" : item.condition === "OEM" ? "bg-[#3B82F6]/15 text-[#3B82F6]" : "bg-[#9A9A9A]/15 text-[#9A9A9A]"}`}>
                      {item.condition}
                    </span>
                    <span className="text-[10px] text-[#666] uppercase">{item.category}</span>
                  </div>
                  <h3 className="text-[14px] font-semibold text-white mb-1 line-clamp-1 group-hover:text-[#3B82F6] transition-colors">{item.name}</h3>
                  <p className="text-[12px] text-[#9A9A9A] mb-3">{item.vehicle_year} {item.make} {item.model}</p>
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-[18px] font-bold text-white">${item.price}</p>
                      {item.retail_price && <p className="text-[11px] text-[#666] line-through">${item.retail_price} retail</p>}
                    </div>
                    <Link
                      to={`/find-part?part=${encodeURIComponent(item.name)}&year=${item.vehicle_year || ""}&make=${item.make || ""}&model=${item.model || ""}`}
                      className="h-8 px-3 bg-[#3B82F6] hover:bg-[#2563EB] text-white text-[11px] font-semibold uppercase rounded-sm flex items-center transition-colors"
                    >
                      Get Quote
                    </Link>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {!loading && filtered.length === 0 && (
          <div className="text-center py-20">
            <p className="text-[#9A9A9A] mb-4">No parts match your search.</p>
            <Link to="/find-part" className="h-10 px-6 bg-[#3B82F6] hover:bg-[#2563EB] text-white text-[13px] font-semibold uppercase rounded-sm inline-flex items-center transition-colors">
              Request a Custom Part
            </Link>
          </div>
        )}
      </div>
    </div>
  );
}
