import { useEffect, useMemo, useState } from "react";
import { businesses } from "@/mocks/dshn";
import type { Product } from "@/mocks/dshnCommerce";
import { cn, fmt } from "../WebUI";

export const PRICE_MIN = 0;
export const PRICE_MAX = 5000;
export const PRICE_STEP = 50;

export const DRAWER_CITIES = ["الرياض", "جدة", "الدمام"];

export interface ProductFilterState {
  lo: number;
  hi: number;
  bizIds: string[];
  cities: string[];
}

export const DEFAULT_FILTERS: ProductFilterState = {
  lo: PRICE_MIN,
  hi: PRICE_MAX,
  bizIds: [],
  cities: [],
};

/** Count the visible active-filter chips (price counts as one, then each business and city). */
export function countActiveFilters(f: ProductFilterState): number {
  const priceOn = f.lo > PRICE_MIN || f.hi < PRICE_MAX;
  return (priceOn ? 1 : 0) + f.bizIds.length + f.cities.length;
}

/** Apply the price / business / city filters to a list of products. */
export function applyDrawerFilters(list: Product[], f: ProductFilterState): Product[] {
  return list.filter((p) => {
    const price = p.price ?? 0;
    if (f.lo > PRICE_MIN && price < f.lo) return false;
    if (f.hi < PRICE_MAX && price > f.hi) return false;
    if (f.bizIds.length > 0 && !f.bizIds.includes(p.businessId)) return false;
    if (f.cities.length > 0) {
      const biz = businesses.find((x) => x.id === p.businessId);
      if (!biz || !f.cities.includes(biz.city)) return false;
    }
    return true;
  });
}

function Checkbox({ checked }: { checked: boolean }) {
  return (
    <span
      className={cn(
        "w-[22px] h-[22px] rounded-[7px] border flex items-center justify-center shrink-0 transition-colors",
        checked ? "bg-primary-500 border-primary-500" : "bg-background-50 border-background-300",
      )}
    >
      {checked && <i className="ri-check-line text-[15px] leading-none text-background-50" />}
    </span>
  );
}

function DualRange({
  lo,
  hi,
  onChange,
}: {
  lo: number;
  hi: number;
  onChange: (lo: number, hi: number) => void;
}) {
  const pct = (v: number) => ((v - PRICE_MIN) / (PRICE_MAX - PRICE_MIN)) * 100;
  return (
    <div className="relative h-6 select-none" dir="ltr">
      <div className="absolute inset-x-0 top-1/2 -translate-y-1/2 h-1 rounded-full bg-background-300" />
      <div
        className="absolute top-1/2 -translate-y-1/2 h-1 rounded-full bg-foreground-950"
        style={{ left: `${pct(lo)}%`, right: `${100 - pct(hi)}%` }}
      />
      <input
        type="range"
        min={PRICE_MIN}
        max={PRICE_MAX}
        step={PRICE_STEP}
        value={lo}
        aria-label="الحد الأدنى للسعر"
        onChange={(e) => onChange(Math.min(Number(e.target.value), hi - PRICE_STEP), hi)}
        className="dual-range absolute inset-0"
        style={{ zIndex: lo >= hi - PRICE_STEP * 2 ? 40 : 20 }}
      />
      <input
        type="range"
        min={PRICE_MIN}
        max={PRICE_MAX}
        step={PRICE_STEP}
        value={hi}
        aria-label="الحد الأعلى للسعر"
        onChange={(e) => onChange(lo, Math.max(Number(e.target.value), lo + PRICE_STEP))}
        className="dual-range absolute inset-0"
        style={{ zIndex: 30 }}
      />
    </div>
  );
}

/**
 * The reusable filter body shared by the desktop sidebar and the narrow-width
 * drawer. Fully controlled so the parent decides when results update.
 */
export function ProductFilterPanel({
  value,
  onChange,
}: {
  value: ProductFilterState;
  onChange: (f: ProductFilterState) => void;
}) {
  const [bizQuery, setBizQuery] = useState("");

  const bizList = useMemo(
    () => businesses.filter((b) => b.name.includes(bizQuery.trim())),
    [bizQuery],
  );

  const toggleBiz = (id: string) =>
    onChange({
      ...value,
      bizIds: value.bizIds.includes(id) ? value.bizIds.filter((x) => x !== id) : [...value.bizIds, id],
    });

  const toggleCity = (city: string) =>
    onChange({
      ...value,
      cities: value.cities.includes(city) ? value.cities.filter((x) => x !== city) : [...value.cities, city],
    });

  return (
    <div className="space-y-4">
      {/* price */}
      <section className="rounded-[20px] bg-background-100 border border-background-200 p-4">
        <h3 className="text-[15px] font-semibold text-foreground-950 mb-4">السعر</h3>
        <DualRange
          lo={value.lo}
          hi={value.hi}
          onChange={(lo, hi) => onChange({ ...value, lo, hi })}
        />
        <p className="text-center text-[11.5px] font-medium text-foreground-600 mt-2.5">
          {fmt(value.lo)} ر.س — {fmt(value.hi)} ر.س
        </p>
        <div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] gap-2 items-end mt-4">
          <div className="min-w-0">
            <label className="text-[11.5px] text-foreground-600 block mb-1.5">من</label>
            <div className="flex items-center gap-1 h-[52px] px-3 rounded-[14px] bg-background-50 border border-background-200 focus-within:border-foreground-400 transition-colors">
              <input
                inputMode="numeric"
                value={value.lo}
                onChange={(e) =>
                  onChange({
                    ...value,
                    lo: Math.max(
                      PRICE_MIN,
                      Math.min(Number(e.target.value.replace(/\D/g, "")) || 0, value.hi - PRICE_STEP),
                    ),
                  })
                }
                className="w-full min-w-0 flex-1 bg-transparent text-[14px] font-semibold text-foreground-950 outline-none"
              />
              <span className="text-[11px] text-foreground-500 shrink-0">ر.س</span>
            </div>
          </div>
          <div className="h-[52px] flex items-center justify-center text-foreground-400">—</div>
          <div className="min-w-0">
            <label className="text-[11.5px] text-foreground-600 block mb-1.5">إلى</label>
            <div className="flex items-center gap-1 h-[52px] px-3 rounded-[14px] bg-background-50 border border-background-200 focus-within:border-foreground-400 transition-colors">
              <input
                inputMode="numeric"
                value={value.hi}
                onChange={(e) =>
                  onChange({
                    ...value,
                    hi: Math.min(
                      PRICE_MAX,
                      Math.max(Number(e.target.value.replace(/\D/g, "")) || 0, value.lo + PRICE_STEP),
                    ),
                  })
                }
                className="w-full min-w-0 flex-1 bg-transparent text-[14px] font-semibold text-foreground-950 outline-none"
              />
              <span className="text-[11px] text-foreground-500 shrink-0">ر.س</span>
            </div>
          </div>
        </div>
      </section>

      {/* business */}
      <section className="rounded-[20px] bg-background-100 border border-background-200 p-4">
        <h3 className="text-[15px] font-semibold text-foreground-950 mb-3">المنشأة</h3>
        <div className="flex items-center gap-2 h-[48px] px-4 rounded-[14px] bg-background-50 border border-background-200 focus-within:border-foreground-400 transition-colors mb-1">
          <i className="ri-search-line text-[18px] text-foreground-500 leading-none shrink-0" />
          <input
            value={bizQuery}
            onChange={(e) => setBizQuery(e.target.value)}
            placeholder="ابحث عن منشأة"
            className="flex-1 min-w-0 bg-transparent text-[14px] text-foreground-950 placeholder:text-foreground-500 outline-none font-body"
          />
        </div>
        <div className="max-h-[260px] overflow-y-auto divide-y divide-background-200">
          {bizList.length === 0 ? (
            <p className="text-[13px] text-foreground-500 text-center py-6">لا توجد نتائج حاليًا</p>
          ) : (
            bizList.map((b) => {
              const checked = value.bizIds.includes(b.id);
              return (
                <button
                  key={b.id}
                  type="button"
                  onClick={() => toggleBiz(b.id)}
                  className="w-full min-h-[56px] flex items-center gap-3 py-2 cursor-pointer text-right"
                >
                  <span className="w-9 h-9 rounded-full overflow-hidden bg-background-200 shrink-0">
                    <img src={b.logo} alt={b.name} className="w-full h-full object-cover object-top" />
                  </span>
                  <span
                    className={cn(
                      "flex-1 text-[13.5px] text-start",
                      checked ? "font-semibold text-foreground-950" : "text-foreground-800",
                    )}
                  >
                    {b.name}
                  </span>
                  <Checkbox checked={checked} />
                </button>
              );
            })
          )}
        </div>
      </section>

      {/* city */}
      <section className="rounded-[20px] bg-background-100 border border-background-200 p-4">
        <h3 className="text-[15px] font-semibold text-foreground-950 mb-3">المدينة</h3>
        <div className="flex flex-wrap gap-2">
          {DRAWER_CITIES.map((city) => {
            const active = value.cities.includes(city);
            return (
              <button
                key={city}
                type="button"
                onClick={() => toggleCity(city)}
                className={cn(
                  "rounded-full px-3.5 py-2 text-[13px] font-medium whitespace-nowrap transition-colors cursor-pointer",
                  active
                    ? "bg-primary-500 text-background-50"
                    : "bg-background-50 border border-background-200 text-foreground-700 hover:border-background-300",
                )}
              >
                {city}
              </button>
            );
          })}
        </div>
      </section>
    </div>
  );
}

export default function ProductFilterDrawer({
  open,
  baseList,
  value,
  onClose,
  onApply,
}: {
  open: boolean;
  baseList: Product[];
  value: ProductFilterState;
  onClose: () => void;
  onApply: (f: ProductFilterState) => void;
}) {
  const [draft, setDraft] = useState<ProductFilterState>(value);

  // Sync the draft with the applied filters each time the drawer opens.
  useEffect(() => {
    if (open) setDraft(value);
  }, [open, value]);

  const resultCount = useMemo(
    () => applyDrawerFilters(baseList, draft).length,
    [baseList, draft],
  );

  return (
    <div className={cn("fixed inset-0 z-[70]", !open && "pointer-events-none")}>
      {/* overlay */}
      <div
        onClick={onClose}
        aria-hidden="true"
        className={cn(
          "absolute inset-0 bg-foreground-950/40 transition-opacity duration-300",
          open ? "opacity-100" : "opacity-0",
        )}
      />

      {/* drawer */}
      <aside
        role="dialog"
        aria-label="فلترة المنتجات"
        aria-hidden={!open}
        className={cn(
          "absolute inset-y-0 left-0 w-[440px] max-w-full bg-background-50 border-r border-background-200 flex flex-col transition-transform duration-300 ease-out",
          open ? "translate-x-0" : "-translate-x-full",
        )}
      >
        <header className="shrink-0 flex items-center justify-between gap-4 px-5 h-[64px] border-b border-background-200">
          <div className="flex items-center gap-1 min-w-0">
            <button
              type="button"
              onClick={onClose}
              aria-label="إغلاق"
              className="w-10 h-10 -ms-2 rounded-full flex items-center justify-center text-foreground-950 hover:bg-background-200 cursor-pointer shrink-0"
            >
              <i className="ri-close-line text-[24px] leading-none" />
            </button>
            <h2 className="text-[17px] font-bold text-foreground-950 font-heading truncate">
              فلترة المنتجات
            </h2>
          </div>
          <button
            type="button"
            onClick={() => setDraft(DEFAULT_FILTERS)}
            className="text-[13px] font-semibold text-foreground-600 hover:text-foreground-950 cursor-pointer whitespace-nowrap shrink-0"
          >
            إعادة تعيين
          </button>
        </header>

        <div className="flex-1 overflow-y-auto px-4 py-4">
          <ProductFilterPanel value={draft} onChange={setDraft} />
        </div>

        <footer className="shrink-0 px-4 py-3 border-t border-background-200 bg-background-50">
          <button
            type="button"
            onClick={() => onApply(draft)}
            className="w-full h-[52px] rounded-[16px] bg-primary-500 text-background-50 text-[15px] font-semibold hover:bg-primary-600 transition-colors cursor-pointer whitespace-nowrap"
          >
            عرض النتائج ({resultCount})
          </button>
        </footer>
      </aside>
    </div>
  );
}