import axios from 'src/utils/axios';

// ----------------------------------------------------------------------

/**
 * GET /mentor/dashboard/
 */
export async function getMentorDashboard(options) {
  const config = options?.signal ? { signal: options.signal } : undefined;
  const res = await axios.get('/mentor/dashboard/', config);
  return res.data;
}

/**
 * GET /mentor/income/?period=week
 */
export async function getMentorIncome(period = 'week', startDate, endDate, options) {
  let url = `/mentor/income/?period=${period}`;
  if (period === 'range' && startDate && endDate) {
    url += `&start_date=${startDate}&end_date=${endDate}`;
  }
  const config = options?.signal ? { signal: options.signal } : undefined;
  const res = await axios.get(url, config);
  return res.data;
}

/**
 * GET /client/dashboard/
 */
export async function getClientDashboard(options) {
  const config = options?.signal ? { signal: options.signal } : undefined;
  const res = await axios.get('/client/dashboard/', config);
  return normalizeClientDashboard(res.data);
}

/**
 * GET /parent/{childId}/child_dashboard/
 */
export async function getChildDashboard(childId, options) {
  const config = options?.signal ? { signal: options.signal } : undefined;
  const res = await axios.get(`/parent/${childId}/child_dashboard/`, config);
  return normalizeClientDashboard(res.data);
}

/**
 * GET /parent/dashboard/
 */
export async function getParentDashboard(options) {
  const config = options?.signal ? { signal: options.signal } : undefined;
  const res = await axios.get('/parent/dashboard/', config);
  return res.data;
}

// ----------------------------------------------------------------------
// Calendar / Schedule

/**
 * GET /schedule/lessons/calendar/?start_date=&end_date=
 */
export async function getCalendarLessons(startDate, endDate, options) {
  const params = new URLSearchParams({ start_date: startDate, end_date: endDate });
  const config = options?.signal ? { signal: options.signal } : undefined;
  const res = await axios.get(`/schedule/lessons/calendar/?${params}`, config);
  return res.data;
}

/**
 * GET /schedule/lessons/{id}/
 */
export async function getLesson(id) {
  const res = await axios.get(`/schedule/lessons/${id}/`);
  return res.data;
}

/**
 * POST /schedule/lessons/
 */
export async function createCalendarLesson(data) {
  const res = await axios.post('/schedule/lessons/', data);
  return res.data;
}

/**
 * PATCH /schedule/lessons/{id}/
 */
export async function updateCalendarLesson(id, data) {
  const res = await axios.patch(`/schedule/lessons/${id}/`, data);
  return res.data;
}

/**
 * DELETE /schedule/lessons/{id}/
 */
export async function deleteCalendarLesson(id, deleteAllFuture = false) {
  await axios.delete(`/schedule/lessons/${id}/`, {
    data: { delete_all_future: deleteAllFuture },
  });
}

// ----------------------------------------------------------------------
// Students & Subjects

/**
 * GET /manage/clients/?page=1&page_size=200
 */
export async function getMentorStudents() {
  const res = await axios.get('/manage/clients/?page=1&page_size=200');
  return res.data;
}

/**
 * GET /schedule/subjects/
 */
export async function getMentorSubjects() {
  const res = await axios.get('/schedule/subjects/');
  return res.data;
}

/**
 * GET /schedule/lessons/ — список занятий с фильтром по статусу
 */
export async function getLessons(params = {}) {
  const query = new URLSearchParams();
  if (params.status) query.set('status', params.status);
  if (params.start_date) query.set('start_date', params.start_date);
  if (params.end_date) query.set('end_date', params.end_date);
  if (params.client_id) query.set('client_id', params.client_id);
  if (params.child_id) query.set('child_id', params.child_id);
  const q = query.toString();
  const res = await axios.get(`/schedule/lessons/${q ? `?${q}` : ''}`);
  return res.data;
}

// ----------------------------------------------------------------------
// Lesson completion / files

/**
 * POST /schedule/lessons/{id}/complete/
 */
export async function completeLesson(id, notes, mentorGrade, schoolGrade, homeworkText, hasHomeworkFiles, lessonFileIds) {
  const body = {
    notes: notes ?? '',
    mentor_grade: mentorGrade,
    school_grade: schoolGrade,
    homework_text: homeworkText,
    has_homework_files: hasHomeworkFiles,
  };
  if (lessonFileIds != null) {
    body.lesson_file_ids = lessonFileIds;
  }
  const res = await axios.post(`/schedule/lessons/${id}/complete/`, body);
  return res.data;
}

/**
 * POST /schedule/lesson-files/ (multipart)
 */
export async function uploadLessonFile(lessonId, file) {
  const formData = new FormData();
  formData.append('lesson', String(lessonId));
  formData.append('file', file);
  const res = await axios.post('/schedule/lesson-files/', formData);
  return res.data;
}

// ----------------------------------------------------------------------

function normalizeClientDashboard(raw) {
  const s = raw?.summary ?? {};
  const upcoming = raw?.upcoming_lessons ?? [];
  return {
    total_lessons: s.total_lessons ?? 0,
    completed_lessons: s.completed_lessons ?? 0,
    homework_pending: s.pending_homeworks ?? 0,
    homework_completed: s.completed_homeworks ?? 0,
    average_grade: s.average_score ?? 0,
    next_lesson: upcoming[0]
      ? {
          id: String(upcoming[0].id),
          title: upcoming[0].title ?? '',
          subject: '',
          start_time: upcoming[0].start_time ?? '',
          end_time: upcoming[0].end_time ?? '',
          status: 'scheduled',
          mentor: upcoming[0].mentor
            ? { id: String(upcoming[0].mentor.id), first_name: upcoming[0].mentor.name, last_name: '' }
            : undefined,
        }
      : null,
    upcoming_lessons: upcoming.map((l) => ({
      id: String(l.id),
      title: l.title ?? '',
      subject: '',
      start_time: l.start_time ?? '',
      end_time: l.end_time ?? '',
      status: 'scheduled',
      mentor: l.mentor
        ? { id: String(l.mentor.id), first_name: l.mentor.name, last_name: '' }
        : undefined,
    })),
    recent_homework: [],
  };
}
