import { useState } from "react";
import { taskPatch, type Schedule } from "../habits/contracts";
import { scheduleLabel } from "../lib/dashboard";
import { ScheduleEditor } from "./design-system/EditingWorkbench";
import { InlineItemForm, type ItemMode } from "./InlineItemForm";

export function InlineTaskEditor({ name, schedule: savedSchedule, habitSchedule, date, mode, disabled, creating = false, onSave, onDelete, onClose }: {
  name: string;
  schedule: Schedule;
  habitSchedule: Schedule;
  date: string;
  mode: ItemMode;
  disabled: boolean;
  creating?: boolean;
  onSave: (patch: { name?: string; schedule?: Schedule }) => Promise<void>;
  onDelete: () => Promise<void>;
  onClose: () => void;
}) {
  const [schedule, setSchedule] = useState(savedSchedule);
  return (
    <InlineItemForm name={name} kind="task" mode={mode} disabled={disabled} onDelete={onDelete} onClose={onClose}
      formLabel={creating ? "Add task" : undefined} submitLabel={creating ? "Add task" : undefined}
      onSave={async (name) => {
        const parsed = taskPatch.safeParse({ name, schedule });
        if (!parsed.success) throw new Error(parsed.error.issues.map((issue) => issue.message).join(" "));
        await onSave(parsed.data);
      }}>
      <ScheduleEditor value={schedule} onChange={setSchedule} anchorDate={date} />
      <p className="ds-footnote">This task is due when both its recurrence and the habit’s schedule match. Habit: {scheduleLabel(habitSchedule)}.</p>
      {!creating && <p className="ds-footnote">Changes start today. Earlier check-ins keep their original schedule.</p>}
    </InlineItemForm>
  );
}
