"use client";

import { Filter, Plus, RefreshCw } from "lucide-react";
import { useRouter } from "next/navigation";
import { ActionButton } from "@/components/ui/ActionButton";
import { Badge } from "@/components/ui/badge";
import DropdownButton, { type DropdownOption } from "@/components/ui/DropdownButton";

export interface ResourceListActionsProps {
  isLoading: boolean;
  onRefresh: () => void;
  addLabel?: string;
  onAdd?: () => void;
  addHref?: string;
  addOptions?: DropdownOption[];
  refreshVariant?: "primary" | "secondary";
  filters?: {
    show: boolean;
    count: number;
    onToggle: () => void;
  };
}

/**
 * Shared list/report toolbar: optional Add, optional Filters, plus Refresh.
 */
export function ResourceListActions({
  isLoading,
  onRefresh,
  addLabel,
  onAdd,
  addHref,
  addOptions,
  refreshVariant = "secondary",
  filters,
}: ResourceListActionsProps) {
  const router = useRouter();

  const handleAdd = () => {
    if (onAdd) {
      onAdd();
      return;
    }
    if (addHref) {
      router.push(addHref);
    }
  };

  const addControl =
    addOptions && addOptions.length > 0 && addLabel ? (
      <DropdownButton
        options={addOptions}
        buttonLabel={isLoading ? "Loading..." : addLabel}
        icon={<Plus size={16} />}
        className="text-xs"
      />
    ) : addLabel && (onAdd || addHref) ? (
      <ActionButton
        variant="primary"
        icon={<Plus />}
        onClick={handleAdd}
        loading={isLoading}
        loadingLabel="Loading…"
      >
        {addLabel}
      </ActionButton>
    ) : null;

  const filterControl = filters ? (
    <ActionButton
      icon={<Filter />}
      variant={filters.show ? "primary" : "secondary"}
      onClick={filters.onToggle}
      aria-pressed={filters.show}
      aria-expanded={filters.show}
    >
      Filters
      {filters.count > 0 && (
        <Badge
          variant={filters.show ? "secondary" : "brand"}
          className="ml-1 h-5 min-w-5 px-1 tabular-nums"
        >
          {filters.count}
        </Badge>
      )}
    </ActionButton>
  ) : null;

  const refreshControl = (
    <ActionButton
      variant={refreshVariant}
      icon={<RefreshCw />}
      onClick={onRefresh}
      loading={isLoading}
      loadingLabel="Refreshing…"
    >
      Refresh
    </ActionButton>
  );

  if (filters) {
    return (
      <div className="flex items-center gap-2">
        {addControl}
        {filterControl}
        {refreshControl}
      </div>
    );
  }

  return (
    <>
      {addControl}
      {refreshControl}
    </>
  );
}
