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

interface TeacherStore {
  syllabuses: any[];
  schemes: any[];
  focusPoints: any[];
  lessonPlans: any[];
  currentStudentDoc: any | null;

  fetchSyllabuses: () => Promise<void>;
  fetchSchemes: () => Promise<void>;
  fetchFocusPoints: (schemeId?: number) => Promise<void>;
  fetchLessonPlans: () => Promise<void>;
  fetchStudentDoc: (studentUid: string) => Promise<void>;

  createSyllabus: (data: any) => Promise<void>;
  createScheme: (data: any) => Promise<void>;
  createFocusPoint: (data: any) => Promise<void>;
  createLessonPlan: (data: any) => Promise<void>;
  saveStudentSocialDoc: (data: any) => Promise<void>;
}

export const useTeacherStore = create<TeacherStore>((set, get) => ({
  syllabuses: [],
  schemes: [],
  focusPoints: [],
  lessonPlans: [],
  currentStudentDoc: null,

  fetchSyllabuses: async () => {
    const response = await api.get('/api/teacher/syllabuses');
    set({ syllabuses: response.data });
  },

  fetchSchemes: async () => {
    const response = await api.get('/api/teacher/schemes');
    set({ schemes: response.data });
  },

  fetchFocusPoints: async (schemeId) => {
    const response = await api.get(`/api/teacher/focus-points${schemeId ? `?scheme_id=${schemeId}` : ''}`);
    set({ focusPoints: response.data });
  },

  fetchLessonPlans: async () => {
    const response = await api.get('/api/teacher/lesson-plans');
    set({ lessonPlans: response.data });
  },

  fetchStudentDoc: async (studentUid) => {
    const response = await api.get(`/api/social/student-docs/${studentUid}`);
    set({ currentStudentDoc: response.data });
  },

  createSyllabus: async (data: any) => {
    await api.post('/api/teacher/syllabuses', data);
    get().fetchSyllabuses();
  },

  createScheme: async (data: any) => {
    await api.post('/api/teacher/schemes', data);
    get().fetchSchemes();
  },

  createFocusPoint: async (data: any) => {
    await api.post('/api/teacher/focus-points', data);
    get().fetchFocusPoints(data.scheme_id);
  },

  createLessonPlan: async (data: any) => {
    await api.post('/api/teacher/lesson-plans', data);
    get().fetchLessonPlans();
  },

  saveStudentSocialDoc: async (data: any) => {
    await api.post('/api/social/student-docs', data);
    // Refreshing isn't strictly necessary here but good practice
  },
}));
