/**
 * Homework Module - Zustand Store
 */

import { create } from 'zustand';
import api from './api';
import type { Attachment } from './attachments';

export type HomeworkStatus = 'draft' | 'published' | 'closed';

export interface Homework {
  id: number;
  uid?: string;
  subject_id: number;
  class_id?: number | null;
  title: string;
  description?: string;
  instructions?: string;
  due_date?: string | null;
  max_score?: number;
  allow_late_submission?: boolean;
  is_published?: boolean;
  status: HomeworkStatus | string;
  created_by?: number | null;
  created_at?: string;
  updated_at?: string;
  attachments?: Attachment[];
  subject_name?: string;
  class_name?: string;
  submission_count?: number;
  graded_count?: number;
}

export interface HomeworkSubmission {
  id: number;
  uid?: string;
  homework_id: number;
  student_id: number;
  content?: string;
  submitted_at?: string;
  status: 'submitted' | 'graded' | 'returned' | 'late' | string;
  grade?: number | null;
  feedback?: string | null;
  graded_by?: number | null;
  graded_at?: string | null;
  attachments?: Attachment[];
  marked_scripts?: Attachment[];
  student_name?: string;
  student_email?: string;
}

interface HomeworkState {
  items: Homework[];
  current: Homework | null;
  submissions: Record<number, HomeworkSubmission[]>;
  loading: boolean;
  error: string | null;

  list: () => Promise<Homework[]>;
  get: (id: number) => Promise<Homework | null>;
  create: (data: Partial<Homework>) => Promise<Homework>;
  update: (id: number, data: Partial<Homework>) => Promise<Homework>;
  remove: (id: number) => Promise<void>;
  submit: (homeworkId: number, payload: { content?: string; file?: File }) => Promise<HomeworkSubmission>;
  grade: (homeworkId: number, submissionId: number, payload: { grade: number; feedback?: string }) => Promise<HomeworkSubmission>;
  returnSubmission: (homeworkId: number, submissionId: number) => Promise<HomeworkSubmission>;
  mySubmissions: () => Promise<HomeworkSubmission[]>;
}

export const useHomeworkStore = create<HomeworkState>((set, get) => ({
  items: [],
  current: null,
  submissions: {},
  loading: false,
  error: null,

  list: async () => {
    set({ loading: true, error: null });
    try {
      const res = await api.get('/homework');
      const rows: Homework[] = Array.isArray(res.data) ? res.data : [];
      set({ items: rows, loading: false });
      return rows;
    } catch (err: any) {
      set({ items: [], loading: false, error: err?.response?.data?.error || err.message });
      return [];
    }
  },

  get: async (id) => {
    set({ loading: true, error: null });
    try {
      const res = await api.get(`/homework/${id}`);
      const data: Homework = res.data;
      set(state => ({
        current: data,
        submissions: {
          ...state.submissions,
          [id]: (data as any).submissions || []
        },
        loading: false
      }));
      return data;
    } catch (err: any) {
      set({ loading: false, error: err?.response?.data?.error || err.message });
      return null;
    }
  },

  create: async (data) => {
    set({ loading: true, error: null });
    try {
      const res = await api.post('/homework', data);
      const created: Homework = res.data;
      set(state => ({
        items: [created, ...state.items],
        loading: false
      }));
      return created;
    } catch (err: any) {
      set({ loading: false, error: err?.response?.data?.error || err.message });
      throw err;
    }
  },

  update: async (id, data) => {
    set({ loading: true, error: null });
    try {
      const res = await api.put(`/homework/${id}`, data);
      const updated: Homework = res.data;
      set(state => ({
        items: state.items.map(item => item.id === id ? updated : item),
        current: state.current?.id === id ? updated : state.current,
        loading: false
      }));
      return updated;
    } catch (err: any) {
      set({ loading: false, error: err?.response?.data?.error || err.message });
      throw err;
    }
  },

  remove: async (id) => {
    set({ loading: true, error: null });
    try {
      await api.delete(`/homework/${id}`);
      set(state => ({
        items: state.items.filter(item => item.id !== id),
        current: state.current?.id === id ? null : state.current,
        loading: false
      }));
    } catch (err: any) {
      set({ loading: false, error: err?.response?.data?.error || err.message });
      throw err;
    }
  },

  submit: async (homeworkId, payload) => {
    set({ loading: true, error: null });
    try {
      const formData = new FormData();
      if (payload.content) formData.append('content', payload.content);
      if (payload.file) formData.append('file', payload.file);

      const res = await api.post(`/homework/${homeworkId}/submit`, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      });
      const submission: HomeworkSubmission = res.data;

      // Update submissions in local state
      set(state => {
        const list = state.submissions[homeworkId] || [];
        const nextList = list.filter(s => s.student_id !== submission.student_id).concat([submission]);
        return {
          submissions: { ...state.submissions, [homeworkId]: nextList },
          loading: false
        };
      });

      return submission;
    } catch (err: any) {
      set({ loading: false, error: err?.response?.data?.error || err.message });
      throw err;
    }
  },

  grade: async (homeworkId, submissionId, payload) => {
    set({ loading: true, error: null });
    try {
      const res = await api.put(`/homework/${homeworkId}/submissions/${submissionId}/grade`, payload);
      const updatedSub: HomeworkSubmission = res.data;

      set(state => {
        const list = state.submissions[homeworkId] || [];
        const nextList = list.map(s => s.id === submissionId ? { ...s, ...updatedSub } : s);
        return {
          submissions: { ...state.submissions, [homeworkId]: nextList },
          loading: false
        };
      });

      return updatedSub;
    } catch (err: any) {
      set({ loading: false, error: err?.response?.data?.error || err.message });
      throw err;
    }
  },

  returnSubmission: async (homeworkId, submissionId) => {
    set({ loading: true, error: null });
    try {
      const res = await api.post(`/homework/${homeworkId}/submissions/${submissionId}/return`);
      const updatedSub: HomeworkSubmission = res.data;

      set(state => {
        const list = state.submissions[homeworkId] || [];
        const nextList = list.map(s => s.id === submissionId ? { ...s, ...updatedSub } : s);
        return {
          submissions: { ...state.submissions, [homeworkId]: nextList },
          loading: false
        };
      });

      return updatedSub;
    } catch (err: any) {
      set({ loading: false, error: err?.response?.data?.error || err.message });
      throw err;
    }
  },

  mySubmissions: async () => {
    set({ loading: true, error: null });
    try {
      const res = await api.get('/homework/my/submissions');
      set({ loading: false });
      return res.data;
    } catch (err: any) {
      set({ loading: false, error: err?.response?.data?.error || err.message });
      return [];
    }
  }
}));

export default useHomeworkStore;
