// stores/screenStore.js
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useScreenStore = defineStore('screen', () => {
  // Initial screen items data
  const screenItems = ref([
    {
      id: 1,
      namaScreen: "Layar Screen 1",
      nomorScreen: "SCR-001",
      klinik: ["AN", "AS", "BD", "GI", "GR", "GZ", "IP", "JT"],
    },
    {
      id: 2,
      namaScreen: "Layar Screen 2",
      nomorScreen: "SCR-002",
      klinik: ["JW", "KK", "MT", "SR", "OB", "PR"],
    },
    {
      id: 3,
      namaScreen: "Layar Screen 3",
      nomorScreen: "SCR-003",
      klinik: ["RT", "RM", "HO"],
    },
  ]);

  // Computed
  const getScreenById = (id) => {
    return computed(() => {
      const targetId = Number(id);
      return screenItems.value.find((s) => Number(s.id) === targetId);
    });
  };

  const getAllScreens = computed(() => screenItems.value);

  // Actions
  const addScreen = (screenPayload) => {
    // Ensure we get a valid ID even if screenItems is empty
    const maxId = screenItems.value.length > 0 
      ? Math.max(...screenItems.value.map(s => s.id), 0) 
      : 0;
    const newId = maxId + 1;
    // Pastikan id baru tidak tertimpa payload (payload.id bisa null)
    const newScreen = {
      ...screenPayload,
      id: newId,
    };
    screenItems.value.push(newScreen);
    return { success: true, message: `Screen ${newScreen.namaScreen} berhasil ditambahkan`, data: newScreen };
  };

  const updateScreen = (screenPayload) => {
    const index = screenItems.value.findIndex(s => s.id === screenPayload.id);
    if (index !== -1) {
      screenItems.value[index] = {
        ...screenItems.value[index],
        ...screenPayload,
      };
      return { success: true, message: `Konfigurasi ${screenPayload.namaScreen} berhasil disimpan` };
    }
    return { success: false, message: 'Screen tidak ditemukan' };
  };

  const deleteScreen = (screenId) => {
    const index = screenItems.value.findIndex(s => s.id === screenId);
    if (index !== -1) {
      const screenName = screenItems.value[index].namaScreen;
      screenItems.value.splice(index, 1);
      return { success: true, message: `Screen ${screenName} berhasil dihapus` };
    }
    return { success: false, message: 'Screen tidak ditemukan' };
  };

  return {
    // State
    screenItems,
    
    // Computed
    getAllScreens,
    getScreenById,
    
    // Actions
    addScreen,
    updateScreen,
    deleteScreen,
  };
}, {
  persist: {
    key: 'screen-store-state',
    storage: typeof window !== 'undefined' ? localStorage : undefined,
    paths: ['screenItems'],
  },
});

