"use client";

import { Button } from "@heroui/react";
import { useCallback, useId, useState } from "react";

export type SortOption = { value: string; label: string };

export function ShopToolbar({
  sortOptions,
  currentSort,
  onSortChange,
  onOpenFilter,
}: {
  sortOptions: SortOption[];
  currentSort: string;
  onSortChange: (value: string) => void;
  onOpenFilter?: () => void;
  /** When set, show "Showing X products" for filtered result count. */
  resultCount?: number;
}) {
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const id = useId();
  const currentLabel = sortOptions.find((o) => o.value === currentSort)?.label ?? currentSort;

  const handleSelect = useCallback(
    (value: string) => {
      onSortChange(value);
      setDropdownOpen(false);
    },
    [onSortChange],
  );

  return (
    <div className="flex flex-wrap items-center justify-between gap-2">
      {/* Filter button: visible only below lg (lg:hidden) */}
      {onOpenFilter && (
        <Button
          variant="outline"
          size="sm"
          onPress={() => {
            onOpenFilter();
          }}
          className="lg:hidden shrink-0"
          aria-label="Open filters"
        >
          Filter
        </Button>
      )}
      {/* Sort by dropdown */}
      <div className="relative flex items-center gap-2">
        <span id={`${id}-label`} className="text-sm text-[var(--muted)]">
          Sort by
        </span>
        <div className="relative">
          <Button
            variant="outline"
            size="sm"
            aria-haspopup="listbox"
            aria-expanded={dropdownOpen}
            aria-labelledby={`${id}-label`}
            onPress={() => setDropdownOpen((o) => !o)}
            className="min-w-[140px] justify-between"
          >
            {currentLabel}
            <ChevronDownIcon className="size-4 shrink-0" />
          </Button>
          {dropdownOpen && (
            <>
              <div
                className="fixed inset-0 z-10"
                aria-hidden
                onClick={() => setDropdownOpen(false)}
              />
              <ul
                role="listbox"
                className="absolute right-0 top-full z-20 mt-1 min-w-[180px] rounded-lg border border-[var(--border)] bg-[var(--surface)] py-1 shadow-lg"
                onClick={(e) => {
                  const value = (e.target as HTMLElement).closest("[data-value]")?.getAttribute("data-value");
                  if (value) handleSelect(value);
                }}
              >
                {sortOptions.map((opt) => (
                  <li
                    key={opt.value}
                    role="option"
                    data-value={opt.value}
                    aria-selected={opt.value === currentSort}
                    className={`cursor-pointer px-3 py-2 text-sm hover:bg-[var(--brand-light)]/30 ${opt.value === currentSort ? "bg-[var(--brand-light)]/50" : ""}`}
                  >
                    {opt.label}
                  </li>
                ))}
              </ul>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function ChevronDownIcon({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
      <path d="M6 9l6 6 6-6" />
    </svg>
  );
}
