import axios from 'src/utils/axios';

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

export async function getHomework(params) {
  const q = new URLSearchParams();
  if (params?.status) q.append('status', params.status);
  if (params?.page_size) q.append('page_size', String(params.page_size || 1000));
  if (params?.child_id) q.append('child_id', params.child_id);
  const query = q.toString();
  const url = `/homework/homeworks/${query ? `?${query}` : ''}`;
  const res = await axios.get(url);
  const {data} = res;
  if (Array.isArray(data)) return { results: data, count: data.length };
  return { results: data?.results ?? [], count: data?.count ?? 0 };
}

export async function getHomeworkById(id) {
  const res = await axios.get(`/homework/homeworks/${id}/`);
  return res.data;
}

export async function createHomework(data) {
  const payload = { max_score: 5, passing_score: 1, ...data };
  const res = await axios.post('/homework/homeworks/', payload);
  return res.data;
}

export async function updateHomework(id, data) {
  const res = await axios.patch(`/homework/homeworks/${id}/`, data);
  return res.data;
}

export async function publishHomework(id) {
  const res = await axios.post(`/homework/homeworks/${id}/publish/`);
  return res.data;
}

export async function getHomeworkSubmissions(homeworkId, options) {
  const params = new URLSearchParams({ homework_id: String(homeworkId) });
  if (options?.child_id) params.append('child_id', options.child_id);
  const res = await axios.get(`/homework/submissions/?${params.toString()}`);
  const {data} = res;
  if (Array.isArray(data)) return data;
  return data?.results ?? [];
}

export async function getMySubmission(homeworkId, options) {
  const list = await getHomeworkSubmissions(homeworkId, options);
  return list.length > 0 ? list[0] : null;
}

export async function getHomeworkSubmission(submissionId) {
  const res = await axios.get(`/homework/submissions/${submissionId}/`);
  return res.data;
}

export async function gradeSubmission(submissionId, data) {
  const res = await axios.post(`/homework/submissions/${submissionId}/grade/`, data);
  return res.data;
}

export async function checkSubmissionWithAi(submissionId) {
  const res = await axios.post(`/homework/submissions/${submissionId}/check_with_ai/`);
  return res.data;
}

export async function returnSubmissionForRevision(submissionId, feedback) {
  const res = await axios.post(`/homework/submissions/${submissionId}/return_for_revision/`, {
    feedback,
  });
  return res.data;
}

export async function deleteSubmission(submissionId) {
  await axios.delete(`/homework/submissions/${submissionId}/`);
}

export async function submitHomework(homeworkId, data, onUploadProgress) {
  const hasFiles = data.files && data.files.length > 0;
  if (hasFiles) {
    const formData = new FormData();
    formData.append('homework_id', String(homeworkId));
    if (data.content) formData.append('content', data.content);
    data.files.forEach((f) => formData.append('attachment', f));
    const res = await axios.post('/homework/submissions/', formData, {
      onUploadProgress:
        onUploadProgress &&
        ((event) => {
          if (event.total && event.total > 0) {
            onUploadProgress(Math.min(Math.round((event.loaded / event.total) * 100), 100));
          }
        }),
    });
    return res.data;
  }
  const res = await axios.post('/homework/submissions/', {
    homework_id: homeworkId,
    content: data.content || '',
  });
  return res.data;
}

export async function uploadHomeworkFile(homeworkId, file) {
  const formData = new FormData();
  formData.append('homework', String(homeworkId));
  formData.append('file_type', 'assignment');
  formData.append('file', file);
  const res = await axios.post('/homework/files/', formData);
  return res.data;
}

export async function deleteHomeworkFile(fileId) {
  await axios.delete(`/homework/files/${fileId}/`);
}

// Helpers
export function validateHomeworkFiles(files) {
  const MAX_FILES = 10;
  const MAX_SIZE = 50 * 1024 * 1024;
  if (files.length > MAX_FILES) return { valid: false, error: `Максимум ${MAX_FILES} файлов` };
  const oversized = files.find((f) => f.size > MAX_SIZE);
  if (oversized) return { valid: false, error: `Файл "${oversized.name}" больше 50 МБ` };
  return { valid: true };
}

export function getHomeworkStatus(hw) {
  if (hw.status !== 'published') return 'pending';
  if (hw.checked_submissions > 0 && hw.checked_submissions === hw.total_submissions)
    return 'reviewed';
  if (hw.returned_submissions > 0 && hw.returned_submissions === hw.total_submissions)
    return 'returned';
  if (hw.total_submissions > 0) return 'submitted';
  return 'pending';
}
