import { Input, Flex, chakra } from "@chakra-ui/react";
import { Table as ReactTable, Column } from "@tanstack/react-table";
import { TData } from "../types";

export interface DataTableFilterProps<T extends TData> {
  column: Column<T>;
  table: ReactTable<T>;
}

export const DataTableFilter = <T extends TData>({
  column,
  table,
}: DataTableFilterProps<T>) => {
  const firstValue = table
    .getPreFilteredRowModel()
    .flatRows[0]?.getValue(column.id);

  const columnFilterValue = column.getFilterValue();

  return typeof firstValue === "number" ? (
    <Flex>
      <SearchInput
        size="xs"
        type="number"
        value={(columnFilterValue as [number, number])?.[0] ?? ""}
        onChange={(e) =>
          column.setFilterValue((old: [number, number]) => [
            e.target.value,
            old?.[1],
          ])
        }
        placeholder="Min"
      />
      <SearchInput
        type="number"
        value={(columnFilterValue as [number, number])?.[1] ?? ""}
        onChange={(e) =>
          column.setFilterValue((old: [number, number]) => [
            old?.[0],
            e.target.value,
          ])
        }
        placeholder="Max"
      />
    </Flex>
  ) : (
    <SearchInput
      size="xs"
      type="text"
      value={(columnFilterValue ?? "") as string}
      onChange={(e) => column.setFilterValue(e.target.value)}
      placeholder="Search..."
    />
  );
};

const SearchInput = chakra(Input, {
  baseStyle: {
    rounded: "lg",
    maxW: "100px",
  },
});
