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

export interface EdutainmentItem {
  id: number;
  uid: string;
  game_type: 'scramble' | 'trivia';
  subject_id: number;
  subject_name?: string;
  created_by: number;
  first_name?: string;
  last_name?: string;
  question_text: string;
  hint_text?: string | null;
  options?: string[] | null;
  correct_answer: string;
  created_at: string;
}

export interface EdutainmentGame {
  id: number;
  uid: string;
  game_type: 'math' | 'scramble' | 'trivia';
  title: string;
  description?: string | null;
  subject_id: number;
  subject_name?: string;
  created_by: number;
  first_name?: string;
  last_name?: string;
  difficulty: 'easy' | 'medium' | 'hard';
  reward_points: number;
  time_limit_seconds: number;
  game_config: any; // for math: operators/range. for scramble: items. for trivia: questions.
  is_published: number;
  attempts_count?: number;
  created_at: string;
}

interface EdutainmentStore {
  content: EdutainmentItem[];
  games: EdutainmentGame[];
  isLoading: boolean;
  error: string | null;

  fetchContent: (gameType?: 'scramble' | 'trivia', subjectId?: number) => Promise<EdutainmentItem[]>;
  createContent: (data: {
    game_type: 'scramble' | 'trivia';
    subject_id: number;
    question_text: string;
    hint_text?: string;
    options?: string[];
    correct_answer?: string;
  }) => Promise<EdutainmentItem>;
  deleteContent: (id: number) => Promise<void>;

  fetchGames: (gameType?: 'math' | 'scramble' | 'trivia', subjectId?: number) => Promise<EdutainmentGame[]>;
  createGame: (data: {
    game_type: 'math' | 'scramble' | 'trivia';
    title: string;
    description?: string;
    subject_id: number;
    difficulty?: 'easy' | 'medium' | 'hard';
    reward_points?: number;
    time_limit_seconds?: number;
    game_config: any;
  }) => Promise<EdutainmentGame>;
  deleteGame: (id: number) => Promise<void>;
  submitSession: (gameId: number, score: number) => Promise<void>;
  reset: () => void;
}

export const useEdutainmentStore = create<EdutainmentStore>((set) => ({
  content: [],
  games: [],
  isLoading: false,
  error: null,

  fetchContent: async (gameType, subjectId) => {
    try {
      set({ isLoading: true, error: null });
      let url = '/edutainment/content';
      const params: string[] = [];
      if (gameType) params.push(`game_type=${gameType}`);
      if (subjectId) params.push(`subject_id=${subjectId}`);
      if (params.length > 0) {
        url += `?${params.join('&')}`;
      }
      const response = await api.get(url);
      set({ content: response.data || [], isLoading: false });
      return response.data;
    } catch (err: any) {
      set({ error: err.response?.data?.error || err.message, isLoading: false });
      console.error('Failed to fetch edutainment content:', err);
      return [];
    }
  },

  createContent: async (data) => {
    try {
      set({ isLoading: true, error: null });
      const response = await api.post('/edutainment/content', data);
      const created = response.data;
      set((state) => ({
        content: [created, ...state.content],
        isLoading: false,
      }));
      return created;
    } catch (err: any) {
      const errMsg = err.response?.data?.error || err.message;
      set({ error: errMsg, isLoading: false });
      throw new Error(errMsg);
    }
  },

  deleteContent: async (id) => {
    try {
      set({ isLoading: true, error: null });
      await api.delete(`/edutainment/content/${id}`);
      set((state) => ({
        content: state.content.filter((item) => item.id !== id),
        isLoading: false,
      }));
    } catch (err: any) {
      set({ error: err.response?.data?.error || err.message, isLoading: false });
      console.error('Failed to delete edutainment content:', err);
    }
  },

  fetchGames: async (gameType, subjectId) => {
    try {
      set({ isLoading: true, error: null });
      let url = '/edutainment/games';
      const params: string[] = [];
      if (gameType) params.push(`game_type=${gameType}`);
      if (subjectId) params.push(`subject_id=${subjectId}`);
      if (params.length > 0) {
        url += `?${params.join('&')}`;
      }
      const response = await api.get(url);
      set({ games: response.data || [], isLoading: false });
      return response.data;
    } catch (err: any) {
      set({ error: err.response?.data?.error || err.message, isLoading: false });
      console.error('Failed to fetch edutainment games:', err);
      return [];
    }
  },

  createGame: async (data) => {
    try {
      set({ isLoading: true, error: null });
      const response = await api.post('/edutainment/games', data);
      const created = response.data;
      set((state) => ({
        games: [created, ...state.games],
        isLoading: false,
      }));
      return created;
    } catch (err: any) {
      const errMsg = err.response?.data?.error || err.message;
      set({ error: errMsg, isLoading: false });
      throw new Error(errMsg);
    }
  },

  deleteGame: async (id) => {
    try {
      set({ isLoading: true, error: null });
      await api.delete(`/edutainment/games/${id}`);
      set((state) => ({
        games: state.games.filter((g) => g.id !== id),
        isLoading: false,
      }));
    } catch (err: any) {
      set({ error: err.response?.data?.error || err.message, isLoading: false });
      console.error('Failed to delete edutainment game:', err);
    }
  },

  submitSession: async (gameId, score) => {
    try {
      set({ error: null });
      await api.post('/edutainment/sessions', { game_id: gameId, score });
    } catch (err: any) {
      console.error('Failed to submit edutainment session:', err);
    }
  },

  reset: () => {
    set({ content: [], games: [], isLoading: false, error: null });
  },
}));

export default useEdutainmentStore;
