"use client"

import { usePathname, useRouter, useSearchParams } from "next/navigation"

import { useT } from "@/components/locale-provider"
import {
  Combobox,
  ComboboxChip,
  ComboboxChips,
  ComboboxChipsInput,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxItem,
  ComboboxList,
} from "@/components/ui/combobox"

/**
 * Which departments an admin is looking at.
 *
 * Admins only, and the page decides that: a manager has exactly one department
 * and a picker offering it back to them is a control that cannot do anything.
 *
 * Several at once, with chips, the same shape as the filter on `/positions` and
 * reading the same `?dept=` parameter, repeated. Two screens meaning the same
 * thing by the same word in the same url is worth more than either of them
 * being individually neater.
 *
 * A combobox and not a select, because there are 46 departments and the seventh
 * one down a scrolling list is found by typing three letters, not by looking.
 *
 * Pushed rather than replaced, so Back returns to the departments the reader
 * came from and a view is a link somebody can send. The service ignores the
 * parameter for anybody below admin, which is why writing it costs nothing.
 */
export function DepartmentPicker({ departments }: { departments: string[] }) {
  const t = useT()
  const router = useRouter()
  const pathname = usePathname()
  const params = useSearchParams()

  const selected = params.getAll("dept")

  return (
    <Combobox
      items={departments}
      multiple
      value={selected}
      onValueChange={(values: string[]) => {
        const next = new URLSearchParams(params.toString())
        next.delete("dept")
        for (const v of values) next.append("dept", v)
        router.push(next.size ? `${pathname}?${next}` : pathname, {
          scroll: false,
        })
      }}
    >
      <ComboboxChips className="min-h-10 w-full sm:w-80">
        {selected.map((name) => (
          <ComboboxChip key={name} aria-label={name}>
            {name}
          </ComboboxChip>
        ))}
        {/*
          No placeholder once something is picked: the chips already say what is
          in view, and a sentence under them would repeat the screen.
        */}
        <ComboboxChipsInput
          placeholder={selected.length ? "" : t("team.chooseDepartment")}
          aria-label={t("team.chooseDepartment")}
        />
      </ComboboxChips>
      <ComboboxContent>
        {/*
          A typed name that matches nothing gets a sentence rather than an empty
          box. 46 departments spelled in two scripts is exactly where somebody
          mistypes, and a list that goes blank reads as a broken control.
        */}
        <ComboboxEmpty>{t("team.noSuchDepartment")}</ComboboxEmpty>
        <ComboboxList>
          {(name: string) => (
            <ComboboxItem key={name} value={name}>
              {name}
            </ComboboxItem>
          )}
        </ComboboxList>
      </ComboboxContent>
    </Combobox>
  )
}
