"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/SendActivityModal/hooks/useSendActivityModal.ts
var useSendActivityModal_exports = {};
__export(useSendActivityModal_exports, {
  useSendActivityModal: () => useSendActivityModal,
  useSendActivityModalStore: () => useSendActivityModalStore
});
module.exports = __toCommonJS(useSendActivityModal_exports);
var import_zustand = require("zustand");

// src/components/SendActivityModal/validation.ts
var import_zod = require("zod");
var ERROR_MESSAGES = {
  SUBTYPE_REQUIRED: "Campo obrigat\xF3rio! Por favor, selecione uma op\xE7\xE3o para continuar.",
  MODE_REQUIRED: "Campo obrigat\xF3rio! Por favor, selecione o modo de prova para continuar.",
  TITLE_REQUIRED: "Campo obrigat\xF3rio! Por favor, preencha este campo para continuar.",
  STUDENTS_REQUIRED: "Campo obrigat\xF3rio! Por favor, selecione pelo menos um aluno para continuar.",
  START_DATE_REQUIRED: "Campo obrigat\xF3rio! Por favor, preencha este campo para continuar.",
  FINAL_DATE_REQUIRED: "Campo obrigat\xF3rio! Por favor, preencha este campo para continuar.",
  FINAL_DATE_INVALID: "A data final deve ser maior ou igual \xE0 data inicial."
};
var activityStepSchema = import_zod.z.object({
  subtype: import_zod.z.enum(
    ["TAREFA" /* TAREFA */, "TRABALHO" /* TRABALHO */, "PROVA" /* PROVA */],
    { error: () => ERROR_MESSAGES.SUBTYPE_REQUIRED }
  ),
  title: import_zod.z.string({ error: () => ERROR_MESSAGES.TITLE_REQUIRED }).transform((val) => val.trim()).refine((val) => val.length > 0, {
    message: ERROR_MESSAGES.TITLE_REQUIRED
  }),
  notification: import_zod.z.string().optional()
});
var recipientStepSchema = import_zod.z.object({
  students: import_zod.z.array(
    import_zod.z.object({
      studentId: import_zod.z.string(),
      userInstitutionId: import_zod.z.string()
    }),
    {
      error: () => ERROR_MESSAGES.STUDENTS_REQUIRED
    }
  ).min(1, ERROR_MESSAGES.STUDENTS_REQUIRED)
});
var DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/;
var TIME_REGEX = /^\d{2}:\d{2}$/;
var deadlineStepBaseSchema = import_zod.z.object({
  startDate: import_zod.z.string({
    error: () => ERROR_MESSAGES.START_DATE_REQUIRED
  }).min(1, ERROR_MESSAGES.START_DATE_REQUIRED).regex(DATE_REGEX, ERROR_MESSAGES.START_DATE_REQUIRED),
  startTime: import_zod.z.string().regex(TIME_REGEX).default("00:00"),
  finalDate: import_zod.z.string({
    error: () => ERROR_MESSAGES.FINAL_DATE_REQUIRED
  }).min(1, ERROR_MESSAGES.FINAL_DATE_REQUIRED).regex(DATE_REGEX, ERROR_MESSAGES.FINAL_DATE_REQUIRED),
  finalTime: import_zod.z.string().regex(TIME_REGEX).default("23:59"),
  canRetry: import_zod.z.boolean().default(false)
});
var deadlineStepSchema = deadlineStepBaseSchema.refine(
  (data) => {
    const start = /* @__PURE__ */ new Date(`${data.startDate}T${data.startTime}`);
    const end = /* @__PURE__ */ new Date(`${data.finalDate}T${data.finalTime}`);
    return end >= start;
  },
  { message: ERROR_MESSAGES.FINAL_DATE_INVALID, path: ["finalDate"] }
);
function validateActivityStep(data, options) {
  const errors = {};
  if (options?.enableExamMode) {
    if (!data.title || data.title.trim().length === 0) {
      errors.title = ERROR_MESSAGES.TITLE_REQUIRED;
    }
    return errors;
  }
  const result = activityStepSchema.safeParse({
    subtype: data.subtype,
    title: data.title,
    notification: data.notification
  });
  if (!result.success) {
    result.error.issues.forEach((issue) => {
      const field = issue.path[0];
      if (field === "subtype" || field === "title") {
        errors[field] = issue.message;
      }
    });
  }
  if (options?.enableExamMode && data.subtype === "PROVA" /* PROVA */ && !data.mode) {
    errors.mode = ERROR_MESSAGES.MODE_REQUIRED;
  }
  return errors;
}
function validateRecipientStep(data) {
  const errors = {};
  const result = recipientStepSchema.safeParse({
    students: data.students ?? []
  });
  if (!result.success) {
    result.error.issues.forEach((issue) => {
      if (issue.path[0] === "students") {
        errors.students = issue.message;
      }
    });
  }
  return errors;
}
function validateDeadlineStep(data, options) {
  const errors = {};
  if (options?.enableExamMode) {
    if (!data.startDate) {
      errors.startDate = ERROR_MESSAGES.START_DATE_REQUIRED;
    }
    return errors;
  }
  if (!data.startDate) {
    errors.startDate = ERROR_MESSAGES.START_DATE_REQUIRED;
  }
  if (!data.finalDate) {
    errors.finalDate = ERROR_MESSAGES.FINAL_DATE_REQUIRED;
  }
  if (data.startDate && data.finalDate) {
    const result = deadlineStepSchema.safeParse({
      startDate: data.startDate,
      startTime: data.startTime ?? "00:00",
      finalDate: data.finalDate,
      finalTime: data.finalTime ?? "23:59",
      canRetry: data.canRetry ?? false
    });
    if (!result.success) {
      result.error.issues.forEach((issue) => {
        const field = issue.path[0];
        if (field === "startDate" || field === "finalDate") {
          errors[field] = issue.message;
        }
      });
    }
  }
  return errors;
}
function validateStep(step, data, options) {
  switch (step) {
    case 1:
      return validateActivityStep(data, options);
    case 2:
      return validateRecipientStep(data);
    case 3:
      return validateDeadlineStep(data, options);
    default:
      return {};
  }
}

// src/utils/extractStudentsFromCategories.ts
function extractStudentsFromCategories(categories) {
  const studentsCategory = categories.find((cat) => cat.key === "students");
  if (!studentsCategory?.selectedIds || !studentsCategory.itens) {
    return [];
  }
  return studentsCategory.selectedIds.map((id) => {
    const student = studentsCategory.itens?.find((item) => item.id === id);
    if (student) {
      const rawUserInstId = student.userInstitutionId;
      const rawInstId = student.institutionId;
      const rawStudentId = student.studentId;
      let userInstitutionId = "";
      if (typeof rawUserInstId === "string" || typeof rawUserInstId === "number") {
        userInstitutionId = String(rawUserInstId);
      } else if (typeof rawInstId === "string" || typeof rawInstId === "number") {
        userInstitutionId = String(rawInstId);
      }
      let studentId;
      if (typeof rawStudentId === "string" || typeof rawStudentId === "number") {
        studentId = String(rawStudentId);
      } else {
        studentId = String(student.id);
      }
      if (!userInstitutionId) {
        return null;
      }
      return { studentId, userInstitutionId };
    }
    return null;
  }).filter((s) => s !== null);
}

// src/components/SendActivityModal/hooks/useSendActivityModal.ts
var initialState = {
  formData: {
    canRetry: false,
    startTime: "00:00",
    finalTime: "23:59"
  },
  currentStep: 1,
  completedSteps: [],
  errors: {},
  categories: []
};
var useSendActivityModalStore = (0, import_zustand.create)(
  (set, get) => ({
    ...initialState,
    setFormData: (data) => {
      set((state) => ({
        formData: { ...state.formData, ...data }
      }));
    },
    goToStep: (step) => {
      if (step >= 1 && step <= 3) {
        set({ currentStep: step, errors: {} });
      }
    },
    nextStep: (enableExamMode) => {
      const state = get();
      const isValid = state.validateCurrentStep(enableExamMode);
      if (isValid && state.currentStep < 3) {
        set((prev) => ({
          currentStep: prev.currentStep + 1,
          completedSteps: prev.completedSteps.includes(prev.currentStep) ? prev.completedSteps : [...prev.completedSteps, prev.currentStep],
          errors: {}
        }));
        return true;
      }
      return isValid;
    },
    previousStep: () => {
      const state = get();
      if (state.currentStep > 1) {
        set({ currentStep: state.currentStep - 1, errors: {} });
      }
    },
    setErrors: (errors) => {
      set({ errors });
    },
    validateCurrentStep: (enableExamMode) => {
      const state = get();
      let formDataToValidate = state.formData;
      let updatedFormData = state.formData;
      if (state.currentStep === 2 && state.categories.length > 0) {
        const students = extractStudentsFromCategories(state.categories);
        formDataToValidate = { ...state.formData, students };
        updatedFormData = formDataToValidate;
      }
      const options = { enableExamMode };
      const errors = validateStep(
        state.currentStep,
        formDataToValidate,
        options
      );
      set({ formData: updatedFormData, errors });
      return Object.keys(errors).length === 0;
    },
    validateAllSteps: (enableExamMode) => {
      const state = get();
      let formDataForStep2 = state.formData;
      if (state.categories.length > 0) {
        const students = extractStudentsFromCategories(state.categories);
        formDataForStep2 = { ...state.formData, students };
      }
      const options = { enableExamMode };
      const errors1 = validateStep(1, state.formData, options);
      const errors2 = validateStep(2, formDataForStep2);
      const errors3 = validateStep(3, state.formData, options);
      const allErrors = { ...errors1, ...errors2, ...errors3 };
      set({ errors: allErrors });
      return Object.keys(allErrors).length === 0;
    },
    setCategories: (categories) => {
      const students = extractStudentsFromCategories(categories);
      set((state) => ({
        categories,
        formData: { ...state.formData, students }
      }));
    },
    reset: () => {
      set({
        ...initialState,
        categories: []
      });
    }
  })
);
function useSendActivityModal() {
  return useSendActivityModalStore();
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useSendActivityModal,
  useSendActivityModalStore
});
//# sourceMappingURL=useSendActivityModal.js.map