import { ResultFiltersSchema } from "@monkeytype/schemas/users";
import { createFilterPreset } from "../elements/account/result-filters";
import { SimpleModal } from "../elements/simple-modal";
import { normalizeName } from "../utils/strings";

export function show(): void {
  newFilterPresetModal.show(undefined, {});
}

const newFilterPresetModal = new SimpleModal({
  id: "newFilterPresetModal",
  title: "New Filter Preset",
  inputs: [
    {
      placeholder: "Preset Name",
      type: "text",
      initVal: "",
      validation: {
        isValid: async (name) => {
          const parsed = ResultFiltersSchema.shape.name.safeParse(
            normalizeName(name),
          );
          if (parsed.success) return true;
          return parsed.error.errors.map((err) => err.message).join(", ");
        },
        debounceDelay: 0,
      },
    },
  ],
  buttonText: "add",
  execFn: async (_thisPopup, name) => {
    const cleanedName = ResultFiltersSchema.shape.name.parse(
      normalizeName(name),
    );
    const status = await createFilterPreset(cleanedName);

    if (status === 1) {
      return { status: "success", message: "Filter preset created" };
    } else {
      let status: "error" | "notice" | "success" = "error";
      let message: string = "Error creating filter preset";
      return { status, message, alwaysHide: true };
    }
  },
});
