"use client";

import React from "react";
import { Cell } from "./Cell";
import TableContext from "./TableContext";
import { TableHeader } from "./types";

interface SortOptions {
  none: string;
  ascending: string;
  descending: string;
}

const Header: React.FC = () => {
  const { headers, expandableRows } = React.useContext(TableContext);
  const sortOptions: SortOptions = {
    none: `zoradiť vzostupne podľa`,
    ascending: `zoradiť zostupne podľa`,
    descending: `vypnúť zoradenie poďľa`,
  };

  return (
    <thead>
      <tr>
        {headers.map((header: TableHeader, i: number) => {
          const {
            isSortable,
            sort = "none",
            label,
            cellProps,
            headCellProps,
          } = header;
          return (
            <Cell
              tag="th"
              key={i.toString()}
              {...cellProps}
              {...headCellProps}
              {...(isSortable && {
                "aria-sort": sort,
              })}
              scope="col"
            >
              {label}
              {isSortable && (
                <>
                  {" "}
                  <button type="button" className="table__sort-button">
                    <span className="sr-only">
                      {sortOptions[sort]} {label}
                    </span>
                  </button>
                </>
              )}
            </Cell>
          );
        })}
        {expandableRows?.hasExpandableRows && (
          <Cell tag="th" scope="col" className="table__cell--shrink">
            <span className="sr-only">
              {expandableRows?.expandableRowsCaptions?.header}
            </span>
          </Cell>
        )}
      </tr>
    </thead>
  );
};

Header.displayName = "TableHeader";

export { Header };
