"use client"

import * as React from "react"

import { useT } from "@/components/locale-provider"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Button } from "@/components/ui/button"

/**
 * Stopping a duty, or starting it again.
 *
 * Behind a confirmation, because what it does is not obvious from the words on
 * the button: it changes what tomorrow brings and leaves everything already
 * produced alone. That sentence is said at the moment of the act, which is the
 * only moment somebody reads it.
 *
 * There is no delete. `active` is what the recurrence engine reads, and the
 * instances a duty has produced are somebody's history.
 *
 * It lives here rather than beside `/positions/[id]` because two screens press
 * it now, and it takes the write as a prop rather than importing one, because
 * the two reach different Server Actions: an admin's is guarded at admin, and
 * the one on `/tasks/new` is guarded by the service alone. A second copy of
 * this dialog would be a second copy of the sentence that says what the press
 * really does.
 */
export function DutySwitch({
  active,
  toggle,
}: {
  active: boolean
  /** Already bound to the duty. Answers whether the write was allowed. */
  toggle: (active: boolean) => Promise<{ ok: boolean }>
}) {
  const t = useT()
  const [open, setOpen] = React.useState(false)
  const [pending, setPending] = React.useState(false)
  const [refused, setRefused] = React.useState<string | null>(null)

  async function go() {
    setPending(true)
    setRefused(null)
    try {
      const result = await toggle(!active)
      if (result.ok) {
        setOpen(false)
        return
      }
      setRefused(t("position.notScoped"))
    } catch {
      setRefused(t("refusal.noAnswer"))
    } finally {
      setPending(false)
    }
  }

  const label = active ? t("position.turnOff") : t("position.turnOn")

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger render={<Button variant="outline" size="sm" />}>
        {label}
      </AlertDialogTrigger>
      <AlertDialogContent className="sm:max-w-md">
        <AlertDialogHeader>
          <AlertDialogTitle>{label}</AlertDialogTitle>
          <AlertDialogDescription>
            {active
              ? t("position.turnOffConsequence")
              : t("position.turnOnConsequence")}
          </AlertDialogDescription>
        </AlertDialogHeader>
        {refused ? <p className="text-sm text-destructive">{refused}</p> : null}
        <AlertDialogFooter>
          <AlertDialogCancel>{t("action.cancel")}</AlertDialogCancel>
          <AlertDialogAction
            disabled={pending}
            onClick={(event) => {
              event.preventDefault()
              void go()
            }}
          >
            {pending ? t("action.working") : label}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
