import type { Table } from "@tanstack/react-table";
import Input from "~/components/custom_ui/input";
import { DataTableViewOptions } from "~/components/custom_ui/dataTable-ViewToggle";
import { Button } from "~/components/ui/button";
import { DataTableFacetedFilter } from "~/components/custom_ui/dataTable-FacetedFilter";
import { RotateCcw } from "lucide-react";
import type { ComponentType } from "react";

export type PinnedFiltro = {
  title: string;
  columnName: string;
  options: {
    label: string;
    value: string;
    icon?: ComponentType<{ className?: string }>;
  }[];
};
export type SearchFiltro = {
  columnName: string;
  placeholder: string;
};
export function DataTableToolbar<TData>(props: {
  table: Table<TData>;
  pinnedColumns?: PinnedFiltro[];
  searchColumn?: SearchFiltro;
  columns_titles: Record<string, string>;
  globalFilter: string;
}) {
  const { table, pinnedColumns, searchColumn, columns_titles, globalFilter } =
    props;
  const isFiltered = table.getState().columnFilters.length > 0;

  return (
    <div className="flex items-center justify-between">
      <div className="flex flex-1 flex-wrap items-center gap-2">
        {searchColumn &&
          (searchColumn.columnName ? (
            <Input
              placeholder={searchColumn.placeholder}
              value={
                (table
                  .getColumn(searchColumn.columnName)
                  ?.getFilterValue() as string) ?? ""
              }
              onChange={(event) =>
                table
                  .getColumn(searchColumn.columnName)
                  ?.setFilterValue(event.target.value)
              }
              className="mt-0 h-8 w-[150px]"
            />
          ) : (
            <Input
              placeholder={searchColumn.placeholder}
              value={globalFilter ?? ""}
              onChange={(event) =>
                table.setGlobalFilter(String(event.target.value))
              }
              className="mt-0 h-8 w-[150px]"
            />
          ))}
        {pinnedColumns &&
          pinnedColumns.map(
            (column) =>
              table.getColumn(column.columnName) && (
                <DataTableFacetedFilter
                  key={column.columnName}
                  column={table.getColumn(column.columnName)}
                  title={column.title}
                  options={column.options}
                />
              ),
          )}

        {isFiltered && (
          <Button
            variant="ghost"
            onClick={() => table.resetColumnFilters()}
            className="h-8 px-2 lg:px-3"
          >
            Reset
            <RotateCcw className="ml-2 size-4" />
          </Button>
        )}
      </div>
      <DataTableViewOptions table={table} columns_titles={columns_titles} />
    </div>
  );
}
