"use client"

import * as React from "react"

import { JobDescriptionForm } from "@/components/job-description-form"
import { useT } from "@/components/locale-provider"
import { Button } from "@/components/ui/button"
import { saveJobDescription } from "./actions"

/**
 * The sentence that says what the job is for, and the one thing on this page
 * somebody writes in prose.
 *
 * Reading is the default and editing is a press away, because this is read far
 * more often than it is written: it is what somebody arriving on the position
 * reads to learn the job. A textarea sitting open on every visit would say the
 * opposite.
 *
 * The typing itself lives in `components/job-description-form.tsx`, shared with
 * the sheet on the admin overview. What stays here is the read-first behaviour,
 * which is this page's and not the form's: the overview opens the form because
 * opening it is what somebody clicked, and this page hides it because somebody
 * came to read.
 *
 * The saved state clears when the text changes again rather than after a
 * timer. A message that disappears on its own is a message somebody misses, and
 * one that lingers while they type is a message that is no longer true.
 */
export function JobDescription({
  positionId,
  text,
}: {
  positionId: string
  text: string | null
}) {
  const t = useT()
  const [editing, setEditing] = React.useState(false)
  const [outcome, setOutcome] = React.useState<string | null>(null)

  if (editing) {
    return (
      <JobDescriptionForm
        positionId={positionId}
        text={text}
        action={saveJobDescription}
        autoFocus
        onSaved={() => {
          setEditing(false)
          setOutcome(t("position.saved"))
        }}
        onCancel={() => setEditing(false)}
      />
    )
  }

  return (
    <div className="flex flex-col gap-3">
      <p className="max-w-prose leading-relaxed whitespace-pre-wrap">
        {text ?? (
          <span className="text-foreground/70">
            {t("position.jobDescriptionEmpty")}
          </span>
        )}
      </p>
      {outcome ? <p className="text-sm text-foreground/80">{outcome}</p> : null}
      <div>
        <Button
          variant="outline"
          onClick={() => {
            setOutcome(null)
            setEditing(true)
          }}
        >
          {t("position.edit")}
        </Button>
      </div>
    </div>
  )
}
