/**
 * Marks Module - Zustand Store
 *
 * Talks to /api/marks:
 *   POST /bulk    (teacher/admin) - multipart upload (field "file").
 *                 CSV columns expected: assignment_id,student_id,score,feedback
 *                 Returns { inserted, updated, errors: [{row, reason, data}], total_rows }
 *   GET  /        list submissions (student sees own only)
 */

import { create } from 'zustand';
import api from './auth';
import { createAxiosUploadProgressHandler } from '../lib/uploadProgress';

export interface BulkMarkError {
  row: number;
  reason: string;
  data?: Record<string, string>;
}

export interface BulkMarksResult {
  inserted: number;
  updated: number;
  errors: BulkMarkError[];
  total_rows: number;
}

export interface Submission {
  id: number;
  assignment_id: number;
  student_id: number;
  status: string;
  grade?: number | null;
  feedback?: string | null;
  graded_by?: number | null;
  graded_at?: string | null;
  created_at?: string;
  updated_at?: string;
  assignment_title?: string;
  max_score?: number;
  student_first_name?: string;
  student_last_name?: string;
  grader_first_name?: string;
  grader_last_name?: string;
}

interface MarksStore {
  // State
  submissions: Submission[];
  lastResult: BulkMarksResult | null;
  isUploading: boolean;
  isLoading: boolean;
  error: string | null;
  uploadProgress: number | null;

  // Actions
  uploadBulkMarks: (file: File) => Promise<BulkMarksResult>;
  fetchSubmissions: (filters?: { assignment_id?: number; student_id?: number }) => Promise<void>;
  reset: () => void;
}

export const useMarksStore = create<MarksStore>((set, get) => ({
  submissions: [],
  lastResult: null,
  isUploading: false,
  isLoading: false,
  error: null,
  uploadProgress: null,

  uploadBulkMarks: async (file) => {
    set({ isUploading: true, error: null, uploadProgress: 0 });
    try {
      const formData = new FormData();
      formData.append('file', file);

      const onUploadProgress = createAxiosUploadProgressHandler((percent) => {
        if (percent == null) return;
        set({ uploadProgress: percent });
      });

      const response = await api.post('/marks/bulk', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
        onUploadProgress,
      });
      const result = response.data as BulkMarksResult;
      set({ lastResult: result, isUploading: false, uploadProgress: null });
      return result;
    } catch (error: any) {
      const message = error.response?.data?.error || error.message;
      set({ error: message, isUploading: false, uploadProgress: null });
      throw error;
    }
  },

  fetchSubmissions: async (filters = {}) => {
    try {
      set({ isLoading: true, error: null });
      const params = new URLSearchParams();
      if (filters.assignment_id) params.append('assignment_id', String(filters.assignment_id));
      if (filters.student_id) params.append('student_id', String(filters.student_id));
      const qs = params.toString();
      const url = qs ? `/marks?${qs}` : '/marks';
      const response = await api.get(url);
      set({ submissions: response.data || [], isLoading: false });
    } catch (error: any) {
      set({ error: error.response?.data?.error || error.message, isLoading: false });
      console.error('Failed to fetch submissions:', error);
    }
  },

  reset: () => {
    set({
      lastResult: null,
      error: null,
      uploadProgress: null,
    });
  },
}));

export default useMarksStore;
