import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useVerificationStore = defineStore('verification', () => {
    // State
    const patients = ref([]);
    const loading = ref(false);
    const error = ref(null);

    // API Base URL
    // API Configuration
    const config = useRuntimeConfig();
    
    // Helper to get API Base URL safely
    const getApiBaseUrl = () => {
        const url = config.public.verificationApiBaseUrl;
        if (!url) {
            console.warn('verificationApiBaseUrl is undefined in runtimeConfig, using fallback');
            return 'http://10.10.123.140:8089/api/v1';
        }
        return url;
    };

    // Helpers
    const formatAddress = (p) => {
        return [p.alamat, p.namakelurahan, p.namakecamatan, p.nama_kota, p.namaprovinsi]
            .filter(Boolean)
            .join(', ');
    };

    const mapPatientData = (apiData) => {
        return {
            nama: apiData.nama,
            rm: apiData.nomr,
            alamat: formatAddress(apiData),
            telepon: apiData.notlp || '',
            status: apiData.notlp ? 'Terverifikasi' : 'Belum Terverifikasi',
            originalData: apiData // Keep original data if needed
        };
    };

    // Actions
    const fetchAllPatients = async () => {
        loading.value = true;
        error.value = null;
        const API_BASE_URL = getApiBaseUrl();
        console.log('Fetching all patients from:', `${API_BASE_URL}/pasien/search`);
        try {
            const result = await $fetch(`${API_BASE_URL}/pasien/search`, {
                params: { nama: 'AA' }
            });
            
            if (result) {
                const data = result.data || result;
                const results = Array.isArray(data) ? data : [];
                patients.value = results.map(mapPatientData);
            } else {
                patients.value = [];
            }
        } catch (e) {
            console.error('Exception fetching all patients:', e);
            error.value = e;
            patients.value = [];
        } finally {
            loading.value = false;
        }
    };

    const fetchPatientByRm = async (rm) => {
        loading.value = true;
        error.value = null;
        const API_BASE_URL = getApiBaseUrl();
        try {
            const result = await $fetch(`${API_BASE_URL}/pasien/${rm}`);
            
            if (result) {
                const data = result.data || result;
                if (data && data.nomr) {
                    patients.value = [mapPatientData(data)];
                } else {
                    patients.value = [];
                }
            } else {
                patients.value = [];
            }
        } catch (e) {
            console.error('Exception fetching patient by RM:', e);
            error.value = e;
            patients.value = [];
        } finally {
            loading.value = false;
        }
    };

    const searchPatientsByName = async (name) => {
        loading.value = true;
        error.value = null;
        const API_BASE_URL = getApiBaseUrl();
        try {
            const result = await $fetch(`${API_BASE_URL}/pasien/search`, {
                params: { nama: name }
            });

            if (result) {
                const data = result.data || result;
                const results = Array.isArray(data) ? data : [];
                patients.value = results.map(mapPatientData);
            } else {
                patients.value = [];
            }
        } catch (e) {
            console.error('Exception searching patients:', e);
            error.value = e;
            patients.value = [];
        } finally {
            loading.value = false;
        }
    };

    const clearPatients = () => {
        patients.value = [];
        error.value = null;
    };
    
    // Optimistic update for verification status
    const updatePatientVerification = (rm, phoneNumber) => {
        const patientIndex = patients.value.findIndex(p => p.rm === rm);
        if (patientIndex !== -1) {
             patients.value[patientIndex].status = 'Terverifikasi';
             patients.value[patientIndex].telepon = phoneNumber;
        }
    }

    return {
        patients,
        loading,
        error,
        fetchAllPatients,
        fetchPatientByRm,
        searchPatientsByName,
        clearPatients,
        updatePatientVerification
    };
});
