import { Button, Group, TextInput } from "@mantine/core";
import { DatePickerInput } from "@mantine/dates";
import { Search, X } from "lucide-react";
import type { ReactNode } from "react";

export interface ListControlsProps {
  search: string;
  onSearchChange: (value: string) => void;
  searchPlaceholder?: string;
  /** `YYYY-MM-DD`, matching Mantine 9's date inputs. */
  dateFrom: string | null;
  onDateFromChange: (value: string | null) => void;
  dateTo: string | null;
  onDateToChange: (value: string | null) => void;
  /** Label above the range, naming the date being filtered (e.g. "Arrival date"). */
  dateLabel?: string;
  hasFilters?: boolean;
  onReset?: () => void;
  /** Page-specific selects (status, warehouse…) rendered after the date range. */
  children?: ReactNode;
  showSearch?: boolean;
  showDateRange?: boolean;
}

/**
 * Search box + inclusive date range + clear, shared by every freight list so the
 * controls sit in the same place and behave the same way on all of them.
 * Pair with `useListControls`, which owns the state and does the filtering.
 */
const ListControls = ({
  search,
  onSearchChange,
  searchPlaceholder = "Search…",
  dateFrom,
  onDateFromChange,
  dateTo,
  onDateToChange,
  dateLabel,
  hasFilters,
  onReset,
  children,
  showSearch = true,
  showDateRange = true,
}: ListControlsProps) => (
  <Group gap="sm" align="flex-end" wrap="wrap">
    {showSearch && (
      <TextInput
        placeholder={searchPlaceholder}
        value={search}
        onChange={(e) => onSearchChange(e.currentTarget.value)}
        leftSection={<Search size={16} />}
        style={{ flex: "1 1 240px", minWidth: 200 }}
      />
    )}

    {showDateRange && (
      <>
        <DatePickerInput
          label={dateLabel ? `${dateLabel} from` : "From"}
          placeholder="Any"
          value={dateFrom}
          onChange={onDateFromChange}
          // Cannot start after it ends — the picker refuses the invalid range
          // instead of silently returning nothing.
          maxDate={dateTo ?? undefined}
          clearable
          w={150}
        />
        <DatePickerInput
          label={dateLabel ? `${dateLabel} to` : "To"}
          placeholder="Any"
          value={dateTo}
          onChange={onDateToChange}
          minDate={dateFrom ?? undefined}
          clearable
          w={150}
        />
      </>
    )}

    {children}

    {hasFilters && onReset && (
      <Button
        variant="subtle"
        color="gray"
        leftSection={<X size={14} />}
        onClick={onReset}
      >
        Clear
      </Button>
    )}
  </Group>
);

export default ListControls;
