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('/teacher/syllabuses');
    set({ syllabuses: response.data });
  },

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

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

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

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

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

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

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

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

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