"use client";

import Image from "next/image";
import { useRouter, useSearchParams } from "next/navigation";
import { useCallback } from "react";

export type SortOption = { value: string; label: string };
export type FilterOptionItem = { value: string; label: string };
export type FilterOption = { key: string; label: string; options: FilterOptionItem[] };

type ListFilterSortProps = {
  /** Sort field options (value = URL param & typically DB column name) */
  sortOptions: SortOption[];
  /** Filter dropdowns: key = URL param name, options = list for dropdown */
  filters?: FilterOption[];
  /** Show the search input in this segment (default true) */
  showSearch?: boolean;
  /** Optional extra content (e.g. Create button) to show on the right */
  children?: React.ReactNode;
};

const ListFilterSort = ({
  sortOptions,
  filters = [],
  showSearch = true,
  children,
}: ListFilterSortProps) => {
  const router = useRouter();
  const searchParams = useSearchParams();

  const updateParams = useCallback(
    (updates: Record<string, string | null>) => {
      const params = new URLSearchParams(searchParams.toString());
      for (const [key, value] of Object.entries(updates)) {
        if (value === null || value === "") params.delete(key);
        else params.set(key, value);
      }
      params.delete("page"); // reset to first page when filters/sort change
      router.push(`${window.location.pathname}?${params}`);
    },
    [router, searchParams]
  );

  const handleSearch = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const value = (e.currentTarget.elements.namedItem("search") as HTMLInputElement)?.value?.trim() ?? "";
    updateParams({ search: value || null });
  };

  const sortBy = searchParams.get("sortBy") ?? (sortOptions[0]?.value ?? "");
  const sortOrder = searchParams.get("sortOrder") ?? "asc";
  const hasActiveFilters = filters.some((f) => searchParams.get(f.key));

  const clearFilters = () => {
    const params = new URLSearchParams(searchParams.toString());
    params.delete("page");
    filters.forEach((f) => params.delete(f.key));
    router.push(`${window.location.pathname}?${params}`);
  };

  return (
    <div className="flex flex-wrap items-center gap-3 py-3 border-b border-gray-200 mb-2">
      {showSearch && (
        <form onSubmit={handleSearch} className="flex items-center gap-2 text-xs rounded-full ring-[1.5px] ring-gray-300 px-2">
          <Image src="/search.png" alt="" width={14} height={14} />
          <input
            name="search"
            type="text"
            placeholder="Search..."
            defaultValue={searchParams.get("search") ?? ""}
            className="w-[180px] sm:w-[200px] p-2 bg-transparent outline-none"
          />
        </form>
      )}

      {sortOptions.length > 0 && (
        <div className="flex items-center gap-2">
          <label className="text-xs text-gray-500 whitespace-nowrap">Sort by</label>
          <select
            value={sortBy}
            onChange={(e) => updateParams({ sortBy: e.target.value })}
            className="text-sm rounded-md border border-gray-300 px-2 py-1.5 bg-white min-w-[120px]"
          >
            {sortOptions.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
          <select
            value={sortOrder}
            onChange={(e) => updateParams({ sortOrder: e.target.value })}
            className="text-sm rounded-md border border-gray-300 px-2 py-1.5 bg-white"
            aria-label="Sort order"
          >
            <option value="asc">Ascending</option>
            <option value="desc">Descending</option>
          </select>
        </div>
      )}

      {filters.map((filter) => (
        <div key={filter.key} className="flex items-center gap-2">
          <label className="text-xs text-gray-500 whitespace-nowrap">{filter.label}</label>
          <select
            value={searchParams.get(filter.key) ?? ""}
            onChange={(e) => updateParams({ [filter.key]: e.target.value || null })}
            className="text-sm rounded-md border border-gray-300 px-2 py-1.5 bg-white min-w-[120px]"
          >
            <option value="">All</option>
            {filter.options.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
        </div>
      ))}

      {hasActiveFilters && (
        <button
          type="button"
          onClick={clearFilters}
          className="text-xs text-gray-600 hover:text-gray-900 underline"
        >
          Clear filters
        </button>
      )}

      {children && <div className="ml-auto flex items-center gap-2">{children}</div>}
    </div>
  );
};

export default ListFilterSort;
