"use client";
import { cn, debounce } from "@/lib/utils";
import React from "react";
import { Input } from "../ui/input";
import { SearchIcon, XIcon } from "lucide-react";
import CategorySelect from "../category/category-select";
import SortFilterSelect from "../sort-filter-select";
import { Button } from "../ui/button";

export type ArticleFilter = {
  query?: string;
  category?: string;
  sort?: string;
};

const defaultFilter: ArticleFilter = {
  query: "",
  category: undefined,
  sort: undefined,
};

function ArticleFilterBar({
  className,
  onFilterUpdate,
}: {
  className?: string;
  onFilterUpdate: (filter: ArticleFilter) => void;
}) {
  const [filter, setFilter] = React.useState<ArticleFilter>(defaultFilter);

  const onFilterChange = React.useCallback(
    (newFilter: Partial<ArticleFilter>, notify: boolean = true) => {
      const f = { ...filter, ...newFilter };
      setFilter(f);
      if (notify) onFilterUpdate(f);
    },
    [filter, onFilterUpdate], // Ensure dependencies are listed
  );

  const debouncedSearch = React.useMemo(
    () =>
      debounce((query: string) => {
        onFilterChange({ query });
      }, 300),
    [],
  );
  const hasFilter =
    filter.query?.length || filter.sort?.length || filter.category?.length;

  return (
    <>
      <div
        className={cn(
          "flex w-full flex-col-reverse items-center justify-center gap-2 rounded-md border bg-background p-2 lg:flex-row lg:gap-4",
          className,
        )}
      >
        <div className="relative w-full">
          <SearchIcon className="absolute left-2 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            className="border-0 p-0 pl-8 shadow-none focus-visible:ring-0"
            value={filter.query}
            onChange={(e) => {
              onFilterChange({ query: e.currentTarget.value }, false);
              debouncedSearch(e.currentTarget.value);
            }}
            placeholder="Artikel Suche..."
          />
        </div>
        <div className="flex w-full flex-col gap-2 sm:flex-row">
          <Button
            disabled={!hasFilter}
            variant={"ghost"}
            className={cn(
              "text-xs text-muted-foreground",
              hasFilter
                ? "flex lg:opacity-100"
                : "hidden lg:flex lg:opacity-0 lg:disabled:opacity-0",
            )}
            onClick={() => onFilterChange(defaultFilter)}
          >
            <span>Filter entfernen</span>
            <XIcon className="size-4" />
          </Button>

          <CategorySelect
            className="w-full"
            initialValue={filter.category}
            onSelect={(category) => {
              onFilterChange({
                category: category?.length ? category : undefined,
              });
            }}
            buttonProps={{
              size: "sm",
            }}
          />
          <SortFilterSelect
            initialValue={filter.sort}
            onSelect={(currentValue) => {
              onFilterChange({
                sort: currentValue?.length ? currentValue : undefined,
              });
            }}
            className="w-full lg:max-w-64"
            buttonProps={{
              size: "sm",
            }}
          />
        </div>
      </div>
    </>
  );
}

export default ArticleFilterBar;
