import React, { useState } from "react"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import './table-header.styles.scss'

const TableHeader = ({ headers, onSorting, controlsField = false}) => {
    const [sortingField, setSortingField] = useState("")
    const [sortingOrder, setSortingOrder] = useState("asc")

    const onSortingChange = (field) => {
        const order =
            field === sortingField && sortingOrder === "asc" ? "desc" : "asc"

        setSortingField(field)
        setSortingOrder(order)
        onSorting(field, order)
    }

    return (
        <thead className="datatable-thead">
            <tr>
                {headers.map(({ name, field, sortable }) => (
                    <th
                        key={name}
                        onClick={() =>
                            sortable ? onSortingChange(field) : null
                        }
                    >
                        {name}

                        {sortingField && sortingField === field && (
                            <FontAwesomeIcon
                                icon={`${sortingOrder === "asc" ? "arrow-down" : "arrow-up"}`                                                                          }
                            />
                        )}
                    </th>
                ))}
                {
                    controlsField ? <th className="action-control">Action</th> : null
                }
            </tr>
        </thead>
    )
}

export default TableHeader
