// stores/masterStore.js - Backward Compatibility Layer
// NOTE: Phase 3 - masterStore sekarang hanya sebagai compatibility layer
// Data sebenarnya ada di: loketStore, ruangStore, penunjangStore, clinicStore
import { defineStore } from 'pinia';
import { computed } from 'vue';
import { useClinicStore } from './clinicStore';
import { useLoketStore } from './loketStore';
import { useRuangStore } from './ruangStore';
import { usePenunjangStore } from './penunjangStore';

export const useMasterStore = defineStore('master', () => {
  // Store references
  const clinicStore = useClinicStore();
  const loketStore = useLoketStore();
  const ruangStore = useRuangStore();
  const penunjangStore = usePenunjangStore();

  // ============================================
  // MASTER KLINIK (Backward Compatibility)
  // ============================================
  // NOTE: klinikData sekarang adalah computed yang reference clinicStore (single source of truth)
  // Ini untuk backward compatibility dengan pages yang masih menggunakan masterStore.klinikData
  // Format: { id, no, kode, nama, shift, totalQuota, jamShiftList, autoShift, jadwalKlinik }
  const klinikData = computed(() => {
    console.log('📊 masterStore.klinikData computed called');
    console.log('📊 clinicStore.clinics.length:', clinicStore.clinics.length);
    
    // Sort by kode first, then by jenisLayanan (Reguler before Eksekutif)
    const sortedClinics = [...clinicStore.clinics].sort((a, b) => {
      // First sort by kode
      if (a.kode < b.kode) return -1;
      if (a.kode > b.kode) return 1;
      // If same kode, sort by jenisLayanan (Reguler before Eksekutif)
      if (a.jenisLayanan === 'Reguler' && b.jenisLayanan === 'Eksekutif') return -1;
      if (a.jenisLayanan === 'Eksekutif' && b.jenisLayanan === 'Reguler') return 1;
      // Finally sort by ID if both are same
      return a.id - b.id;
    });
    console.log('📊 sortedClinics.length:', sortedClinics.length);
    
    const result = sortedClinics.map((clinic, index) => {
      // Convert clinic data ke format masterStore (untuk backward compatibility)
      return {
        id: clinic.id,
        no: index + 1,
        kode: clinic.kode,
        nama: clinic.name, // Convert 'name' to 'nama' for compatibility
        shift: typeof clinic.shift === 'string' ? parseInt(clinic.shift.replace(/[^0-9]/g, '')) || 1 : clinic.shift || 1,
        totalQuota: clinic.totalQuota || 0,
        jamShiftList: clinic.jamShiftList || [],
        jamShiftPerHari: clinic.jamShiftPerHari || {}, // New: shift configuration per day
        autoShift: clinic.autoShift || false,
        jadwalKlinik: clinic.jadwalKlinik || [],
        tanggalTutup: clinic.tanggalTutup || [], // New: array of closed dates
        jenisLayanan: clinic.jenisLayanan || 'Reguler',
      };
    });
    
    console.log('📊 masterStore.klinikData result:', result.length, 'items');
    if (result.length > 0) {
      console.log('📋 First item:', result[0]);
    }
    
    return result;
  });

  // Computed - Get klinik list for dropdowns
  const klinikList = computed(() => {
    const availableCodes = new Set(klinikData.value.map((k) => k.kode));

    // getClinicsForDropdown() sudah mengembalikan { id, name, kode, icon, available }
    const baseList = typeof clinicStore.getClinicsForDropdown === 'function'
      ? clinicStore.getClinicsForDropdown()
      : [];

    return baseList
      .filter((c) => availableCodes.has(c.kode))
      .map((c) => ({
        id: c.id,
        kode: c.kode,
        nama: c.name,
      }));
  });

  // Actions - Klinik (delegate to clinicStore)
  const addKlinik = (klinikPayload) => {
    // Map masterStore format ke clinicStore format
    const mappedClinic = {
      ...klinikPayload,
      name: klinikPayload.nama, // Convert 'nama' to 'name'
      shift: `Shift ${klinikPayload.shift || 1}`, // Convert number to string format
    };
    return clinicStore.addClinic(mappedClinic);
  };

  const updateKlinik = (klinikPayload) => {
    // Map masterStore format ke clinicStore format
    const clinicUpdates = {
      ...klinikPayload,
      name: klinikPayload.nama, // Convert 'nama' to 'name'
      shift: `Shift ${klinikPayload.shift}`, // Convert number to string format
    };
    return clinicStore.updateClinic(klinikPayload.id, clinicUpdates);
  };

  const deleteKlinik = (klinikId) => {
    return clinicStore.deleteClinic(klinikId);
  };

  const getKlinikById = (id) => {
    // Menggunakan getter dari clinicStore
    const clinic = clinicStore.clinics.find(c => c.id === id);
    if (clinic) {
      return {
        id: clinic.id,
        no: klinikData.value.findIndex(k => k.id === clinic.id) + 1, // Recalculate 'no'
        kode: clinic.kode,
        nama: clinic.name,
        shift: typeof clinic.shift === 'string' ? parseInt(clinic.shift.replace(/[^0-9]/g, '')) || 1 : clinic.shift || 1,
        totalQuota: clinic.totalQuota,
        jamShiftList: clinic.jamShiftList,
        autoShift: clinic.autoShift,
        jadwalKlinik: clinic.jadwalKlinik,
      };
    }
    return undefined;
  };

  const getKlinikByKode = (kode) => {
    // Menggunakan getter dari clinicStore
    const clinic = clinicStore.getClinicByKode(kode);
    if (clinic) {
      return {
        id: clinic.id,
        no: klinikData.value.findIndex(k => k.kode === clinic.kode) + 1, // Recalculate 'no'
        kode: clinic.kode,
        nama: clinic.name,
        shift: typeof clinic.shift === 'string' ? parseInt(clinic.shift.replace(/[^0-9]/g, '')) || 1 : clinic.shift || 1,
        totalQuota: clinic.totalQuota,
        jamShiftList: clinic.jamShiftList,
        autoShift: clinic.autoShift,
        jadwalKlinik: clinic.jadwalKlinik,
      };
    }
    return undefined;
  };

  // ============================================
  // MASTER LOKET (Backward Compatibility)
  // ============================================
  // Reference dari loketStore
  const loketData = computed(() => loketStore.loketData);
  // availableServices adalah computed dari loketStore
  // Pinia computed sudah handle reactivity dengan baik, jadi akses langsung
  // loketStore.availableServices adalah computed, jadi kita bisa langsung reference
  const availableServices = computed(() => {
    // loketStore.availableServices adalah computed, akses .value untuk mendapatkan array
    const services = loketStore.availableServices;
    return services?.value || services || [];
  });

  // Actions - Loket (delegate to loketStore)
  const addLoket = (loketPayload) => loketStore.addLoket(loketPayload);
  const updateLoket = (loketPayload) => loketStore.updateLoket(loketPayload);
  const deleteLoket = (loketId) => loketStore.deleteLoket(loketId);
  const getLoketById = (id) => loketStore.getLoketById(id);

  // ============================================
  // MASTER KLINIK RUANG (Backward Compatibility)
  // ============================================
  // Reference dari ruangStore
  const ruangData = computed(() => ruangStore.ruangData);
  const totalKlinikRuang = computed(() => ruangStore.totalKlinikRuang);
  const totalRuangan = computed(() => ruangStore.totalRuangan);
  const getAllRuangList = computed(() => ruangStore.getAllRuangList);

  // Actions - Ruang (delegate to ruangStore)
  const addRuang = (ruangPayload) => ruangStore.addRuang(ruangPayload);
  const updateRuang = (ruangPayload) => ruangStore.updateRuang(ruangPayload);
  const deleteRuang = (ruangId) => ruangStore.deleteRuang(ruangId);
  const getRuangByKlinik = (kodeKlinik) => ruangStore.getRuangByKlinik(kodeKlinik);

  // ============================================
  // MASTER PENUNJANG (Backward Compatibility)
  // ============================================
  // Reference dari penunjangStore
  const penunjangData = computed(() => penunjangStore.penunjangData);
  const totalPenunjang = computed(() => penunjangStore.totalPenunjang);
  const activePenunjang = computed(() => penunjangStore.activePenunjang);
  const penunjangMedis = computed(() => penunjangStore.penunjangMedis);
  const penunjangNonMedis = computed(() => penunjangStore.penunjangNonMedis);
  const penunjangList = computed(() => penunjangStore.penunjangList);

  // Actions - Penunjang (delegate to penunjangStore)
  const addPenunjang = (penunjangPayload) => penunjangStore.addPenunjang(penunjangPayload);
  const updatePenunjang = (penunjangPayload) => penunjangStore.updatePenunjang(penunjangPayload);
  const deletePenunjang = (penunjangId) => penunjangStore.deletePenunjang(penunjangId);
  const getPenunjangById = (id) => penunjangStore.getPenunjangById(id);
  const getPenunjangByKode = (kode) => penunjangStore.getPenunjangByKode(kode);
  const getActivePenunjangList = () => penunjangStore.getActivePenunjangList();

  // ============================================
  // UTILITY FUNCTIONS
  // ============================================
  const getKlinikNameByKode = (kode) => {
    // Single source of truth: selalu ambil dari clinicStore
    const clinic = clinicStore.getClinicByKode(kode);
    if (clinic) {
      return clinic.name;
    }
    // Fallback jika tidak ditemukan
    return kode;
  };

  const getPenunjangNameByKode = (kode) => {
    return penunjangStore.getPenunjangNameByKode(kode);
  };

  return {
    // ============================================
    // KLINIK
    // ============================================
    // State
    klinikData,
    klinikList,
    
    // Actions
    addKlinik,
    updateKlinik,
    deleteKlinik,
    getKlinikById,
    getKlinikByKode,

    // ============================================
    // LOKET
    // ============================================
    // State
    loketData,
    availableServices,

    // Actions
    addLoket,
    updateLoket,
    deleteLoket,
    getLoketById,

    // ============================================
    // RUANG
    // ============================================
    // State
    ruangData,
    totalKlinikRuang,
    totalRuangan,
    getAllRuangList,

    // Actions
    addRuang,
    updateRuang,
    deleteRuang,
    getRuangByKlinik,

    // ============================================
    // PENUNJANG
    // ============================================
    // State
    penunjangData,
    totalPenunjang,
    activePenunjang,
    penunjangMedis,
    penunjangNonMedis,
    penunjangList,

    // Actions
    addPenunjang,
    updatePenunjang,
    deletePenunjang,
    getPenunjangById,
    getPenunjangByKode,
    getActivePenunjangList,

    // ============================================
    // UTILITIES
    // ============================================
    getKlinikNameByKode,
    getPenunjangNameByKode,
  };
}, {
  // NOTE: masterStore tidak perlu persist karena semua data sudah di-persist di stores masing-masing
  persist: false,
});
