"use client"

import * as React from "react"

import { useT } from "@/components/locale-provider"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import type { WriteResult } from "@/lib/services/duties"

/**
 * The one place the job description is typed.
 *
 * Extracted the day a second screen needed to write one. There is a rule in the
 * older spec — `single_write_surface_positions` — saying `/positions/[id]` is
 * the only write surface for this text, and the point of it is that two
 * editors drift: one grows a validation or a trim the other never hears about,
 * and the same paragraph then saves differently depending on where it was
 * typed. Keeping one component and opening it from two places honours that
 * where it matters, which is in the code rather than in the route.
 *
 * It takes the action rather than importing one, because the two callers
 * revalidate different paths and neither of them is this component's business.
 */
export function JobDescriptionForm({
  positionId,
  text,
  action,
  onSaved,
  onCancel,
  autoFocus = false,
}: {
  positionId: string
  text: string | null
  action: (positionId: string, text: string) => Promise<WriteResult>
  onSaved?: () => void
  onCancel?: () => void
  /** True where the form is what somebody opened, false where it is revealed. */
  autoFocus?: boolean
}) {
  const t = useT()
  const [draft, setDraft] = React.useState(text ?? "")
  const [pending, setPending] = React.useState(false)
  const [outcome, setOutcome] = React.useState<string | null>(null)

  async function save() {
    setPending(true)
    setOutcome(null)
    try {
      const result = await action(positionId, draft)
      if (result.ok) {
        onSaved?.()
        return
      }
      setOutcome(t("position.notScoped"))
    } catch {
      setOutcome(t("refusal.noAnswer"))
    } finally {
      setPending(false)
    }
  }

  return (
    <div className="flex w-full max-w-prose flex-col gap-3">
      <Textarea
        rows={8}
        value={draft}
        autoFocus={autoFocus}
        onChange={(e) => {
          setDraft(e.target.value)
          setOutcome(null)
        }}
        aria-label={t("position.jobDescription")}
      />
      {outcome ? <p className="text-sm text-destructive">{outcome}</p> : null}
      <div className="flex gap-2">
        <Button disabled={pending} onClick={() => void save()}>
          {pending ? t("position.saving") : t("position.save")}
        </Button>
        <Button variant="outline" disabled={pending} onClick={onCancel}>
          {t("action.cancel")}
        </Button>
      </div>
    </div>
  )
}
