'use client';

import { useCallback, useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, Field, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { SendEmailDrawer } from '@/features/contacts/ui/actions/SendEmailDrawer';
import { actionErrorText, TEXTAREA_STYLE } from '@/features/contacts/ui/actions/shared';
import { getManualEmailDraft } from '@/features/sequences/api.client';
import type { ManualEmailDraft } from '@/features/sequences/types';
import { htmlToText, textToHtml } from '@/features/inbox/format';
import { listObjectPipelines } from '@/features/objects/api.client';
import type { Pipeline } from '@/features/pipelines/api.client';
import type { PicklistOption } from '@/features/picklists/api.client';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { useTaskQueues } from '@/features/task-queues/useTaskQueues';
import {
  completeTask,
  deleteTask,
  getTask,
  reopenTask,
  updateTask,
} from '@/features/tasks/api.client';
import {
  dueFromInputs,
  dueInputs,
  formatDue,
  priorityLabel,
  reminderFromInputs,
  reminderInputs,
  TASK_REMINDER_OPTIONS,
  TASK_REPEAT_UNITS,
  type TaskReminderKey,
  repeatEndFromInputs,
  repeatEndInputs,
  TASK_REPEAT_END_OPTIONS,
  TASK_REPEAT_MAX_OCCURRENCES,
  type TaskRepeatEndKind,
} from '@/features/tasks/format';
import {
  TASK_PRIORITIES,
  TASK_STATUSES,
  TASK_STATUS_LABELS,
  type Task,
  type TaskLink,
  type TaskPriority,
  type TaskStatus,
  type TaskRepeatUnit,
  type UpdateTaskBody,
} from '@/features/tasks/types';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { ConfirmDialog } from './ConfirmDialog';
import { sameLink, TaskLinksPicker } from './TaskLinksPicker';
import { canChangeTask, taskLockedReason } from '../taskAccess';
import { SnippetTextarea } from '@/features/snippets/ui/SnippetTextarea';
import { snippetTargetFromLinks } from '@/features/snippets/model';

interface FormState {
  title: string;
  taskType: string;
  priority: string;
  day: string;
  time: string;
  assigneeId: string;
  notes: string;
  /** HUB-226: the task pipeline stage's id; '' for none. */
  stageId: string;
  /** TK2: the Task stage (status). */
  status: TaskStatus;
  /** QA #349: "Send reminder" and its custom moment (datetime-local). */
  reminder: TaskReminderKey;
  reminderCustom: string;
  /** QA #349: "Set to repeat": every `repeatEvery` `repeatUnit`s. */
  repeat: boolean;
  repeatEvery: string;
  repeatUnit: TaskRepeatUnit;
  /** TK7 (P16): how the series ends (never, on a day, after N tasks). */
  repeatEnd: TaskRepeatEndKind;
  repeatEndDate: string;
  repeatEndAfter: string;
  /** QA #349: the task queue's id; '' for none. */
  queueId: string;
}

function formOf(task: Task, timeZone: string): FormState {
  const due = dueInputs(task, timeZone);
  const reminder = reminderInputs(task, timeZone);
  return {
    title: task.title,
    taskType: task.taskType,
    priority: task.priority ?? '',
    day: due.day,
    time: due.time,
    assigneeId: task.assignee?.id ?? '',
    notes: task.notes ? htmlToText(task.notes) : '',
    stageId: task.stageId ?? '',
    status: task.status,
    reminder: reminder.key,
    reminderCustom: reminder.custom,
    repeat: task.repeat !== null,
    repeatEvery: String(task.repeat?.interval ?? 1),
    repeatUnit: task.repeat?.unit ?? 'week',
    ...(() => {
      const end = repeatEndInputs(task.repeat);
      return { repeatEnd: end.kind, repeatEndDate: end.date, repeatEndAfter: end.count };
    })(),
    queueId: task.queueId ?? '',
  };
}

const repeatEveryOf = (form: FormState) =>
  Math.max(1, Math.min(99, Math.floor(Number(form.repeatEvery)) || 1));
/** The repeat rule as one comparable value ('' = none). */
const repeatKey = (form: FormState) =>
  form.repeat
    ? `${repeatEveryOf(form)}:${form.repeatUnit}:${form.repeatEnd}:${
        form.repeatEnd === 'date'
          ? form.repeatEndDate
          : form.repeatEnd === 'after'
            ? form.repeatEndAfter
            : ''
      }`
    : '';
const reminderKey = (form: FormState) =>
  form.reminder === 'custom' ? `custom:${form.reminderCustom}` : form.reminder;

const linkInput = (l: TaskLink) => ({ objectType: l.objectType, id: l.id });

/**
 * One task (GET /tasks/:id), opened from a row or `/tasks?task=<id>`: edit its fields and
 * associations (PATCH with only the changed fields, addLinks / removeLinks and the loaded
 * `updatedAt`, so a change made meanwhile is a 409), complete / reopen, delete.
 */
export function TaskDetailDrawer({
  taskId,
  onClose,
  onChanged,
  onDeleted,
  taskTypes,
  members,
  timeZone,
  canWrite,
}: {
  taskId: string | null;
  onClose: () => void;
  /** After any saved change (refresh lists and counts). */
  onChanged: () => void;
  onDeleted: (task: Task) => void;
  taskTypes: PicklistOption[];
  /** People the task can be assigned to. */
  members: { userId: string; name: string }[];
  timeZone: string;
  canWrite: boolean;
}) {
  const me = useCurrentUser();
  const toast = useToast();
  const region = useUserPrefs().regionFormat;
  const [task, setTask] = useState<Task | null>(null);
  // BL3: a task the caller only sees (through a record they can view) opens read only; since TK1
  // (26 Nov 2026) Delete follows the same edit rule.
  const editable = canChangeTask(task, canWrite);
  const lockedReason = taskLockedReason(task, canWrite);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [form, setForm] = useState<FormState | null>(null);
  const [links, setLinks] = useState<TaskLink[]>([]);
  const [busy, setBusy] = useState<'save' | 'status' | 'delete' | null>(null);
  const [conflict, setConflict] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState(false);
  /** A sequence's manual email task: its email, to send from here (QA 16 Oct #143). */
  const [draft, setDraft] = useState<ManualEmailDraft | null>(null);
  const [composing, setComposing] = useState(false);
  /** HUB-226: the business's task pipelines (archived ones too, for a task still in one). */
  const [pipelines, setPipelines] = useState<Pipeline[]>([]);
  /** QA #349: the task queues the user can use. */
  const { queues } = useTaskQueues(taskId !== null);

  useEffect(() => {
    if (taskId === null) return;
    let alive = true;
    listObjectPipelines('task', true).then(
      (rows) => alive && setPipelines(rows),
      () => alive && setPipelines([]), // no pipelines to offer; the task still opens
    );
    return () => {
      alive = false;
    };
  }, [taskId]);

  const show = useCallback(
    (t: Task) => {
      setTask(t);
      setForm(formOf(t, timeZone));
      setLinks(t.links);
      setConflict(false);
    },
    [timeZone],
  );

  const load = useCallback(
    async (id: string) => {
      setLoadError(null);
      try {
        show(await getTask(id));
      } catch (err) {
        setLoadError(
          isApiError(err) && err.isNotFound
            ? 'This task was deleted or does not exist.'
            : errorText(err),
        );
      }
    },
    [show],
  );

  useEffect(() => {
    setTask(null);
    setForm(null);
    setConfirmDelete(false);
    if (taskId) void load(taskId);
  }, [taskId, load]);

  const open = taskId !== null;
  const done = task?.status === 'completed';

  const draftFor = task && task.taskType === 'email' && !done ? task.id : null;
  useEffect(() => {
    setDraft(null);
    setComposing(false);
    if (!draftFor) return;
    let alive = true;
    getManualEmailDraft(draftFor).then(
      (d) => {
        if (alive) setDraft(d);
      },
      () => {}, // not made by a sequence: an ordinary email task
    );
    return () => {
      alive = false;
    };
  }, [draftFor]);

  /** Sent from the composer: the task is done, and the sequence moves on. */
  const onEmailSent = async () => {
    setComposing(false);
    if (!task) return;
    try {
      show(await completeTask(task.id));
      toast('Email sent and task completed', 'success');
      onChanged();
    } catch (err) {
      failed(err);
    }
  };
  const showAssignee = members.length > 0;
  const set = (key: Exclude<keyof FormState, 'repeat'>) => (value: string) =>
    setForm((f) => (f ? { ...f, [key]: value } : f));

  const failed = (err: unknown) => {
    if (isApiError(err) && err.isConflict) setConflict(true);
    toast(actionErrorText(err), 'danger', { durationMs: 8000 });
  };

  const save = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!task || !form || busy) return;
    const before = formOf(task, timeZone);
    const body: UpdateTaskBody = {};
    const title = form.title.trim();
    if (!title) {
      toast('The title is required', 'danger');
      return;
    }
    if (title !== task.title) body.title = title;
    if (form.taskType !== before.taskType) body.taskType = form.taskType;
    if (form.priority !== before.priority) {
      body.priority = (form.priority || null) as TaskPriority | null;
    }
    if (form.day !== before.day || form.time !== before.time) {
      const due = dueFromInputs(form.day, form.time, timeZone);
      if ('error' in due) {
        toast(due.error, 'danger');
        return;
      }
      if (due.dueAt) body.dueAt = due.dueAt;
      else if (due.dueDate) body.dueDate = due.dueDate;
      else {
        body.dueAt = null;
        body.dueDate = null;
      }
    }
    // QA #349: the reminder (the API moves one set before the due time with it) and repeat rule.
    if (reminderKey(form) !== reminderKey(before)) {
      const remind = reminderFromInputs(
        { key: form.reminder, custom: form.reminderCustom },
        Boolean(form.day),
        timeZone,
      );
      if ('error' in remind) {
        toast(remind.error, 'danger');
        return;
      }
      if (remind.reminderAt) body.reminderAt = remind.reminderAt;
      else body.reminderMinutesBefore = remind.reminderMinutesBefore;
    }
    if (repeatKey(form) !== repeatKey(before)) {
      if (!form.repeat) body.repeat = null;
      else {
        const end = repeatEndFromInputs(
          { kind: form.repeatEnd, date: form.repeatEndDate, count: form.repeatEndAfter },
          form.day,
        );
        if ('error' in end) {
          toast(end.error, 'danger');
          return;
        }
        body.repeat = { interval: repeatEveryOf(form), unit: form.repeatUnit, ...end };
      }
    }
    if (form.notes.trim() !== before.notes.trim()) {
      body.notes = form.notes.trim() ? textToHtml(form.notes) : null;
    }
    if (form.queueId !== before.queueId) body.queueId = form.queueId || null;
    // TK2: Completed completes the task, leaving it reopens it (the API does both).
    if (form.status !== before.status) body.status = form.status;
    if (showAssignee && form.assigneeId !== before.assigneeId) {
      body.assigneeId = form.assigneeId || null;
    }
    if (form.stageId !== before.stageId) {
      const pipeline = pipelines.find((p) => p.stages.some((s) => s.id === form.stageId));
      if (pipeline) {
        body.pipelineId = pipeline.id;
        body.stageId = form.stageId;
      } else body.pipelineId = null;
    }
    const added = links.filter((l) => !task.links.some((o) => sameLink(o, l)));
    const removed = task.links.filter((o) => !links.some((l) => sameLink(l, o)));
    if (added.length) body.addLinks = added.map(linkInput);
    if (removed.length) body.removeLinks = removed.map(linkInput);
    if (Object.keys(body).length === 0) {
      toast('Nothing to save');
      return;
    }
    body.updatedAt = task.updatedAt;
    setBusy('save');
    try {
      show(await updateTask(task.id, body));
      toast('Task saved');
      onChanged();
    } catch (err) {
      failed(err);
    } finally {
      setBusy(null);
    }
  };

  const toggleStatus = async () => {
    if (!task || busy) return;
    setBusy('status');
    try {
      const next = done ? await reopenTask(task.id) : await completeTask(task.id);
      show(next);
      toast(done ? 'Task reopened' : 'Task completed');
      onChanged();
    } catch (err) {
      failed(err);
    } finally {
      setBusy(null);
    }
  };

  const remove = async () => {
    if (!task || busy) return;
    setBusy('delete');
    try {
      await deleteTask(task.id);
      setConfirmDelete(false);
      onDeleted(task);
      onClose();
    } catch (err) {
      failed(err);
    } finally {
      setBusy(null);
    }
  };

  const meta = task
    ? [
        done
          ? `Completed${task.completedAt ? ` ${formatDue({ dueAt: task.completedAt, dueDate: null }, timeZone, region)}` : ''}${task.completedBy ? ` by ${task.completedBy.name}` : ''}`
          : 'Open',
        task.createdBy ? `Created by ${task.createdBy.name}` : null,
      ]
        .filter(Boolean)
        .join(' · ')
    : '';

  return (
    <>
      <CrmModal id="taskDetailModal" open={open} onClose={onClose} drawer size="wide">
        <form noValidate onSubmit={save}>
          <ModalHeader
            id="taskDetailModal"
            title={task ? 'Task' : 'Loading task…'}
            onClose={onClose}
          />
          <div className="modal__body">
            {loadError ? <Alert tone="danger">{loadError}</Alert> : null}
            {conflict && taskId ? (
              <Alert tone="warning">
                Someone else changed this task.{' '}
                <button
                  type="button"
                  className="btn-crm btn-crm--outline btn-crm--sm"
                  onClick={() => void load(taskId)}
                >
                  Reload
                </button>
              </Alert>
            ) : null}
            {task && form ? (
              <>
                <p
                  className={cn('crm-fs-8 crm-mb-3', done ? 'crm-text-success' : 'crm-text-muted')}
                >
                  {meta}
                </p>
                <fieldset disabled={!editable || busy !== null} style={{ border: 0, padding: 0 }}>
                  <div className="form-grid">
                    <Field label="Task title" htmlFor="taskEditTitle" className="span-2">
                      <input
                        className="input"
                        id="taskEditTitle"
                        required
                        maxLength={255}
                        value={form.title}
                        onChange={(e) => set('title')(e.target.value)}
                      />
                    </Field>
                    <Field label="Type" htmlFor="taskEditType">
                      <select
                        className="input"
                        id="taskEditType"
                        value={form.taskType}
                        onChange={(e) => set('taskType')(e.target.value)}
                      >
                        {taskTypes.some((t) => t.value === form.taskType) ? null : (
                          <option value={form.taskType}>{form.taskType}</option>
                        )}
                        {taskTypes.map((t) => (
                          <option key={t.id} value={t.value}>
                            {t.label}
                          </option>
                        ))}
                      </select>
                    </Field>
                    <Field label="Task stage" htmlFor="taskEditStatus">
                      <select
                        className="input"
                        id="taskEditStatus"
                        value={form.status}
                        onChange={(e) => set('status')(e.target.value as TaskStatus)}
                      >
                        {TASK_STATUSES.map((st) => (
                          <option key={st} value={st}>
                            {TASK_STATUS_LABELS[st]}
                          </option>
                        ))}
                      </select>
                    </Field>
                    <Field label="Priority" htmlFor="taskEditPriority">
                      <select
                        className="input"
                        id="taskEditPriority"
                        value={form.priority}
                        onChange={(e) => set('priority')(e.target.value)}
                      >
                        <option value="">None</option>
                        {TASK_PRIORITIES.map((p) => (
                          <option key={p} value={p}>
                            {priorityLabel(p)}
                          </option>
                        ))}
                      </select>
                    </Field>
                    <Field label="Due date" htmlFor="taskEditDay">
                      <input
                        className="input"
                        id="taskEditDay"
                        type="date"
                        value={form.day}
                        onChange={(e) => set('day')(e.target.value)}
                      />
                    </Field>
                    <Field label="Time (optional)" htmlFor="taskEditTime">
                      <input
                        className="input"
                        id="taskEditTime"
                        type="time"
                        value={form.time}
                        onChange={(e) => set('time')(e.target.value)}
                      />
                    </Field>
                    <Field label="Send reminder" htmlFor="taskEditReminder">
                      <select
                        className="input"
                        id="taskEditReminder"
                        value={form.reminder}
                        onChange={(e) => set('reminder')(e.target.value)}
                      >
                        {TASK_REMINDER_OPTIONS.map((o) => (
                          <option key={o.key} value={o.key}>
                            {o.label}
                          </option>
                        ))}
                      </select>
                    </Field>
                    {form.reminder === 'custom' ? (
                      <Field label="Reminder date and time" htmlFor="taskEditReminderAt">
                        <input
                          className="input"
                          id="taskEditReminderAt"
                          type="datetime-local"
                          value={form.reminderCustom}
                          onChange={(e) => set('reminderCustom')(e.target.value)}
                        />
                      </Field>
                    ) : (
                      <div aria-hidden />
                    )}
                    <div className="span-2 crm-d-flex crm-align-items-center crm-gap-2">
                      <label className="check">
                        <input
                          type="checkbox"
                          id="taskEditRepeat"
                          checked={form.repeat}
                          onChange={(e) =>
                            setForm((f) => (f ? { ...f, repeat: e.target.checked } : f))
                          }
                        />
                        <span>Set to repeat</span>
                      </label>
                      {form.repeat ? (
                        <>
                          <span>every</span>
                          <input
                            className="input"
                            type="number"
                            min={1}
                            max={99}
                            aria-label="Repeat every"
                            style={{ width: 72 }}
                            value={form.repeatEvery}
                            onChange={(e) => set('repeatEvery')(e.target.value)}
                          />
                          <select
                            className="input"
                            aria-label="Repeat unit"
                            style={{ width: 'auto' }}
                            value={form.repeatUnit}
                            onChange={(e) => set('repeatUnit')(e.target.value)}
                          >
                            {TASK_REPEAT_UNITS.map((u) => (
                              <option key={u} value={u}>
                                {u}
                              </option>
                            ))}
                          </select>
                          {/* TK7 (P16): the series' end. */}
                          <span>ends</span>
                          <select
                            className="input"
                            aria-label="Repeat ends"
                            style={{ width: 'auto' }}
                            value={form.repeatEnd}
                            onChange={(e) => set('repeatEnd')(e.target.value)}
                          >
                            {TASK_REPEAT_END_OPTIONS.map((o) => (
                              <option key={o.key} value={o.key}>
                                {o.label}
                              </option>
                            ))}
                          </select>
                          {form.repeatEnd === 'date' ? (
                            <input
                              className="input"
                              type="date"
                              aria-label="Repeat ends on"
                              style={{ width: 'auto' }}
                              value={form.repeatEndDate}
                              onChange={(e) => set('repeatEndDate')(e.target.value)}
                            />
                          ) : null}
                          {form.repeatEnd === 'after' ? (
                            <>
                              <input
                                className="input"
                                type="number"
                                min={1}
                                max={TASK_REPEAT_MAX_OCCURRENCES}
                                aria-label="Number of tasks"
                                style={{ width: 72 }}
                                value={form.repeatEndAfter}
                                onChange={(e) => set('repeatEndAfter')(e.target.value)}
                              />
                              <span>times</span>
                            </>
                          ) : null}
                        </>
                      ) : null}
                    </div>
                    <Field label="Assigned to" htmlFor="taskEditAssignee" className="span-2">
                      {showAssignee && editable ? (
                        <select
                          className="input"
                          id="taskEditAssignee"
                          value={form.assigneeId}
                          onChange={(e) => set('assigneeId')(e.target.value)}
                        >
                          <option value="">Nobody</option>
                          {task.assignee && !members.some((m) => m.userId === task.assignee?.id) ? (
                            <option value={task.assignee.id}>{task.assignee.name}</option>
                          ) : null}
                          {members.map((m) => (
                            <option key={m.userId} value={m.userId}>
                              {m.userId === me.user.id ? `${m.name} (me)` : m.name}
                            </option>
                          ))}
                        </select>
                      ) : (
                        <input
                          className="input"
                          id="taskEditAssignee"
                          readOnly
                          disabled
                          value={task.assignee?.name ?? 'Nobody'}
                        />
                      )}
                    </Field>
                    <Field label="Queue" htmlFor="taskEditQueue" className="span-2">
                      <select
                        className="input"
                        id="taskEditQueue"
                        value={form.queueId}
                        onChange={(e) => set('queueId')(e.target.value)}
                      >
                        <option value="">None</option>
                        {/* A queue the user cannot use (private to someone else) still shows. */}
                        {form.queueId && !queues.some((q) => q.id === form.queueId) ? (
                          <option value={form.queueId}>
                            {task.queueId === form.queueId
                              ? 'Another user’s queue'
                              : 'Unknown queue'}
                          </option>
                        ) : null}
                        {queues.map((q) => (
                          <option key={q.id} value={q.id}>
                            {q.name}
                          </option>
                        ))}
                      </select>
                    </Field>
                    {/* HUB-226: shown once the business has a task pipeline. */}
                    {(pipelines.some((p) => !p.archived) || task.stageId) && (
                      <Field label="Pipeline stage" htmlFor="taskEditStage" className="span-2">
                        <select
                          className="input"
                          id="taskEditStage"
                          value={form.stageId}
                          disabled={!editable}
                          onChange={(e) => set('stageId')(e.target.value)}
                        >
                          <option value="">Not in a pipeline</option>
                          {pipelines.map((p) => {
                            // Archived pipelines and stages only for the task's own stage.
                            const stages = p.stages.filter(
                              (s) => (!s.archived && !p.archived) || s.id === task.stageId,
                            );
                            return stages.length ? (
                              <optgroup key={p.id} label={p.name}>
                                {stages.map((s) => (
                                  <option key={s.id} value={s.id}>
                                    {s.name}
                                  </option>
                                ))}
                              </optgroup>
                            ) : null;
                          })}
                        </select>
                      </Field>
                    )}
                    <Field label="Associated with" htmlFor="taskEditLinks" className="span-2">
                      <TaskLinksPicker
                        id="taskEditLinks"
                        value={links}
                        onChange={setLinks}
                        disabled={!editable}
                        customTypes
                      />
                    </Field>
                    <Field label="Notes" htmlFor="taskEditNotes" className="span-2">
                      <SnippetTextarea
                        className="input"
                        id="taskEditNotes"
                        rows={4}
                        style={TEXTAREA_STYLE}
                        value={form.notes}
                        onChange={(e) => set('notes')(e.target.value)}
                        snippetTarget={snippetTargetFromLinks(links)}
                      />
                    </Field>
                  </div>
                </fieldset>
                <p className="crm-fs-8 crm-text-muted crm-mt-3">Times are in {timeZone}.</p>
              </>
            ) : null}
          </div>
          <div className="modal__footer">
            {task && canWrite ? (
              <>
                <button
                  type="button"
                  className="btn-crm btn-crm--ghost crm-me-auto crm-text-danger"
                  disabled={busy !== null || !editable}
                  title={lockedReason}
                  onClick={() => setConfirmDelete(true)}
                >
                  Delete
                </button>
                {draft && !done ? (
                  <button
                    type="button"
                    className="btn-crm btn-crm--outline"
                    disabled={busy !== null || !draft.to}
                    title={draft.to ? undefined : 'The contact has no email address'}
                    onClick={() => setComposing(true)}
                  >
                    Send email
                  </button>
                ) : null}
                <button
                  type="button"
                  className={cn('btn-crm btn-crm--outline', busy === 'status' && 'is-loading')}
                  disabled={busy !== null || !editable}
                  title={lockedReason}
                  onClick={() => void toggleStatus()}
                >
                  {done ? 'Reopen' : 'Mark complete'}
                </button>
                <button
                  type="submit"
                  className={cn('btn-crm btn-crm--primary', busy === 'save' && 'is-loading')}
                  disabled={busy !== null || !editable}
                  title={lockedReason}
                  aria-busy={busy === 'save'}
                >
                  Save
                </button>
              </>
            ) : (
              <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
                Close
              </button>
            )}
          </div>
        </form>
      </CrmModal>
      {draft ? (
        <SendEmailDrawer
          open={composing}
          onClose={() => setComposing(false)}
          contactId={draft.contactId}
          contactEmail={draft.to}
          recordLink={{ type: 'contact', id: draft.contactId }}
          recordName={
            task?.links.find((l) => l.objectType === 'contact' && l.id === draft.contactId)
              ?.displayName
          }
          signature={null}
          initialSubject={draft.subject}
          initialBodyHtml={draft.bodyHtml}
          onSent={() => void onEmailSent()}
        />
      ) : null}
      <ConfirmDialog
        id="taskDeleteConfirm"
        open={confirmDelete}
        title="Delete task?"
        confirmLabel="Delete"
        busy={busy === 'delete'}
        onCancel={() => setConfirmDelete(false)}
        onConfirm={() => void remove()}
      >
        &ldquo;{task?.title}&rdquo; will be deleted. An admin can restore it.
      </ConfirmDialog>
    </>
  );
}
