"use client";

import { useState, useEffect } from "react";
import { ChevronDown, ChevronUp, X, SlidersHorizontal, Search } from "lucide-react";
import { cn, FUEL_TYPES, TRANSMISSIONS, BODY_TYPES } from "@/lib/utils";
import { fetchBrands } from "@/lib/api";
import BodyTypeSilhouette from "@/components/ui/BodyTypeSilhouette";

interface Filters {
  brand: string[];
  fuelType: string[];
  transmission: string[];
  bodyType: string[];
  priceMin: number;
  priceMax: number;
  seating?: number;
  hasADAS?: boolean;
  ncapRating?: string;
  isEV?: boolean;
}

interface Props {
  filters: Filters;
  onChange: (f: Partial<Filters>) => void;
  onReset: () => void;
  totalCount: number;
}

/* ── Accordion section ─────────────────────────────────────────────────────── */
function Section({
  title,
  children,
  count = 0,
  defaultOpen = true,
}: {
  title: string;
  children: React.ReactNode;
  count?: number;
  defaultOpen?: boolean;
}) {
  const [open, setOpen] = useState(defaultOpen);
  const sectionId = `filter-${title.toLowerCase().replace(/\s+/g, "-")}`;

  return (
    <div className="border-b border-gray-100 last:border-0">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        aria-expanded={open}
        aria-controls={sectionId}
        className="w-full flex items-center justify-between px-4 py-3.5 text-left hover:bg-gray-50/80 transition-colors"
      >
        <div className="flex items-center gap-2">
          <span className="text-sm font-black text-gray-800">{title}</span>
          {count > 0 && (
            <span className="bg-blue-600 text-white text-[10px] font-black px-1.5 py-0.5 rounded-full min-w-[18px] text-center">
              {count}
            </span>
          )}
        </div>
        {open
          ? <ChevronUp className="w-3.5 h-3.5 text-gray-400" aria-hidden="true" />
          : <ChevronDown className="w-3.5 h-3.5 text-gray-400" aria-hidden="true" />
        }
      </button>
      {open && (
        <div id={sectionId} className="px-4 pb-4">
          {children}
        </div>
      )}
    </div>
  );
}

/* ── Checkbox item ─────────────────────────────────────────────────────────── */
function CheckItem({
  label,
  checked,
  onChange,
}: {
  label: string;
  checked: boolean;
  onChange: () => void;
}) {
  return (
    <label
      className={cn(
        "flex items-center gap-2.5 py-1.5 cursor-pointer rounded-xl px-1 transition-colors",
        checked ? "text-blue-600" : "text-gray-700 hover:text-gray-900"
      )}
    >
      <div
        className={cn(
          "w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-all duration-200",
          checked
            ? "bg-blue-600 border-blue-600"
            : "bg-white border-gray-300"
        )}
        aria-hidden="true"
      >
        {checked && (
          <svg viewBox="0 0 10 8" className="w-2.5 h-2 fill-none stroke-white stroke-[2]">
            <polyline points="1,4 3.5,7 9,1" />
          </svg>
        )}
      </div>
      <input
        type="checkbox"
        checked={checked}
        onChange={onChange}
        className="sr-only"
        aria-label={`Filter by ${label}`}
      />
      <span className={cn("text-sm leading-none", checked ? "font-semibold" : "font-medium")}>
        {label}
      </span>
    </label>
  );
}

/* ── Main sidebar ──────────────────────────────────────────────────────────── */
export default function FilterSidebar({ filters, onChange, onReset, totalCount }: Props) {
  const [brandSearch, setBrandSearch] = useState("");
  const [showAllBrands, setShowAllBrands] = useState(false);
  const [brands, setBrands] = useState<string[]>([]);
  const [brandsLoading, setBrandsLoading] = useState(true);

  useEffect(() => {
    fetchBrands()
      .then((res) => setBrands(res.brands ?? []))
      .catch(() => {
        setBrands([
          "Maruti Suzuki", "Hyundai", "Tata", "Mahindra", "Honda",
          "Toyota", "Kia", "MG", "Skoda", "Volkswagen",
          "Renault", "Jeep", "Mercedes-Benz", "BMW", "Audi",
        ]);
      })
      .finally(() => setBrandsLoading(false));
  }, []);

  const visibleBrands = brandSearch
    ? brands.filter((b) => b.toLowerCase().includes(brandSearch.toLowerCase()))
    : showAllBrands ? brands : brands.slice(0, 8);

  const activeCount =
    filters.brand.length +
    filters.fuelType.length +
    filters.transmission.length +
    filters.bodyType.length +
    (filters.priceMin > 0 || filters.priceMax < 200 ? 1 : 0) +
    (filters.seating ? 1 : 0) +
    (filters.hasADAS ? 1 : 0) +
    (filters.ncapRating ? 1 : 0) +
    (filters.isEV ? 1 : 0);

  function toggle(key: keyof Filters, val: string) {
    const cur = filters[key] as string[];
    onChange({ [key]: cur.includes(val) ? cur.filter((v) => v !== val) : [...cur, val] });
  }

  return (
    <aside aria-label="Filter cars" className="w-full bg-white rounded-[24px] border border-gray-200/70 overflow-hidden shadow-[0_4px_20px_rgba(0,0,0,0.05)]">
      {/* ── Header ── */}
      <div className="flex items-center justify-between px-4 py-4 border-b border-gray-100">
        <div className="flex items-center gap-2.5">
          <div className="w-8 h-8 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center">
            <SlidersHorizontal className="w-4 h-4 text-blue-600" aria-hidden="true" />
          </div>
          <div>
            <p className="text-sm font-black text-gray-900">Filters</p>
            {activeCount > 0 && (
              <p className="text-[10px] text-gray-400 font-medium">{activeCount} active</p>
            )}
          </div>
          {activeCount > 0 && (
            <span
              className="bg-blue-600 text-white text-[10px] font-black px-1.5 py-0.5 rounded-full"
              aria-label={`${activeCount} active filters`}
            >
              {activeCount}
            </span>
          )}
        </div>
        {activeCount > 0 && (
          <button
            type="button"
            onClick={onReset}
            aria-label="Clear all filters"
            className="flex items-center gap-1 text-xs font-bold text-red-500 hover:text-red-600 transition-colors focus:outline-none focus:ring-2 focus:ring-red-400 rounded-lg px-2 py-1 hover:bg-red-50"
          >
            <X className="w-3.5 h-3.5" aria-hidden="true" />
            Clear
          </button>
        )}
      </div>

      {/* ── Active filter chips ── */}
      {activeCount > 0 && (
        <div className="px-4 py-3 border-b border-gray-100 flex flex-wrap gap-1.5">
          {filters.brand.map((b) => (
            <button
              key={b}
              type="button"
              onClick={() => toggle("brand", b)}
              aria-label={`Remove ${b} filter`}
              className="inline-flex items-center gap-1 bg-blue-50 border border-blue-200 text-blue-700 text-[11px] font-bold px-2.5 py-1 rounded-xl hover:bg-red-50 hover:border-red-200 hover:text-red-600 transition-all duration-200 group"
            >
              {b}
              <X className="w-3 h-3 opacity-50 group-hover:opacity-100" aria-hidden="true" />
            </button>
          ))}
          {filters.fuelType.map((f) => (
            <button
              key={f}
              type="button"
              onClick={() => toggle("fuelType", f)}
              aria-label={`Remove ${f} filter`}
              className="inline-flex items-center gap-1 bg-green-50 border border-green-200 text-green-700 text-[11px] font-bold px-2.5 py-1 rounded-xl hover:bg-red-50 hover:border-red-200 hover:text-red-600 transition-all duration-200 group"
            >
              {f}
              <X className="w-3 h-3 opacity-50 group-hover:opacity-100" aria-hidden="true" />
            </button>
          ))}
          {filters.transmission.map((t) => (
            <button
              key={t}
              type="button"
              onClick={() => toggle("transmission", t)}
              aria-label={`Remove ${t} filter`}
              className="inline-flex items-center gap-1 bg-purple-50 border border-purple-200 text-purple-700 text-[11px] font-bold px-2.5 py-1 rounded-xl hover:bg-red-50 hover:border-red-200 hover:text-red-600 transition-all duration-200 group"
            >
              {t}
              <X className="w-3 h-3 opacity-50 group-hover:opacity-100" aria-hidden="true" />
            </button>
          ))}
          {filters.bodyType.map((b) => (
            <button
              key={b}
              type="button"
              onClick={() => toggle("bodyType", b)}
              aria-label={`Remove ${b} filter`}
              className="inline-flex items-center gap-1 bg-orange-50 border border-orange-200 text-orange-700 text-[11px] font-bold px-2.5 py-1 rounded-xl hover:bg-red-50 hover:border-red-200 hover:text-red-600 transition-all duration-200 group"
            >
              {b}
              <X className="w-3 h-3 opacity-50 group-hover:opacity-100" aria-hidden="true" />
            </button>
          ))}
        </div>
      )}

      {/* ── Budget ── */}
      <Section title="Budget" count={filters.priceMin > 0 || filters.priceMax < 200 ? 1 : 0}>
        <div className="space-y-3">
          <div className="flex justify-between text-xs font-semibold text-gray-500">
            <span>₹{filters.priceMin}L</span>
            <span>₹{filters.priceMax}L{filters.priceMax >= 200 ? "+" : ""}</span>
          </div>

          {/* Track */}
          <div className="relative py-2">
            <div className="relative h-1.5 bg-gray-200 rounded-full">
              <div
                className="absolute h-1.5 bg-gradient-to-r from-blue-600 to-cyan-500 rounded-full"
                style={{
                  left: `${(filters.priceMin / 200) * 100}%`,
                  right: `${100 - (filters.priceMax / 200) * 100}%`,
                }}
                aria-hidden="true"
              />
            </div>
            <input
              type="range" min={0} max={200} step={1}
              value={filters.priceMin}
              aria-label="Minimum price in lakhs"
              onChange={(e) => onChange({ priceMin: Math.min(+e.target.value, filters.priceMax - 1) })}
              className="absolute inset-0 w-full opacity-0 cursor-pointer h-5 top-[-4px]"
            />
            <input
              type="range" min={0} max={200} step={1}
              value={filters.priceMax}
              aria-label="Maximum price in lakhs"
              onChange={(e) => onChange({ priceMax: Math.max(+e.target.value, filters.priceMin + 1) })}
              className="absolute inset-0 w-full opacity-0 cursor-pointer h-5 top-[-4px]"
            />
          </div>

          {/* Quick chips */}
          <div className="grid grid-cols-2 gap-1.5" role="group" aria-label="Quick budget ranges">
            {[
              { label: "Under ₹5L",  min: 0,  max: 5   },
              { label: "₹5–10L",     min: 5,  max: 10  },
              { label: "₹10–20L",    min: 10, max: 20  },
              { label: "Above ₹20L", min: 20, max: 200 },
            ].map(({ label, min, max }) => {
              const active = filters.priceMin === min && filters.priceMax === max;
              return (
                <button
                  key={label}
                  type="button"
                  onClick={() => onChange({ priceMin: min, priceMax: max })}
                  aria-pressed={active}
                  className={cn(
                    "text-xs px-2 py-2 rounded-xl border font-bold transition-all duration-200 text-center",
                    active
                      ? "border-blue-500 bg-blue-50 text-blue-600 shadow-sm"
                      : "border-gray-200 text-gray-600 hover:border-blue-300 hover:text-blue-600 hover:bg-blue-50/50"
                  )}
                >
                  {label}
                </button>
              );
            })}
          </div>
        </div>
      </Section>

      {/* ── Brand ── */}
      <Section title="Brand" count={filters.brand.length}>
        <div className="space-y-1">
          {/* Search */}
          <div className="relative mb-2">
            <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400" aria-hidden="true" />
            <input
              type="search"
              placeholder="Search brands…"
              value={brandSearch}
              onChange={(e) => setBrandSearch(e.target.value)}
              aria-label="Search car brands"
              className="w-full border border-gray-200 rounded-xl pl-8 pr-3 py-2 text-xs text-gray-700 outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all"
            />
          </div>

          {brandsLoading ? (
            <div className="space-y-2 py-1">
              {Array.from({ length: 6 }).map((_, i) => (
                <div key={i} className="h-6 bg-gray-100 rounded-xl animate-pulse" />
              ))}
            </div>
          ) : (
            <>
              {visibleBrands.map((b) => (
                <CheckItem
                  key={b}
                  label={b}
                  checked={filters.brand.includes(b)}
                  onChange={() => toggle("brand", b)}
                />
              ))}
              {!brandSearch && brands.length > 8 && (
                <button
                  type="button"
                  onClick={() => setShowAllBrands((s) => !s)}
                  aria-expanded={showAllBrands}
                  className="text-xs font-bold text-blue-600 hover:text-blue-700 mt-1.5 flex items-center gap-1"
                >
                  {showAllBrands
                    ? <><ChevronUp className="w-3 h-3" /> Show Less</>
                    : <><ChevronDown className="w-3 h-3" /> +{brands.length - 8} more brands</>
                  }
                </button>
              )}
            </>
          )}
        </div>
      </Section>

      {/* ── Fuel Type ── */}
      <Section title="Fuel Type" count={filters.fuelType.length}>
        <div className="space-y-0.5" role="group" aria-label="Filter by fuel type">
          {FUEL_TYPES.map((f) => (
            <CheckItem
              key={f}
              label={f}
              checked={filters.fuelType.includes(f)}
              onChange={() => toggle("fuelType", f)}
            />
          ))}
        </div>
      </Section>

      {/* ── Transmission ── */}
      <Section title="Transmission" count={filters.transmission.length}>
        <div className="space-y-0.5" role="group" aria-label="Filter by transmission">
          {TRANSMISSIONS.map((t) => (
            <CheckItem
              key={t}
              label={t}
              checked={filters.transmission.includes(t)}
              onChange={() => toggle("transmission", t)}
            />
          ))}
        </div>
      </Section>

      {/* ── Body Type ── */}
      <Section title="Body Type" count={filters.bodyType.length} defaultOpen={false}>
        <div className="space-y-1" role="group" aria-label="Filter by body type">
          {BODY_TYPES.map((b) => {
            const active = filters.bodyType.includes(b);
            return (
              <button
                key={b}
                type="button"
                onClick={() => toggle("bodyType", b)}
                aria-pressed={active}
                className={cn(
                  "w-full flex items-center gap-3 px-3 py-2.5 rounded-xl border transition-all duration-200 text-left",
                  active
                    ? "border-blue-300 bg-blue-50 text-blue-700"
                    : "border-gray-100 bg-white text-gray-700 hover:border-blue-200 hover:bg-blue-50/40"
                )}
              >
                <div className={cn(
                  "w-10 h-6 shrink-0 flex items-center justify-center",
                  active ? "text-blue-500" : "text-gray-300"
                )}>
                  <BodyTypeSilhouette type={b} className="w-full h-full" />
                </div>
                <span className={cn("text-sm", active ? "font-bold" : "font-medium")}>{b}</span>
                {active && (
                  <div className="ml-auto w-4 h-4 rounded-full bg-blue-600 flex items-center justify-center shrink-0">
                    <svg viewBox="0 0 10 8" className="w-2.5 h-2 fill-none stroke-white stroke-[2]">
                      <polyline points="1,4 3.5,7 9,1" />
                    </svg>
                  </div>
                )}
              </button>
            );
          })}
        </div>
      </Section>

      {/* ── Seating Capacity ── */}
      <Section title="Seating Capacity" count={filters.seating ? 1 : 0} defaultOpen={false}>
        <div className="grid grid-cols-4 gap-1.5" role="group" aria-label="Filter by seating capacity">
          {[5, 6, 7, 8].map((seats) => {
            const active = filters.seating === seats;
            return (
              <button
                key={seats}
                type="button"
                onClick={() => onChange({ seating: active ? undefined : seats })}
                aria-pressed={active}
                className={cn(
                  "text-xs px-2 py-2.5 rounded-xl border font-black transition-all duration-200 text-center",
                  active
                    ? "border-blue-500 bg-blue-50 text-blue-600 shadow-sm"
                    : "border-gray-200 text-gray-600 hover:border-blue-300 hover:text-blue-600 hover:bg-blue-50/50"
                )}
              >
                {seats}+
              </button>
            );
          })}
        </div>
        <p className="text-[10px] text-gray-400 mt-2">Shows cars with minimum N seats</p>
      </Section>

      {/* ── Features ── */}
      <Section title="Features" count={(filters.hasADAS ? 1 : 0) + (filters.isEV ? 1 : 0)} defaultOpen={false}>
        {[
          { key: "hasADAS" as const, label: "ADAS Available", sub: "Advanced Driver Assistance Systems" },
          { key: "isEV"    as const, label: "Electric Only",  sub: "Battery Electric Vehicles" },
        ].map(({ key, label, sub }) => {
          const active = !!filters[key];
          return (
            <label key={key} className={cn(
              "flex items-center gap-2.5 py-2 cursor-pointer rounded-xl px-1 transition-colors",
              active ? "text-blue-600" : "text-gray-700 hover:text-gray-900"
            )}>
              <div className={cn(
                "w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-all duration-200",
                active ? "bg-blue-600 border-blue-600" : "bg-white border-gray-300"
              )} aria-hidden="true">
                {active && (
                  <svg viewBox="0 0 10 8" className="w-2.5 h-2 fill-none stroke-white stroke-[2]">
                    <polyline points="1,4 3.5,7 9,1" />
                  </svg>
                )}
              </div>
              <input type="checkbox" checked={active}
                onChange={() => onChange({ [key]: active ? undefined : true })}
                className="sr-only" aria-label={`Filter: ${label}`}
              />
              <div>
                <span className={cn("text-sm leading-none block", active ? "font-semibold" : "font-medium")}>{label}</span>
                <span className="text-[10px] text-gray-400">{sub}</span>
              </div>
            </label>
          );
        })}
      </Section>

      {/* ── Safety (NCAP) ── */}
      <Section title="Safety Rating" count={filters.ncapRating ? 1 : 0} defaultOpen={false}>
        <div className="grid grid-cols-3 gap-1.5" role="group" aria-label="Filter by NCAP rating">
          {["5 Star", "4 Star", "3 Star"].map((rating) => {
            const active = filters.ncapRating === rating;
            return (
              <button key={rating} type="button"
                onClick={() => onChange({ ncapRating: active ? undefined : rating })}
                aria-pressed={active}
                className={cn(
                  "text-xs px-2 py-2.5 rounded-xl border font-black transition-all duration-200 text-center",
                  active
                    ? "border-amber-400 bg-amber-50 text-amber-700 shadow-sm"
                    : "border-gray-200 text-gray-600 hover:border-amber-300 hover:text-amber-600 hover:bg-amber-50/50"
                )}
              >
                {rating}
              </button>
            );
          })}
        </div>
        <p className="text-[10px] text-gray-400 mt-2">Global NCAP crash test rating</p>
      </Section>

      {/* ── Results count ── */}
      {totalCount > 0 && (
        <div className="px-4 py-3.5 border-t border-gray-100 bg-gradient-to-r from-blue-50 to-cyan-50">
          <p className="text-xs text-center font-bold text-blue-700">
            {totalCount.toLocaleString()} cars match your filters
          </p>
        </div>
      )}
    </aside>
  );
}
