import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { Module, Topic, Progress } from '@/types';

/**
 * Module State Interface
 */
interface ModuleState {
  // State
  modules: Module[];
  currentModule: Module | null;
  currentTopic: Topic | null;
  progress: Progress[];
  isLoading: boolean;
  error: string | null;

  // Actions
  setModules: (modules: Module[]) => void;
  setCurrentModule: (module: Module | null) => void;
  setCurrentTopic: (topic: Topic | null) => void;
  setProgress: (progress: Progress[]) => void;
  updateModuleProgress: (moduleId: string, progress: Partial<Progress>) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  clearError: () => void;
  reset: () => void;
}

/**
 * Module Store with Zustand
 */
export const useModuleStore = create<ModuleState>()(
  persist(
    (set) => ({
      // Initial State
      modules: [],
      currentModule: null,
      currentTopic: null,
      progress: [],
      isLoading: false,
      error: null,

      // Actions
      setModules: (modules) =>
        set({
          modules,
          error: null,
        }),

      setCurrentModule: (module) =>
        set({
          currentModule: module,
        }),

      setCurrentTopic: (topic) =>
        set({
          currentTopic: topic,
        }),

      setProgress: (progress) =>
        set({
          progress,
        }),

      updateModuleProgress: (moduleId, progressUpdate) =>
        set((state) => {
          const existingIndex = state.progress.findIndex((p) => p.moduleId === moduleId);
          if (existingIndex >= 0) {
            return {
              progress: state.progress.map((p) =>
                p.moduleId === moduleId ? { ...p, ...progressUpdate } : p
              ),
            };
          }
          const newProgress: Progress = {
            userId: '',
            moduleId,
            exercisesCompleted: 0,
            totalExercises: 0,
            points: 0,
            percentage: 0,
            isStarted: true,
            isCompleted: false,
            lastActivityAt: new Date().toISOString(),
            ...progressUpdate,
          };
          return {
            progress: [...state.progress, newProgress],
          };
        }),

      setLoading: (isLoading) =>
        set({
          isLoading,
        }),

      setError: (error) =>
        set({
          error,
        }),

      clearError: () =>
        set({
          error: null,
        }),

      reset: () =>
        set({
          modules: [],
          currentModule: null,
          currentTopic: null,
          progress: [],
          isLoading: false,
          error: null,
        }),
    }),
    {
      name: 'math-platform-modules',
      partialize: (state) => ({
        progress: state.progress,
      }),
    }
  )
);

/**
 * Selectors for better performance
 */
export const selectModules = (state: ModuleState): Module[] => state.modules;
export const selectCurrentModule = (state: ModuleState): Module | null => state.currentModule;
export const selectModuleProgress = (moduleId: string) => (state: ModuleState): Progress | undefined =>
  state.progress.find((p) => p.moduleId === moduleId);
