'use client';

import { useRouter, usePathname, useSearchParams } from 'next/navigation';
import { useState, useMemo } from 'react';
import type { ProductListAggregations } from '@/lib/shopware-api';

interface Props {
  aggregations: ProductListAggregations;
}

export default function CategoryFilters({ aggregations }: Props) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [priceMin, setPriceMin] = useState(searchParams.get('min-price') ?? '');
  const [priceMax, setPriceMax] = useState(searchParams.get('max-price') ?? '');

  // Current active filter values from URL
  const activeManufacturers = useMemo(
    () => new Set(searchParams.get('manufacturer')?.split(',').filter(Boolean) ?? []),
    [searchParams]
  );
  const activeProperties = useMemo(
    () => new Set(searchParams.get('properties')?.split(',').filter(Boolean) ?? []),
    [searchParams]
  );

  function buildUrl(updates: Record<string, string | null>) {
    const params = new URLSearchParams(searchParams.toString());
    params.delete('page'); // reset to page 1 on filter change
    for (const [key, value] of Object.entries(updates)) {
      if (value === null || value === '') {
        params.delete(key);
      } else {
        params.set(key, value);
      }
    }
    const qs = params.toString();
    return qs ? `${pathname}?${qs}` : pathname;
  }

  function toggleSet(current: Set<string>, id: string): string | null {
    const next = new Set(current);
    next.has(id) ? next.delete(id) : next.add(id);
    return next.size ? Array.from(next).join(',') : null;
  }

  function toggleManufacturer(id: string) {
    router.push(buildUrl({ manufacturer: toggleSet(activeManufacturers, id) }));
  }

  function toggleProperty(id: string) {
    router.push(buildUrl({ properties: toggleSet(activeProperties, id) }));
  }

  function applyPrice() {
    router.push(buildUrl({ 'min-price': priceMin || null, 'max-price': priceMax || null }));
  }

  function clearPrice() {
    setPriceMin('');
    setPriceMax('');
    router.push(buildUrl({ 'min-price': null, 'max-price': null }));
  }

  function clearAll() {
    setPriceMin('');
    setPriceMax('');
    router.push(buildUrl({ manufacturer: null, properties: null, 'min-price': null, 'max-price': null }));
  }

  // Group property options by their group
  const propertyGroups = useMemo(() => {
    const map = new Map<string, { groupName: string; options: NonNullable<typeof aggregations.properties>['entities'] }>();
    for (const opt of aggregations.properties?.entities ?? []) {
      if (!opt.group) continue;
      const gid = opt.group.id;
      if (!map.has(gid)) {
        map.set(gid, {
          groupName: opt.group.translated?.name ?? opt.group.name,
          options: [],
        });
      }
      map.get(gid)!.options.push(opt);
    }
    return Array.from(map.values());
  }, [aggregations.properties]);

  const manufacturers = aggregations.manufacturer?.entities ?? [];
  const priceAgg = aggregations.price;

  const totalActive = activeManufacturers.size + activeProperties.size +
    (searchParams.get('min-price') || searchParams.get('max-price') ? 1 : 0);

  const hasFilters = manufacturers.length > 0 || propertyGroups.length > 0 || priceAgg;
  if (!hasFilters) return null;

  const panel = (
    <div className="space-y-6">
      {/* Active filters + clear all */}
      {totalActive > 0 && (
        <div>
          <div className="flex items-center justify-between mb-2">
            <span className="text-xs font-semibold text-surface-500 uppercase tracking-wider">Active filters</span>
            <button onClick={clearAll} className="text-xs text-brand-600 hover:text-brand-700 font-medium">
              Clear all
            </button>
          </div>
          <div className="flex flex-wrap gap-1.5">
            {Array.from(activeManufacturers).map((id) => {
              const m = manufacturers.find((m) => m.id === id);
              if (!m) return null;
              return (
                <button
                  key={id}
                  onClick={() => toggleManufacturer(id)}
                  className="inline-flex items-center gap-1 px-2 py-1 bg-brand-50 text-brand-700 text-xs rounded-full border border-brand-200 hover:bg-brand-100"
                >
                  {m.translated?.name ?? m.name}
                  <span aria-hidden="true">×</span>
                </button>
              );
            })}
            {Array.from(activeProperties).map((id) => {
              const opt = aggregations.properties?.entities.find((o) => o.id === id);
              if (!opt) return null;
              return (
                <button
                  key={id}
                  onClick={() => toggleProperty(id)}
                  className="inline-flex items-center gap-1 px-2 py-1 bg-brand-50 text-brand-700 text-xs rounded-full border border-brand-200 hover:bg-brand-100"
                >
                  {opt.translated?.name ?? opt.name}
                  <span aria-hidden="true">×</span>
                </button>
              );
            })}
            {(searchParams.get('min-price') || searchParams.get('max-price')) && (
              <button
                onClick={clearPrice}
                className="inline-flex items-center gap-1 px-2 py-1 bg-brand-50 text-brand-700 text-xs rounded-full border border-brand-200 hover:bg-brand-100"
              >
                {searchParams.get('min-price') ?? '0'} – {searchParams.get('max-price') ?? '∞'}
                <span aria-hidden="true">×</span>
              </button>
            )}
          </div>
        </div>
      )}

      {/* Price range */}
      {priceAgg && (
        <FilterSection title="Price">
          <div className="flex items-center gap-2">
            <input
              type="number"
              min={0}
              placeholder={String(Math.floor(Number(priceAgg.min)))}
              value={priceMin}
              onChange={(e) => setPriceMin(e.target.value)}
              className="w-full px-2 py-1.5 text-sm border border-surface-200 rounded-lg focus:outline-none focus:border-brand-400"
            />
            <span className="text-surface-400 text-sm flex-shrink-0">–</span>
            <input
              type="number"
              min={0}
              placeholder={String(Math.ceil(Number(priceAgg.max)))}
              value={priceMax}
              onChange={(e) => setPriceMax(e.target.value)}
              className="w-full px-2 py-1.5 text-sm border border-surface-200 rounded-lg focus:outline-none focus:border-brand-400"
            />
          </div>
          <button
            onClick={applyPrice}
            className="mt-2 w-full px-3 py-1.5 text-sm bg-brand-600 hover:bg-brand-700 text-white rounded-lg transition-colors"
          >
            Apply
          </button>
        </FilterSection>
      )}

      {/* Manufacturer */}
      {manufacturers.length > 0 && (
        <FilterSection title="Brand">
          <ul className="space-y-1.5">
            {manufacturers.map((m) => (
              <li key={m.id}>
                <label className="flex items-center gap-2 cursor-pointer group">
                  <input
                    type="checkbox"
                    checked={activeManufacturers.has(m.id)}
                    onChange={() => toggleManufacturer(m.id)}
                    className="w-4 h-4 rounded border-surface-300 text-brand-600 focus:ring-brand-400"
                  />
                  <span className="text-sm text-surface-700 group-hover:text-surface-900">
                    {m.translated?.name ?? m.name}
                  </span>
                </label>
              </li>
            ))}
          </ul>
        </FilterSection>
      )}

      {/* Property groups (Color, Size, Material, etc.) */}
      {propertyGroups.map(({ groupName, options }) => (
        <FilterSection key={groupName} title={groupName}>
          <ul className="space-y-1.5">
            {options.map((opt) => (
              <li key={opt.id}>
                <label className="flex items-center gap-2 cursor-pointer group">
                  <input
                    type="checkbox"
                    checked={activeProperties.has(opt.id)}
                    onChange={() => toggleProperty(opt.id)}
                    className="w-4 h-4 rounded border-surface-300 text-brand-600 focus:ring-brand-400"
                  />
                  <span className="text-sm text-surface-700 group-hover:text-surface-900">
                    {opt.translated?.name ?? opt.name}
                  </span>
                </label>
              </li>
            ))}
          </ul>
        </FilterSection>
      ))}
    </div>
  );

  return (
    <>
      {/* Mobile toggle button */}
      <div className="lg:hidden mb-4">
        <button
          onClick={() => setMobileOpen((o) => !o)}
          className="flex items-center gap-2 px-4 py-2 border border-surface-200 rounded-lg text-sm font-medium text-surface-700 hover:bg-surface-50 transition-colors"
        >
          <svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2a1 1 0 01-.293.707L13 13.414V19a1 1 0 01-.553.894l-4 2A1 1 0 017 21v-7.586L3.293 6.707A1 1 0 013 6V4z" />
          </svg>
          Filters
          {totalActive > 0 && (
            <span className="ml-1 px-1.5 py-0.5 bg-brand-600 text-white text-xs rounded-full leading-none">
              {totalActive}
            </span>
          )}
        </button>
      </div>

      {/* Mobile drawer */}
      {mobileOpen && (
        <div className="lg:hidden mb-6 p-4 border border-surface-200 rounded-xl bg-white shadow-sm">
          {panel}
        </div>
      )}

      {/* Desktop sidebar */}
      <div className="hidden lg:block w-56 flex-shrink-0">
        <div className="sticky top-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-sm font-semibold text-surface-900 uppercase tracking-wider">Filters</h2>
            {totalActive > 0 && (
              <button onClick={clearAll} className="text-xs text-brand-600 hover:text-brand-700 font-medium">
                Clear all
              </button>
            )}
          </div>
          {panel}
        </div>
      </div>
    </>
  );
}

function FilterSection({ title, children }: { title: string; children: React.ReactNode }) {
  const [open, setOpen] = useState(true);
  return (
    <div className="border-t border-surface-100 pt-4">
      <button
        onClick={() => setOpen((o) => !o)}
        className="flex items-center justify-between w-full mb-3 group"
      >
        <span className="text-sm font-semibold text-surface-800 group-hover:text-surface-900">{title}</span>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          className={`w-4 h-4 text-surface-400 transition-transform ${open ? 'rotate-180' : ''}`}
          fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}
        >
          <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
        </svg>
      </button>
      {open && children}
    </div>
  );
}
