Skip to content

Your favorite shift management application!

10.1 KB
Raw Blame
"use client";

import { Ref, useId } from "react";
import { useTranslations } from "next-intl";
import { Input } from "@/components/ui/input";
import { CheckRow, ColorSwatches, Field, inputClass } from "@/components/form-kit";
import { CustomFieldInputs } from "@/components/custom-field-inputs";
import { DEFAULT_COLOR } from "@/lib/constants";
import type { PresetFormData, ShiftPresetWithValues } from "@/hooks/usePresets";
import { useAuthFeatures } from "@/hooks/useAuthFeatures";
import { useCustomFields } from "@/hooks/useCustomFields";
import { cn } from "@/lib/utils";
import { suggestNextTimeRange, validateTimeRanges, toTimeRanges } from "@/lib/time-ranges";
import { Button } from "@/components/ui/button";
import { Plus, X } from "lucide-react";

export const EMPTY_PRESET_FORM: PresetFormData = {
  title: "",
  startTime: "09:00",
  endTime: "17:00",
  color: DEFAULT_COLOR,
  notes: "",
  groupName: "",
  isSecondary: false,
  isAllDay: false,
  hideFromStats: false,
  defaultSignupCapacity: null,
  segments: [],
  customFields: {},
};

export function presetToFormData(preset: ShiftPresetWithValues): PresetFormData {
  return {
    title: preset.title,
    startTime: preset.startTime,
    endTime: preset.endTime,
    color: preset.color,
    notes: preset.notes || "",
    groupName: preset.groupName || "",
    isSecondary: preset.isSecondary || false,
    isAllDay: preset.isAllDay || false,
    hideFromStats: preset.hideFromStats || false,
    defaultSignupCapacity: preset.defaultSignupCapacity ?? null,
    segments: preset.segments ?? [],
    customFields: preset.customFields ?? {},
  };
}

export function samePresetForm(a: PresetFormData, b: PresetFormData): boolean {
  const { segments: segmentsA, customFields: customFieldsA, ...restA } = a;
  const { segments: segmentsB, customFields: customFieldsB, ...restB } = b;
  return (
    (Object.keys(restA) as (keyof typeof restA)[]).every((key) => restA[key] === restB[key]) &&
    JSON.stringify(segmentsA) === JSON.stringify(segmentsB) &&
    JSON.stringify(customFieldsA ?? {}) === JSON.stringify(customFieldsB ?? {})
  );
}


interface PresetFormCardProps {
  formId: string;
  editing: boolean;
  value: PresetFormData;
  onChange: (patch: Partial<PresetFormData>) => void;
  onSubmit: () => void;
  disabled?: boolean;
  cardRef?: Ref<HTMLFormElement>;
  titleRef?: Ref<HTMLInputElement>;
  /** Existing group names across this calendar's presets, offered as datalist suggestions. */
  existingGroupNames?: string[];
  splitShiftsEnabled?: boolean;
  calendarId?: string;
}

/** "Neue Vorlage" card; the same card edits an existing preset. */
export function PresetFormCard({
  formId,
  editing,
  value,
  onChange,
  onSubmit,
  disabled,
  cardRef,
  titleRef,
  existingGroupNames = [],
  splitShiftsEnabled,
  calendarId,
}: PresetFormCardProps) {
  const t = useTranslations();
  const id = useId();
  const { isAuthEnabled } = useAuthFeatures();
  const { customFields } = useCustomFields(calendarId ?? null);
  const fieldClass = cn(inputClass, "bg-surface-card");

  return (
    <form
      id={formId}
      ref={cardRef}
      onSubmit={(e) => {
        e.preventDefault();
        onSubmit();
      }}
      className="flex scroll-mt-4 flex-col gap-3 rounded-[11px] border border-line bg-surface-panel p-4"
    >
      <div className="text-[14px] font-semibold text-fg-strong">
        {editing ? t("preset.edit") : t("presetSheet.newPreset")}
      </div>

      <Field label={t("shift.titleLabel")} htmlFor={`${id}-title`}>
        <Input
          id={`${id}-title`}
          ref={titleRef}
          value={value.title}
          onChange={(e) => onChange({ title: e.target.value })}
          placeholder={t("presetSheet.titlePlaceholder")}
          className={fieldClass}
          disabled={disabled}
        />
      </Field>

      {!value.isAllDay && (
        <div className="grid grid-cols-2 gap-2.5">
          <Field label={t("presetSheet.start")} htmlFor={`${id}-start`}>
            <Input
              id={`${id}-start`}
              type="time"
              value={value.startTime}
              onChange={(e) => onChange({ startTime: e.target.value })}
              className={cn(fieldClass, "font-mono")}
              disabled={disabled}
            />
          </Field>
          <Field label={t("presetSheet.end")} htmlFor={`${id}-end`}>
            <Input
              id={`${id}-end`}
              type="time"
              value={value.endTime}
              onChange={(e) => onChange({ endTime: e.target.value })}
              className={cn(fieldClass, "font-mono")}
              disabled={disabled}
            />
          </Field>
        </div>
      )}

      {!value.isAllDay && value.segments.length > 0 && (
        <div className="flex flex-col gap-2">
          {value.segments.map((segment, index) => (
            <div key={index} className="grid grid-cols-[1fr_1fr_auto] items-end gap-2.5">
              <Field label={t("presetSheet.start")}>
                <Input
                  type="time"
                  value={segment.startTime}
                  onChange={(e) => {
                    const next = [...value.segments];
                    next[index] = { ...next[index], startTime: e.target.value };
                    onChange({ segments: next });
                  }}
                  className={cn(fieldClass, "font-mono")}
                  disabled={disabled}
                />
              </Field>
              <Field label={t("presetSheet.end")}>
                <Input
                  type="time"
                  value={segment.endTime}
                  onChange={(e) => {
                    const next = [...value.segments];
                    next[index] = { ...next[index], endTime: e.target.value };
                    onChange({ segments: next });
                  }}
                  className={cn(fieldClass, "font-mono")}
                  disabled={disabled}
                />
              </Field>
              <Button
                type="button"
                variant="outline"
                size="icon"
                aria-label={t("timeRanges.remove")}
                disabled={disabled}
                onClick={() => onChange({ segments: value.segments.filter((_, i) => i !== index) })}
              >
                <X className="size-4" />
              </Button>
            </div>
          ))}
        </div>
      )}

      {!value.isAllDay && splitShiftsEnabled && !disabled && (
        <Button
          type="button"
          variant="outline"
          size="sm"
          className="self-start"
          onClick={() =>
            onChange({
              segments: [...value.segments, suggestNextTimeRange(toTimeRanges(value))],
            })
          }
        >
          <Plus className="size-4" />
          {t("timeRanges.add")}
        </Button>
      )}

      {!value.isAllDay &&
        (() => {
          const error = validateTimeRanges(toTimeRanges(value));
          return error ? <p className="text-[13px] text-destructive">{t(`timeRanges.errors.${error}`)}</p> : null;
        })()}

      <ColorSwatches
        value={value.color}
        onChange={(color) => onChange({ color })}
        allowCustom
        disabled={disabled}
      />

      <Field label={t("form.notesLabel")} htmlFor={`${id}-notes`} optional>
        <Input
          id={`${id}-notes`}
          value={value.notes}
          onChange={(e) => onChange({ notes: e.target.value })}
          placeholder={t("form.notesPlaceholder")}
          className={fieldClass}
          disabled={disabled}
        />
      </Field>

      {customFields.length > 0 && (
        <div className="flex flex-col gap-3">
          <div className="text-[13px] font-semibold text-fg-body">
            {t("customFields.presetDefaultsTitle")}
          </div>
          <CustomFieldInputs
            definitions={customFields}
            values={value.customFields ?? {}}
            onChange={(customFields) => onChange({ customFields })}
            disabled={disabled}
          />
        </div>
      )}

      {isAuthEnabled && (
        <Field
          label={t("presetSheet.defaultSignupCapacityLabel")}
          htmlFor={`${id}-signup-capacity`}
          hint={t("presetSheet.defaultSignupCapacityHint")}
          optional
        >
          <Input
            id={`${id}-signup-capacity`}
            type="number"
            min={1}
            inputMode="numeric"
            value={value.defaultSignupCapacity ?? ""}
            onChange={(e) =>
              onChange({
                defaultSignupCapacity: e.target.value === "" ? null : Number(e.target.value),
              })
            }
            className={fieldClass}
            disabled={disabled}
          />
        </Field>
      )}

      <Field label={t("preset.group")} htmlFor={`${id}-group`} optional>
        <Input
          id={`${id}-group`}
          list={`${id}-group-names`}
          value={value.groupName}
          onChange={(e) => onChange({ groupName: e.target.value })}
          placeholder={t("preset.groupPlaceholder")}
          className={fieldClass}
          disabled={disabled}
        />
        <datalist id={`${id}-group-names`}>
          {existingGroupNames.map((name) => (
            <option key={name} value={name} />
          ))}
        </datalist>
      </Field>

      <div className="flex flex-col gap-2.5 pt-0.5">
        <CheckRow
          id={`${id}-allday`}
          checked={value.isAllDay}
          onCheckedChange={(isAllDay) => onChange({ isAllDay })}
          disabled={disabled}
        >
          {t("presetSheet.allDay")}
        </CheckRow>
        <CheckRow
          id={`${id}-secondary`}
          checked={value.isSecondary}
          onCheckedChange={(isSecondary) => onChange({ isSecondary })}
          disabled={disabled}
          hint={t("presetSheet.markAsSecondaryHint")}
        >
          {t("presetSheet.markAsSecondary")}
        </CheckRow>
        <CheckRow
          id={`${id}-stats`}
          checked={value.hideFromStats}
          onCheckedChange={(hideFromStats) => onChange({ hideFromStats })}
          disabled={disabled}
          hint={t("presetSheet.hideFromStatsHint")}
        >
          {t("preset.hideFromStats")}
        </CheckRow>
      </div>
    </form>
  );
}