"use client";

import { useState } from "react";
import { useRouter, useSearchParams, usePathname } from "next/navigation";
import { SlidersHorizontal, X, ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";

interface Brand { id: string; name: string; slug: string }

interface ProductFiltersProps {
  brands: Brand[];
  currentCategory?: string;
}

export default function ProductFilters({ brands }: ProductFiltersProps) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [open, setOpen] = useState(false);

  const updateParam = (key: string, value: string | null) => {
    const params = new URLSearchParams(searchParams.toString());
    params.delete("page");
    if (value) params.set(key, value);
    else params.delete(key);
    router.push(`${pathname}?${params.toString()}`);
  };

  const activeBrand = searchParams.get("brand");
  const activeMin = searchParams.get("minPrice");
  const activeMax = searchParams.get("maxPrice");
  const activeSort = searchParams.get("sort") || "createdAt";
  const hasFilters = activeBrand || activeMin || activeMax;

  const priceRanges = [
    { label: "Under KES 50,000", min: "0", max: "50000" },
    { label: "KES 50,000 – 80,000", min: "50000", max: "80000" },
    { label: "KES 80,000 – 120,000", min: "80000", max: "120000" },
    { label: "KES 120,000 – 200,000", min: "120000", max: "200000" },
    { label: "Above KES 200,000", min: "200000", max: "" },
  ];

  const clearAll = () => {
    const params = new URLSearchParams(searchParams.toString());
    ["brand", "minPrice", "maxPrice"].forEach((k) => params.delete(k));
    router.push(`${pathname}?${params.toString()}`);
  };

  return (
    <>
      {/* Mobile toggle */}
      <div className="flex gap-2 mb-4 lg:hidden">
        <button
          onClick={() => setOpen(!open)}
          className="flex items-center gap-2 px-4 py-2 border-2 border-sky-200 text-sky-700 rounded-xl text-sm font-medium"
        >
          <SlidersHorizontal className="w-4 h-4" /> Filters
          {hasFilters && <span className="bg-sky-500 text-white text-xs w-5 h-5 rounded-full flex items-center justify-center">!</span>}
        </button>

        {/* Sort */}
        <div className="relative flex-1 sm:flex-none">
          <select
            value={activeSort}
            onChange={(e) => updateParam("sort", e.target.value)}
            className="w-full appearance-none pl-3 pr-8 py-2 border-2 border-slate-200 rounded-xl text-sm focus:border-sky-400 focus:outline-none bg-white"
          >
            <option value="createdAt">Latest</option>
            <option value="price_asc">Price: Low to High</option>
            <option value="price_desc">Price: High to Low</option>
            <option value="name">Name A-Z</option>
          </select>
          <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" />
        </div>
      </div>

      {/* Sidebar */}
      <aside className={cn("lg:block w-64 shrink-0", open ? "block" : "hidden")}>
        <div className="bg-white rounded-2xl border border-slate-100 p-5 space-y-6">
          {/* Header */}
          <div className="flex items-center justify-between">
            <h3 className="font-black text-slate-800">Filters</h3>
            {hasFilters && (
              <button onClick={clearAll} className="text-xs text-red-500 hover:text-red-600 flex items-center gap-1 font-medium">
                <X className="w-3 h-3" /> Clear all
              </button>
            )}
          </div>

          {/* Sort (desktop) */}
          <div className="hidden lg:block">
            <label className="text-xs font-bold text-slate-500 uppercase tracking-wider block mb-2">Sort By</label>
            <div className="space-y-1">
              {[
                { value: "createdAt", label: "Latest" },
                { value: "price_asc", label: "Price: Low to High" },
                { value: "price_desc", label: "Price: High to Low" },
                { value: "name", label: "Name A-Z" },
              ].map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => {
                    if (opt.value.includes("_")) {
                      const [field, ord] = opt.value.split("_");
                      updateParam("sort", field);
                      updateParam("order", ord);
                    } else {
                      updateParam("sort", opt.value);
                      updateParam("order", "desc");
                    }
                  }}
                  className={cn("w-full text-left px-3 py-2 rounded-lg text-sm transition-colors", activeSort === opt.value.split("_")[0] ? "bg-sky-50 text-sky-700 font-medium" : "text-slate-600 hover:bg-slate-50")}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          </div>

          {/* Brand */}
          <div>
            <label className="text-xs font-bold text-slate-500 uppercase tracking-wider block mb-2">Brand</label>
            <div className="space-y-1">
              <button
                onClick={() => updateParam("brand", null)}
                className={cn("w-full text-left px-3 py-2 rounded-lg text-sm transition-colors", !activeBrand ? "bg-sky-50 text-sky-700 font-medium" : "text-slate-600 hover:bg-slate-50")}
              >
                All Brands
              </button>
              {brands.map((brand) => (
                <button
                  key={brand.id}
                  onClick={() => updateParam("brand", activeBrand === brand.slug ? null : brand.slug)}
                  className={cn("w-full text-left px-3 py-2 rounded-lg text-sm transition-colors flex items-center justify-between", activeBrand === brand.slug ? "bg-sky-50 text-sky-700 font-medium" : "text-slate-600 hover:bg-slate-50")}
                >
                  {brand.name}
                  {activeBrand === brand.slug && <X className="w-3 h-3" />}
                </button>
              ))}
            </div>
          </div>

          {/* Price Range */}
          <div>
            <label className="text-xs font-bold text-slate-500 uppercase tracking-wider block mb-2">Price Range</label>
            <div className="space-y-1">
              <button
                onClick={() => { updateParam("minPrice", null); updateParam("maxPrice", null); }}
                className={cn("w-full text-left px-3 py-2 rounded-lg text-sm transition-colors", !activeMin && !activeMax ? "bg-sky-50 text-sky-700 font-medium" : "text-slate-600 hover:bg-slate-50")}
              >
                Any Price
              </button>
              {priceRanges.map((range) => {
                const active = activeMin === range.min && activeMax === range.max;
                return (
                  <button
                    key={range.label}
                    onClick={() => {
                      if (active) { updateParam("minPrice", null); updateParam("maxPrice", null); }
                      else { updateParam("minPrice", range.min || null); updateParam("maxPrice", range.max || null); }
                    }}
                    className={cn("w-full text-left px-3 py-2 rounded-lg text-sm transition-colors", active ? "bg-sky-50 text-sky-700 font-medium" : "text-slate-600 hover:bg-slate-50")}
                  >
                    {range.label}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Condition */}
          <div>
            <label className="text-xs font-bold text-slate-500 uppercase tracking-wider block mb-2">Condition</label>
            <div className="space-y-1">
              {["Brand New", "Refurbished", "Ex-UK"].map((cond) => (
                <button
                  key={cond}
                  onClick={() => updateParam("condition", searchParams.get("condition") === cond ? null : cond)}
                  className={cn("w-full text-left px-3 py-2 rounded-lg text-sm transition-colors", searchParams.get("condition") === cond ? "bg-sky-50 text-sky-700 font-medium" : "text-slate-600 hover:bg-slate-50")}
                >
                  {cond}
                </button>
              ))}
            </div>
          </div>
        </div>
      </aside>
    </>
  );
}
