"use client";

import { flexRender, Table } from "@tanstack/react-table";
import { TableClassNames } from "../../../types/table.types";

interface TableHeaderProps<TData extends object> {
  table: Table<TData>;
  classNames?: Pick<
    TableClassNames,
    "tableThead" | "tableTheadRow" | "tableTheadCell"
  >;
}

const getSortIndicator = (direction: false | "asc" | "desc") => {
  if (direction === "asc") return "↑";
  if (direction === "desc") return "↓";
  return null;
};

const mergeClasses = (...classes: Array<string | undefined>) =>
  classes.filter(Boolean).join(" ");

export function TableHeader<TData extends object>({
  table,
  classNames,
}: TableHeaderProps<TData>) {
  return (
    <thead className={classNames?.tableThead}>
      {table.getHeaderGroups().map((headerGroup) => (
        <tr key={headerGroup.id} className={classNames?.tableTheadRow}>
          {headerGroup.headers.map((header) => {
            const sortingHandler = header.column.getCanSort()
              ? header.column.getToggleSortingHandler()
              : undefined;

            return (
              <th
                key={header.id}
                scope="col"
                className={mergeClasses(
                  "",
                  classNames?.tableTheadCell,
                  header.column.getCanSort()
                    ? "cursor-pointer select-none"
                    : "",
                  "align-middle",
                  header.column.getCanSort() ? "cursor-pointer select-none" : "",
                )}
                onClick={sortingHandler}
              >
                {header.isPlaceholder
                  ? null
                  : flexRender(
                      header.column.columnDef.header,
                      header.getContext(),
                    )}

                <span className="ml-2 text-slate-400">
                  {getSortIndicator(
                    header.column.getIsSorted() as false | "asc" | "desc",
                  )}
                </span>
              </th>
            );
          })}
        </tr>
      ))}
    </thead>
  );
}
