import { useMemo } from 'react'
import { api } from '../../../__data__/api/api'

export interface AttendanceData {
  students: any[]
  teachers: any[]
  attendance: any[]
  isLoading: boolean
  courseInfo: any
}

export const useAttendanceData = (courseId: string | undefined): AttendanceData => {
  const { data: attendance, isLoading } = api.useLessonListQuery(courseId, {
    selectFromResult: ({ data, isLoading }) => ({
      data: data?.body,
      isLoading,
    }),
  })
  const { data: courseInfo, isLoading: courseInfoIsLoading } =
    api.useGetCourseByIdQuery(courseId)

  const processedData = useMemo(() => {
    if (!attendance) return { students: [], teachers: [], attendance: [] }

    const studentsMap = new Map()
    const teachersMap = new Map()

    attendance.forEach((lesson) => {
      lesson.teachers?.forEach((teacher: any) => {
        teachersMap.set(teacher.sub, {  
          id: teacher.sub, 
          ...teacher, 
          value: teacher.value || (teacher.family_name && teacher.given_name
            ? `${teacher.family_name} ${teacher.given_name}`
            : teacher.name || teacher.email || teacher.preferred_username || teacher.family_name || teacher.given_name), 
        })
      })

      lesson.students.forEach((student) => {
        const current = studentsMap.get(student.sub) || {}

        studentsMap.set(student.sub, {
          ...student,
          id: student.sub,
          value: current.value || (student.family_name && student.given_name
              ? `${student.family_name} ${student.given_name}`
              : student.name || student.email || student.preferred_username || student.family_name || student.given_name),
        })
      })
    })

    const compare = Intl.Collator('ru').compare

    const students = [...studentsMap.values()]
    const teachers = [...teachersMap.values()]
    students.sort(({ family_name: name }, { family_name: nname }) =>
      compare(name, nname),
    )
    
    return {
      students,
      teachers,
      attendance,
    }
  }, [attendance])

  return {
    ...processedData,
    isLoading: isLoading || courseInfoIsLoading,
    courseInfo
  }
} 