"use client"

import * as React from "react"

import { useT } from "@/components/locale-provider"
import { DataTable } from "@/components/ui/data-table"
import type { JobDescriptionRow } from "@/lib/job-description-view"
import { jobDescriptionColumns } from "./columns"
import { JobDescriptionSheet } from "./job-description-sheet"

/**
 * The rows arrive already ordered by the page, emptiest first. Sorting and
 * paging stay here, as on the roster: they concern only the person looking.
 *
 * Clicking a column header replaces that order with an alphabetical one, which
 * is the point — the default answers "what is left to write", and the header
 * answers "where is this one person".
 *
 * Which position is being edited lives here rather than in the cell, so there
 * is one panel for the table instead of one per row. `useMemo` on the columns
 * because rebuilding them on every render would rebuild every cell's render
 * function with them.
 */
export function JobDescriptionsTable({ rows }: { rows: JobDescriptionRow[] }) {
  const t = useT()
  const [editing, setEditing] = React.useState<string | null>(null)

  const columns = React.useMemo(() => jobDescriptionColumns(t, setEditing), [t])

  return (
    <>
      <DataTable
        columns={columns}
        data={rows}
        empty={t("jobDescriptions.none")}
      />
      <JobDescriptionSheet
        positionId={editing}
        onClose={() => setEditing(null)}
      />
    </>
  )
}
