// src/hooks/useSendActivity.ts
import { useState, useCallback as useCallback2, useMemo, useRef as useRef2 } from "react";
import dayjs from "dayjs";

// src/utils/categoryDataUtils.ts
async function fetchStudentsByFilters(apiClient, filters) {
  if ((!filters.schoolIds || filters.schoolIds.length === 0) && (!filters.schoolYearIds || filters.schoolYearIds.length === 0) && (!filters.classIds || filters.classIds.length === 0)) {
    return [];
  }
  const response = await apiClient.post("/students/filters", {
    ...filters.schoolIds && filters.schoolIds.length > 0 && {
      schoolIds: filters.schoolIds
    },
    ...filters.schoolYearIds && filters.schoolYearIds.length > 0 && {
      schoolYearIds: filters.schoolYearIds
    },
    ...filters.classIds && filters.classIds.length > 0 && {
      classIds: filters.classIds
    }
  });
  return response.data.data.students || [];
}
async function loadCategoriesData(apiClient, existingCategories) {
  if (existingCategories.length > 0) {
    return existingCategories;
  }
  const [schoolsResponse, schoolYearsResponse, classesResponse] = await Promise.all([
    apiClient.get(
      "/school"
    ),
    apiClient.get("/schoolYear"),
    apiClient.get("/classes")
  ]);
  const schools = schoolsResponse.data.data.schools;
  const schoolYears = schoolYearsResponse.data.data.schoolYears;
  const classes = classesResponse.data.data.classes;
  const transformedCategories = [
    {
      key: "escola",
      label: "Escola",
      itens: schools.map((s) => ({ id: s.id, name: s.companyName })),
      selectedIds: []
    },
    {
      key: "serie",
      label: "S\xE9rie",
      dependsOn: ["escola"],
      filteredBy: [{ key: "escola", internalField: "schoolId" }],
      itens: schoolYears.map((sy) => ({
        id: sy.id,
        name: sy.name,
        schoolId: sy.schoolId
      })),
      selectedIds: []
    },
    {
      key: "turma",
      label: "Turma",
      dependsOn: ["serie"],
      filteredBy: [{ key: "serie", internalField: "schoolYearId" }],
      itens: classes.map((c) => ({
        id: c.id,
        name: c.name,
        schoolYearId: c.schoolYearId
      })),
      selectedIds: []
    },
    {
      key: "students",
      label: "Alunos",
      dependsOn: ["turma"],
      filteredBy: [
        { key: "escola", internalField: "escolaId" },
        { key: "serie", internalField: "serieId" },
        { key: "turma", internalField: "turmaId" }
      ],
      // Students will be loaded dynamically based on selections
      itens: [],
      selectedIds: []
    }
  ];
  return transformedCategories;
}

// src/utils/useDynamicStudentFetching.ts
import { useCallback, useRef } from "react";
function extractSelectedIds(updatedCategories) {
  const escolaCategory = updatedCategories.find((c) => c.key === "escola");
  const serieCategory = updatedCategories.find((c) => c.key === "serie");
  const turmaCategory = updatedCategories.find((c) => c.key === "turma");
  const studentsCategory = updatedCategories.find((c) => c.key === "students");
  return {
    schoolIds: escolaCategory?.selectedIds || [],
    schoolYearIds: serieCategory?.selectedIds || [],
    classIds: turmaCategory?.selectedIds || [],
    studentsCategory
  };
}
function detectSelectionChanges(previousSelections, currentSelections) {
  const isInitialState = previousSelections.schoolIds.length === 0 && previousSelections.schoolYearIds.length === 0 && previousSelections.classIds.length === 0;
  const arraysEqual = (a, b) => {
    if (a.length !== b.length) return false;
    return a.every((id) => b.includes(id)) && b.every((id) => a.includes(id));
  };
  const schoolIdsChanged = isInitialState || !arraysEqual(previousSelections.schoolIds, currentSelections.schoolIds);
  const schoolYearIdsChanged = isInitialState || !arraysEqual(
    previousSelections.schoolYearIds,
    currentSelections.schoolYearIds
  );
  const classIdsChanged = isInitialState || !arraysEqual(previousSelections.classIds, currentSelections.classIds);
  const shouldFetchStudents = schoolIdsChanged || schoolYearIdsChanged || classIdsChanged;
  return {
    schoolIdsChanged,
    schoolYearIdsChanged,
    classIdsChanged,
    shouldFetchStudents
  };
}
function transformStudentsToItems(students) {
  return students.map((s) => ({
    id: `${s.userInstitutionId}-${s.class.id}`,
    name: s.name,
    classId: String(s.class.id),
    schoolId: String(s.school.id),
    schoolYearId: String(s.schoolYear.id),
    studentId: s.id,
    userInstitutionId: s.userInstitutionId,
    escolaId: String(s.school.id),
    serieId: String(s.schoolYear.id),
    turmaId: String(s.class.id)
  }));
}
function updateCategoriesWithStudents(updatedCategories, studentItems) {
  return updatedCategories.map(
    (cat) => cat.key === "students" ? { ...cat, itens: studentItems } : cat
  );
}
function clearStudentsFromCategories(updatedCategories) {
  return updatedCategories.map(
    (cat) => cat.key === "students" ? { ...cat, itens: [] } : cat
  );
}
function useDynamicStudentFetching(setCategories, options = {}) {
  const {
    apiClient,
    fetchStudentsByFilters: customFetchStudents,
    onError
  } = options;
  const previousSelectionsRef = useRef({
    schoolIds: [],
    schoolYearIds: [],
    classIds: []
  });
  const fetchRequestId = useRef(0);
  const buildStudentFilters = useCallback(
    (selectedSchoolIds, selectedSchoolYearIds, selectedClassIds) => ({
      schoolIds: selectedSchoolIds.length > 0 ? selectedSchoolIds : void 0,
      schoolYearIds: selectedSchoolYearIds.length > 0 ? selectedSchoolYearIds : void 0,
      classIds: selectedClassIds.length > 0 ? selectedClassIds : void 0
    }),
    []
  );
  const fetchWithCustomFunction = useCallback(
    async (selectedSchoolIds, selectedSchoolYearIds, selectedClassIds, localRequestId) => {
      if (!customFetchStudents) {
        return null;
      }
      const filters = buildStudentFilters(
        selectedSchoolIds,
        selectedSchoolYearIds,
        selectedClassIds
      );
      const students = await customFetchStudents(filters);
      if (localRequestId !== fetchRequestId.current) {
        return null;
      }
      return students;
    },
    [customFetchStudents, buildStudentFilters]
  );
  const fetchWithApiClient = useCallback(
    async (selectedSchoolIds, selectedSchoolYearIds, selectedClassIds, localRequestId) => {
      if (!apiClient) {
        return null;
      }
      const filters = buildStudentFilters(
        selectedSchoolIds,
        selectedSchoolYearIds,
        selectedClassIds
      );
      const students = await fetchStudentsByFilters(apiClient, filters);
      if (localRequestId !== fetchRequestId.current) {
        return null;
      }
      return students;
    },
    [apiClient, buildStudentFilters]
  );
  const performStudentFetch = useCallback(
    async (selectedSchoolIds, selectedSchoolYearIds, selectedClassIds, localRequestId) => {
      const students = await fetchWithCustomFunction(
        selectedSchoolIds,
        selectedSchoolYearIds,
        selectedClassIds,
        localRequestId
      );
      if (students !== null) {
        return students;
      }
      return fetchWithApiClient(
        selectedSchoolIds,
        selectedSchoolYearIds,
        selectedClassIds,
        localRequestId
      );
    },
    [fetchWithCustomFunction, fetchWithApiClient]
  );
  const handleSuccessfulFetch = useCallback(
    (students, updatedCategories, localRequestId) => {
      if (localRequestId !== fetchRequestId.current) {
        return false;
      }
      const studentItems = transformStudentsToItems(students);
      const finalCategories = updateCategoriesWithStudents(
        updatedCategories,
        studentItems
      );
      setCategories(finalCategories);
      return true;
    },
    [setCategories]
  );
  const handleFetchError = useCallback(
    (error, updatedCategories, localRequestId) => {
      console.error("Error fetching students:", error);
      if (onError && error instanceof Error) {
        onError(error);
      }
      if (localRequestId !== fetchRequestId.current) {
        return false;
      }
      const finalCategories = clearStudentsFromCategories(updatedCategories);
      setCategories(finalCategories);
      return true;
    },
    [onError, setCategories]
  );
  const handleCategoriesChange = useCallback(
    async (updatedCategories) => {
      if (!customFetchStudents && !apiClient) {
        setCategories(updatedCategories);
        return;
      }
      const {
        schoolIds: selectedSchoolIds,
        schoolYearIds: selectedSchoolYearIds,
        classIds: selectedClassIds,
        studentsCategory
      } = extractSelectedIds(updatedCategories);
      const previousSelections = previousSelectionsRef.current;
      const { shouldFetchStudents } = detectSelectionChanges(
        previousSelections,
        {
          schoolIds: selectedSchoolIds,
          schoolYearIds: selectedSchoolYearIds,
          classIds: selectedClassIds
        }
      );
      previousSelectionsRef.current = {
        schoolIds: [...selectedSchoolIds],
        schoolYearIds: [...selectedSchoolYearIds],
        classIds: [...selectedClassIds]
      };
      if (shouldFetchStudents && selectedClassIds.length > 0 && studentsCategory) {
        fetchRequestId.current += 1;
        const localRequestId = fetchRequestId.current;
        try {
          const students = await performStudentFetch(
            selectedSchoolIds,
            selectedSchoolYearIds,
            selectedClassIds,
            localRequestId
          );
          if (students === null) {
            return;
          }
          handleSuccessfulFetch(students, updatedCategories, localRequestId);
        } catch (error) {
          handleFetchError(error, updatedCategories, localRequestId);
        }
      } else if (shouldFetchStudents && studentsCategory) {
        fetchRequestId.current += 1;
        const finalCategories = clearStudentsFromCategories(updatedCategories);
        setCategories(finalCategories);
      } else {
        setCategories(updatedCategories);
      }
    },
    [
      apiClient,
      customFetchStudents,
      setCategories,
      performStudentFetch,
      handleSuccessfulFetch,
      handleFetchError
    ]
  );
  return {
    handleCategoriesChange
  };
}

// src/hooks/useSendActivity.ts
function toISODateTime(date, time) {
  return dayjs(`${date}T${time}`).toISOString();
}
function useSendActivity(config) {
  const { api, onSuccess, onError } = config;
  const [isOpen, setIsOpen] = useState(false);
  const [selectedModel, setSelectedModel] = useState(
    null
  );
  const [categories, setCategories] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isCategoriesLoading, setIsCategoriesLoading] = useState(false);
  const categoriesLoadedRef = useRef2(false);
  const initialData = useMemo(() => {
    if (!selectedModel) return void 0;
    return {
      title: selectedModel.title
    };
  }, [selectedModel]);
  const loadCategories = useCallback2(async () => {
    if (categoriesLoadedRef.current) return;
    setIsCategoriesLoading(true);
    try {
      const categoryConfig = await loadCategoriesData(api, []);
      setCategories(categoryConfig);
      categoriesLoadedRef.current = true;
    } catch (error) {
      console.error("Error loading categories:", error);
      onError?.("Erro ao carregar destinat\xE1rios");
    } finally {
      setIsCategoriesLoading(false);
    }
  }, [api, onError]);
  const openModal = useCallback2(
    (model) => {
      setSelectedModel(model);
      setIsOpen(true);
      void loadCategories();
    },
    [loadCategories]
  );
  const closeModal = useCallback2(() => {
    setIsOpen(false);
    setSelectedModel(null);
  }, []);
  const { handleCategoriesChange: onCategoriesChange } = useDynamicStudentFetching(setCategories, { apiClient: api });
  const handleSubmit = useCallback2(
    async (data) => {
      if (!selectedModel) return;
      setIsLoading(true);
      try {
        let questionIds = null;
        try {
          const response = await api.get(`/activity-drafts/${selectedModel.id}`);
          questionIds = response.data.data.selectedQuestions?.map((q) => q.id) || null;
        } catch {
          questionIds = null;
        }
        if (!questionIds || questionIds.length === 0) {
          throw new Error("N\xE3o foi poss\xEDvel obter quest\xF5es do modelo");
        }
        const createResponse = await api.post(
          "/activities",
          {
            title: data.title,
            subjectId: selectedModel.subjectId,
            questionIds,
            subtype: data.subtype,
            isDigital: data.subtype === "PROVA" /* PROVA */ ? data.mode !== "PRESENCIAL" /* PRESENCIAL */ : true,
            notification: data.notification,
            startDate: toISODateTime(data.startDate, data.startTime),
            finalDate: toISODateTime(data.finalDate, data.finalTime),
            canRetry: data.canRetry
          }
        );
        await api.post("/activities/send-to-students", {
          activityId: createResponse.data.data.id,
          students: data.students
        });
        onSuccess?.(`Atividade enviada para ${data.students.length} aluno(s)`);
        closeModal();
      } catch (error) {
        console.error("Error sending activity:", error);
        onError?.("Erro ao enviar atividade");
      } finally {
        setIsLoading(false);
      }
    },
    [selectedModel, api, onSuccess, onError, closeModal]
  );
  return {
    isOpen,
    openModal,
    closeModal,
    selectedModel,
    initialData,
    categories,
    onCategoriesChange,
    isLoading,
    isCategoriesLoading,
    handleSubmit
  };
}
export {
  useSendActivity
};
//# sourceMappingURL=index.mjs.map