<script setup lang="ts">
import { apiGomed } from '@/services/api';
import type { Props } from '~/types/common';
import type { DiagnosisItem, TindakanItem, DiagnosisApiData, TindakanApiData } from '~/types/pendaftaran';

const props = withDefaults(defineProps<Props>(), {
    readonly: false
});

const diagnosisItems = defineModel<DiagnosisItem[]>('diagnosisItems', { required: true });
const tindakanItems = defineModel<TindakanItem[]>('tindakanItems', { required: true });

// Modal state for diagnosis
const showDiagnosisModal = ref(false);
const diagnosisForm = ref<DiagnosisItem>({
    kodeDiagnosa: '',
    diagnosa: '',
    jenisDiagnosa: 'utama'
});
const editingDiagnosisIndex = ref<number | null>(null);
const diagnosisList = ref<DiagnosisApiData[]>([]);
const loadingDiagnosis = ref(false);
const diagnosisSearchTimeout = ref<NodeJS.Timeout | null>(null);
const diagnosisSearchPerformed = ref(false);

// Search diagnosis from API
const searchDiagnosis = async (search: string) => {
    if (!search || search.length < 3) {
        diagnosisList.value = [];
        diagnosisSearchPerformed.value = false;
        return;
    }

    loadingDiagnosis.value = true;
    diagnosisSearchPerformed.value = false;
    
    try {
        const response = await apiGomed.get('/account/caridiagnosa', {
            params: {
                limit: 100,
                search: search
            }
        });

        if (response.data?.response) {
            diagnosisList.value = response.data.response;
            diagnosisSearchPerformed.value = true;
        }
    } catch (error) {
        console.error('Error fetching diagnosis:', error);
        diagnosisList.value = [];
        diagnosisSearchPerformed.value = true;
    } finally {
        loadingDiagnosis.value = false;
    }
};

// Handle diagnosis search input with debounce
const handleDiagnosisSearchInput = (value: string) => {
    if (diagnosisSearchTimeout.value) {
        clearTimeout(diagnosisSearchTimeout.value);
    }

    diagnosisSearchTimeout.value = setTimeout(() => {
        searchDiagnosis(value);
    }, 500);
};

// Autocomplete options for diagnosis
const diagnosisOptions = computed(() => {
    return diagnosisList.value.map(d => ({
        title: d.select,
        value: d.kodeicd,
        diagnosa: d.keterangan
    }));
});

// Modal state for tindakan
const showTindakanModal = ref(false);
const tindakanForm = ref<TindakanItem>({
    kodeTindakan: '',
    tindakan: '',
    tindakanTambahan: ''
});
const editingTindakanIndex = ref<number | null>(null);
const tindakanList = ref<TindakanApiData[]>([]);
const loadingTindakan = ref(false);
const tindakanSearchTimeout = ref<NodeJS.Timeout | null>(null);
const tindakanSearchPerformed = ref(false);

// Search tindakan from API
const searchTindakan = async (search: string) => {
    if (!search || search.length < 3) {
        tindakanList.value = [];
        tindakanSearchPerformed.value = false;
        return;
    }

    loadingTindakan.value = true;
    tindakanSearchPerformed.value = false;
    
    try {
        const response = await apiGomed.get('/account/cariprosedur', {
            params: {
                limit: 100,
                search: search
            }
        });

        if (response.data?.response) {
            tindakanList.value = response.data.response;
            tindakanSearchPerformed.value = true;
        }
    } catch (error) {
        console.error('Error fetching tindakan:', error);
        tindakanList.value = [];
        tindakanSearchPerformed.value = true;
    } finally {
        loadingTindakan.value = false;
    }
};

// Handle tindakan search input with debounce
const handleTindakanSearchInput = (value: string) => {
    if (tindakanSearchTimeout.value) {
        clearTimeout(tindakanSearchTimeout.value);
    }

    tindakanSearchTimeout.value = setTimeout(() => {
        searchTindakan(value);
    }, 500);
};

// Autocomplete options for tindakan
const tindakanOptions = computed(() => {
    return tindakanList.value.map(t => ({
        title: t.select,
        value: t.kode,
        tindakan: t.keterangan
    }));
});

// Initialize arrays if not already
if (!Array.isArray(diagnosisItems.value)) {
    diagnosisItems.value = [];
}
if (!Array.isArray(tindakanItems.value)) {
    tindakanItems.value = [];
}

const openDiagnosisModal = () => {
    diagnosisForm.value = {
        kodeDiagnosa: '',
        diagnosa: '',
        jenisDiagnosa: 'utama'
    };
    editingDiagnosisIndex.value = null;
    showDiagnosisModal.value = true;
};

const editDiagnosis = (index: number) => {
    diagnosisForm.value = { ...diagnosisItems.value[index] };
    editingDiagnosisIndex.value = index;
    showDiagnosisModal.value = true;
};

const saveDiagnosis = () => {
    if (!diagnosisForm.value.kodeDiagnosa.trim() || !diagnosisForm.value.diagnosa.trim()) return;
    
    if (editingDiagnosisIndex.value !== null) {
        diagnosisItems.value[editingDiagnosisIndex.value] = { ...diagnosisForm.value };
    } else {
        diagnosisItems.value.push({ ...diagnosisForm.value });
    }
    
    showDiagnosisModal.value = false;
    diagnosisForm.value = {
        kodeDiagnosa: '',
        diagnosa: '',
        jenisDiagnosa: 'utama'
    };
    editingDiagnosisIndex.value = null;
};

const deleteDiagnosis = (index: number) => {
    diagnosisItems.value.splice(index, 1);
};

// Auto-fill diagnosis when code is selected
const handleKodeDiagnosaChange = (kode: string) => {
    const found = diagnosisList.value.find(d => d.kodeicd === kode);
    if (found) {
        diagnosisForm.value.diagnosa = found.keterangan;
        // Keep jenisDiagnosa as is or default to current value
    }
};

const openTindakanModal = () => {
    tindakanForm.value = {
        kodeTindakan: '',
        tindakan: '',
        tindakanTambahan: ''
    };
    editingTindakanIndex.value = null;
    showTindakanModal.value = true;
};

const editTindakan = (index: number) => {
    tindakanForm.value = { ...tindakanItems.value[index] };
    editingTindakanIndex.value = index;
    showTindakanModal.value = true;
};

const saveTindakan = () => {
    if (!tindakanForm.value.kodeTindakan.trim() || !tindakanForm.value.tindakan.trim()) return;
    
    if (editingTindakanIndex.value !== null) {
        tindakanItems.value[editingTindakanIndex.value] = { ...tindakanForm.value };
    } else {
        tindakanItems.value.push({ ...tindakanForm.value });
    }
    
    showTindakanModal.value = false;
    tindakanForm.value = {
        kodeTindakan: '',
        tindakan: '',
        tindakanTambahan: ''
    };
    editingTindakanIndex.value = null;
};

const deleteTindakan = (index: number) => {
    tindakanItems.value.splice(index, 1);
};

// Auto-fill tindakan when code is selected
const handleKodeTindakanChange = (kode: string) => {
    const found = tindakanList.value.find(t => t.kode === kode);
    if (found) {
        tindakanForm.value.tindakan = found.keterangan;
        // Keep tindakanTambahan as is or user can input manually
    }
};
</script>

<template>
    <v-card elevation="10">
        <v-card-item>
            <h5 class="text-h5 font-weight-bold">Data Medis Pasien</h5>
        </v-card-item>
        <v-divider></v-divider>
        <v-card-text>
            <!-- Diagnosa -->
            <div class="mb-6">
                <h6 class="text-h6 font-weight-medium mb-3">Diagnosa</h6>
                <v-card variant="outlined" class="mb-3">
                    <v-alert
                        v-if="diagnosisItems.length === 0"
                        type="info"
                        variant="tonal"
                        density="compact"
                    >
                        <div class="d-flex align-center">
                            <span>No items</span>
                        </div>
                    </v-alert>
                    <v-list v-else density="compact">
                        <v-list-item
                            v-for="(item, index) in diagnosisItems"
                            :key="index"
                            class="px-4 mb-2"
                            @click="!readonly && editDiagnosis(index)"
                            :style="readonly ? 'cursor: default;' : 'cursor: pointer;'"
                        >
                            <template #default>
                                <div class="d-flex align-center justify-space-between w-100">
                                    <div>
                                        <div class="font-weight-medium">{{ item.kodeDiagnosa }} - {{ item.diagnosa }}</div>
                                        <div class="text-caption text-medium-emphasis">
                                            {{ item.jenisDiagnosa === 'utama' ? 'Diagnosa Utama' : 'Diagnosa Tambahan' }}
                                        </div>
                                    </div>
                                    <v-btn
                                        v-if="!readonly"
                                        icon
                                        size="small"
                                        variant="text"
                                        color="error"
                                        @click.stop="deleteDiagnosis(index)"
                                    >
                                        <v-icon>mdi-delete</v-icon>
                                    </v-btn>
                                </div>
                            </template>
                        </v-list-item>
                    </v-list>
                </v-card>
                <v-btn v-if="!readonly" color="primary" prepend-icon="mdi-plus" @click="openDiagnosisModal">
                    Tambah Diagnosa
                </v-btn>
            </div>

            <!-- Tindakan -->
            <div>
                <h6 class="text-h6 font-weight-medium mb-3">Tindakan</h6>
                <v-card variant="outlined" class="mb-3">
                    <v-alert
                        v-if="tindakanItems.length === 0"
                        type="info"
                        variant="tonal"
                        density="compact"
                    >
                        <div class="d-flex align-center">
                            <span>No items</span>
                        </div>
                    </v-alert>
                    <v-list v-else density="compact">
                        <v-list-item
                            v-for="(item, index) in tindakanItems"
                            :key="index"
                            class="px-4 mb-2"
                            @click="!readonly && editTindakan(index)"
                            :style="readonly ? 'cursor: default;' : 'cursor: pointer;'"
                        >
                            <template #default>
                                <div class="d-flex align-center justify-space-between w-100">
                                    <div>
                                        <div class="font-weight-medium">{{ item.kodeTindakan }} - {{ item.tindakan }}</div>
                                        <div v-if="item.tindakanTambahan" class="text-caption text-medium-emphasis">
                                            {{ item.tindakanTambahan }}
                                        </div>
                                    </div>
                                    <v-btn
                                        v-if="!readonly"
                                        icon
                                        size="small"
                                        variant="text"
                                        color="error"
                                        @click.stop="deleteTindakan(index)"
                                    >
                                        <v-icon>mdi-delete</v-icon>
                                    </v-btn>
                                </div>
                            </template>
                        </v-list-item>
                    </v-list>
                </v-card>
                <v-btn v-if="!readonly" color="primary" prepend-icon="mdi-plus" @click="openTindakanModal">
                    Tambah Tindakan
                </v-btn>
            </div>
        </v-card-text>
    </v-card>

    <!-- Modal for adding diagnosis -->
    <v-dialog v-model="showDiagnosisModal" max-width="800px">
        <v-card>
            <v-card-title class="d-flex align-center justify-space-between pa-4">
                <div class="d-flex align-center">
                    <v-icon class="mr-3">mdi-package-variant</v-icon>
                    <span class="text-h6">{{ editingDiagnosisIndex !== null ? 'Edit' : 'Tambah' }} Item Data Diagnosa Pasien Operasi</span>
                </div>
                <v-btn
                    icon
                    variant="text"
                    @click="showDiagnosisModal = false"
                >
                    <v-icon>mdi-close</v-icon>
                </v-btn>
            </v-card-title>
            
            <v-divider></v-divider>
            
            <v-card-text class="pa-6">
                <v-row>
                    <!-- Kode Diagnosa -->
                    <v-col cols="12" md="6">
                        <v-label class="mb-2 font-weight-medium">Kode Diagnosa</v-label>
                        <v-autocomplete
                            v-model="diagnosisForm.kodeDiagnosa"
                            :items="diagnosisOptions"
                            placeholder="Ketik minimal 3 karakter untuk mencari diagnosa"
                            variant="outlined"
                            density="comfortable"
                            hide-details="auto"
                            :loading="loadingDiagnosis"
                            no-filter
                            clearable
                            @update:search="handleDiagnosisSearchInput"
                            @update:model-value="handleKodeDiagnosaChange"
                        >
                            <template #no-data>
                                <v-list-item>
                                    <v-list-item-title>
                                        {{ diagnosisSearchPerformed && diagnosisList.length === 0 
                                            ? 'Data tidak ditemukan' 
                                            : 'Ketik minimal 3 karakter untuk mencari diagnosa' }}
                                    </v-list-item-title>
                                </v-list-item>
                            </template>
                        </v-autocomplete>
                    </v-col>

                    <!-- Diagnosa -->
                    <v-col cols="12" md="6">
                        <v-label class="mb-2 font-weight-medium">Diagnosa</v-label>
                        <v-text-field
                            v-model="diagnosisForm.diagnosa"
                            variant="outlined"
                            density="comfortable"
                            readonly
                            bg-color="grey-lighten-3"
                            hide-details="auto"
                        ></v-text-field>
                    </v-col>

                    <!-- Jenis Diagnosa -->
                    <v-col cols="12">
                        <v-label class="mb-2 font-weight-medium">Jenis Diagnosa</v-label>
                        <v-radio-group v-model="diagnosisForm.jenisDiagnosa" inline hide-details="auto">
                            <v-radio label="Diagnosa Utama" value="utama" color="primary"></v-radio>
                            <v-radio label="Diagnosa Tambahan" value="tambahan" color="primary"></v-radio>
                        </v-radio-group>
                    </v-col>
                </v-row>
            </v-card-text>
            
            <v-divider></v-divider>
            
            <v-card-actions class="pa-4 justify-end">
                <v-btn
                    color="primary"
                    variant="flat"
                    @click="saveDiagnosis"
                    :disabled="!diagnosisForm.kodeDiagnosa.trim() || !diagnosisForm.diagnosa.trim()"
                >
                    <v-icon start>mdi-check</v-icon>
                    Simpan
                </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>

    <!-- Modal for adding tindakan -->
    <v-dialog v-model="showTindakanModal" max-width="800px">
        <v-card>
            <v-card-title class="d-flex align-center justify-space-between pa-4">
                <div class="d-flex align-center">
                    <v-icon class="mr-3">mdi-package-variant</v-icon>
                    <span class="text-h6">{{ editingTindakanIndex !== null ? 'Edit' : 'Tambah' }} Item Data Tindakan Pasien Operasi</span>
                </div>
                <v-btn
                    icon
                    variant="text"
                    @click="showTindakanModal = false"
                >
                    <v-icon>mdi-close</v-icon>
                </v-btn>
            </v-card-title>
            
            <v-divider></v-divider>
            
            <v-card-text class="pa-6">
                <v-row>
                    <!-- Kode Tindakan -->
                    <v-col cols="12" md="6">
                        <v-label class="mb-2 font-weight-medium">Kode Tindakan</v-label>
                        <v-autocomplete
                            v-model="tindakanForm.kodeTindakan"
                            :items="tindakanOptions"
                            placeholder="Ketik minimal 3 karakter untuk mencari tindakan"
                            variant="outlined"
                            density="comfortable"
                            hide-details="auto"
                            :loading="loadingTindakan"
                            no-filter
                            clearable
                            @update:search="handleTindakanSearchInput"
                            @update:model-value="handleKodeTindakanChange"
                        >
                            <template #no-data>
                                <v-list-item>
                                    <v-list-item-title>
                                        {{ tindakanSearchPerformed && tindakanList.length === 0 
                                            ? 'Data tidak ditemukan' 
                                            : 'Ketik minimal 3 karakter untuk mencari tindakan' }}
                                    </v-list-item-title>
                                </v-list-item>
                            </template>
                        </v-autocomplete>
                    </v-col>

                    <!-- Tindakan -->
                    <v-col cols="12" md="6">
                        <v-label class="mb-2 font-weight-medium">Tindakan</v-label>
                        <v-text-field
                            v-model="tindakanForm.tindakan"
                            variant="outlined"
                            density="comfortable"
                            readonly
                            bg-color="grey-lighten-3"
                            hide-details="auto"
                        ></v-text-field>
                    </v-col>

                    <!-- Tindakan Tambahan -->
                    <v-col cols="12">
                        <v-label class="mb-2 font-weight-medium">Tindakan Tambahan</v-label>
                        <v-text-field
                            v-model="tindakanForm.tindakanTambahan"
                            placeholder="Prosedur Tindakan Tambahan"
                            variant="outlined"
                            density="comfortable"
                            hide-details="auto"
                        ></v-text-field>
                    </v-col>
                </v-row>
            </v-card-text>
            
            <v-divider></v-divider>
            
            <v-card-actions class="pa-4 justify-end">
                <v-btn
                    color="primary"
                    variant="flat"
                    @click="saveTindakan"
                    :disabled="!tindakanForm.kodeTindakan.trim() || !tindakanForm.tindakan.trim()"
                >
                    <v-icon start>mdi-check</v-icon>
                    Simpan
                </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>
