import { useState } from "react";
import type { HabitConfig } from "../habits/contracts";
import { habitPatch } from "../habits/contracts";
import { Field } from "./design-system/Field";
import { ScheduleEditor } from "./design-system/EditingWorkbench";
import { HabitColorPicker } from "./design-system/HabitColorPicker";
import { InlineItemForm, type ItemMode } from "./InlineItemForm";
import { Checkbox } from "./design-system/primitives";

export function InlineHabitEditor({ config, color: initialColor, date, mode, disabled, onSave, onDelete, onClose }: {
  config: HabitConfig;
  color: string;
  date: string;
  mode: ItemMode;
  disabled: boolean;
  onSave: (patch: Record<string, unknown>) => Promise<void>;
  onDelete: () => Promise<void>;
  onClose: () => void;
}) {
  const [schedule, setSchedule] = useState(config.schedule);
  const [method, setMethod] = useState(config.method);
  const [carryPartialProgress, setCarryPartialProgress] = useState(config.method === "count" && config.carryPartialProgress);
  const [color, setColor] = useState(initialColor);
  const [target, setTarget] = useState(config.method === "count" ? config.target : 1);
  const [unit, setUnit] = useState(config.method === "count" ? config.unit : "times");
  return (
    <InlineItemForm name={config.name} kind="habit" mode={mode} disabled={disabled} onClose={onClose} onDelete={onDelete}
      onSave={async (name) => {
        const parsed = habitPatch.safeParse({ name, method, schedule, color, ...(method === "count" ? { target, unit, carryPartialProgress } : {}) });
        if (!parsed.success) throw new Error(parsed.error.issues.map((issue) => issue.message).join(" "));
        await onSave(parsed.data);
      }}>
      <Field label="How will you track it?">
        {(id) => <select id={id} value={method} onChange={(event) => setMethod(event.target.value as HabitConfig["method"])}>
          <option value="manual">A simple check-in</option>
          <option value="count">A count target</option>
          <option value="tasks">A list of tasks</option>
        </select>}
      </Field>
      {method !== config.method && <p className="ds-footnote">Changing the tracking method starts today’s progress over. Earlier history is kept.{method === "tasks" ? " After saving, add tasks below." : config.method === "tasks" ? " Existing tasks will leave this habit." : ""}</p>}
      {method === "count" && (<>
        <div className="ds-form-grid">
          <Field label="Daily target">{(id) => <input id={id} type="number" min={1} max={10000} step={1} required value={Number.isNaN(target) ? "" : target} onChange={(event) => setTarget(event.target.valueAsNumber)} />}</Field>
          <Field label="Unit">{(id) => <input id={id} required maxLength={80} value={unit} onChange={(event) => setUnit(event.target.value)} />}</Field>
        </div>
        <Checkbox label="Carry unfinished counts to the next scheduled day" checked={carryPartialProgress} onChange={(event) => setCarryPartialProgress(event.target.checked)} />
        <p className="ds-footnote">Completed counts reset. Explicitly recorded counts are kept.</p>
      </>)}
      <ScheduleEditor value={schedule} onChange={setSchedule} anchorDate={date} />
      <HabitColorPicker value={color} onChange={setColor} mode="edit" />
      <p className="ds-footnote">Changes start today. Earlier targets and schedules stay as they were.</p>
    </InlineItemForm>
  );
}
