"use client";

import type { Table } from "@tanstack/react-table";

import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";

import { X } from "lucide-react";
import { DataTableViewOptions } from "./dataTableViewOptions";
import { DataTableFacetedFilter } from "./dataTableFacetedFilter";
import { ReactNode } from "react";

export interface FilterConfig {
  columnKey: string;
  title: string;
  options: { label: string; value: string }[];
  isVisible?: boolean;
}

export interface DataTableToolbarProps<TData> {
  table: Table<TData>;
  tableName: string;
  toolBarPosition?: "right" | "left" | "center";
  extraToolbar?: ReactNode;
  filters?: FilterConfig[];
  refreshTable?: () => void;
}

export function DataTableToolbar<TData>({
  table,
  tableName,
  toolBarPosition = "left",
  extraToolbar,
  filters = [],
  refreshTable,
}: DataTableToolbarProps<TData>) {
  const isFiltered = table.getState().columnFilters.length > 0;

  return (
    <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
      {/* Filters & Reset */}
      <div className="flex flex-wrap items-center gap-2">
        <Input
          placeholder={`Filter ${tableName}...`}
          onChange={(event) => table.setGlobalFilter(event.target.value)}
          className="h-8 w-full sm:w-[150px] lg:w-[250px]"
        />

        {filters.map(
          ({ columnKey, title, options, isVisible = true }) =>
            isVisible &&
            table.getColumn(columnKey) && (
              <DataTableFacetedFilter
                key={columnKey}
                column={table.getColumn(columnKey)}
                title={title}
                options={options}
              />
            )
        )}

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

      {/* Extra Toolbar + View Options */}
      <div
        className={`flex flex-wrap items-center gap-2 ${
          toolBarPosition === "center"
            ? "justify-center"
            : toolBarPosition === "left"
            ? "justify-start"
            : "justify-end"
        }`}
      >
        {extraToolbar}
        <DataTableViewOptions table={table} refreshTable={refreshTable} />
      </div>
    </div>
  );
}
