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

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

const formData = defineModel<{
    noRekamMedis: string;
    noKtp: string;
    namaPasien: string;
    jenisKelamin: string;
    tanggalLahir: string;
    umur: string;
    alamat: string;
    nomorTelepon: string[];
}>({ required: true });

const rules = {
    required: (value: string) => !!value || 'Field ini wajib diisi'
};

// Autocomplete state
const patientItems = ref<PatientData[]>([]);
const loadingPatients = ref(false);
const searchTimeout = ref<NodeJS.Timeout | null>(null);
const selectedPatient = ref<PatientData | null>(null);

// Search patients by RM number or name
const searchPatients = async (search: string) => {
    if (!search || search.length < 3) {
        patientItems.value = [];
        return;
    }

    loadingPatients.value = true;
    
    try {
        const response = await apiGomed.get('/account/caripasienbynomorrm', {
            params: {
                limit: 10,
                search: search
            }
        });

        if (response.data?.response) {
            patientItems.value = response.data.response;
        }
    } catch (error) {
        console.error('Error fetching patients:', error);
        patientItems.value = [];
    } finally {
        loadingPatients.value = false;
    }
};

// Handle search input with debounce
const handleSearchInput = (value: string) => {
    if(value === formData.value.noRekamMedis) {
        patientItems.value = selectedPatient.value ? [selectedPatient.value] : [];
        return;
    }
    if (searchTimeout.value) {
        clearTimeout(searchTimeout.value);
    }

    searchTimeout.value = setTimeout(() => {
        searchPatients(value);
    }, 500);
};

// Handle patient selection
const handlePatientSelect = (patient: PatientData | null) => {
    if (patient) {
        selectedPatient.value = patient;
        formData.value.noRekamMedis = patient.nomr;
        formData.value.noKtp = patient.nik;
        formData.value.namaPasien = patient.nama;
        formData.value.jenisKelamin = patient.jeniskelamin;
        formData.value.tanggalLahir = patient.tgllahir;
        formData.value.umur = patient.dataumur.label;
        formData.value.alamat = patient.alamat;
    }
};

// Phone validation rules
const phoneLength = (value: string) => {
    if (!value) return true;
    // Hapus karakter non-angka sebelum menghitung panjang
    const length = value.replace(/[^0-9]/g, '').length;
    return (length >= 9 && length <= 15) || 'Nomor telepon harus antara 9 hingga 15 digit.';
};

const indonesianPhoneFormat = (value: string) => {
    if (!value) return true;
    // Pola: Harus dimulai dengan '08', diikuti 7 hingga 13 digit angka
    return /^08[0-9]{7,13}$/.test(value) || 'Format nomor telepon tidak valid (Contoh: 08xxxxxxxx).';
};

// Modal state
const showModal = ref(false);
const newPhoneNumber = ref('');
const editingIndex = ref<number | null>(null);
const phoneError = ref<string | boolean>(true);

// Initialize nomorTelepon as array if not already
if (!Array.isArray(formData.value.nomorTelepon)) {
    formData.value.nomorTelepon = [];
}

const openAddModal = () => {
    newPhoneNumber.value = '';
    editingIndex.value = null;
    phoneError.value = true;
    showModal.value = true;
};

const editPhoneNumber = (index: number) => {
    const phone = formData.value.nomorTelepon[index];
    newPhoneNumber.value = phone;
    editingIndex.value = index;
    phoneError.value = true;
    showModal.value = true;
};

// Handle only numeric input and validate
const handlePhoneInput = (event: Event) => {
    const input = event.target as HTMLInputElement;
    const value = input.value;
    
    // Only allow numbers
    const numericValue = value.replace(/\D/g, '');
    newPhoneNumber.value = numericValue;
    
    // Validate format and length
    const lengthValidation = phoneLength(numericValue);
    const formatValidation = indonesianPhoneFormat(numericValue);
    
    if (lengthValidation !== true) {
        phoneError.value = lengthValidation;
    } else if (formatValidation !== true) {
        phoneError.value = formatValidation;
    } else {
        phoneError.value = true;
    }
};

const savePhoneNumber = () => {
    if (!newPhoneNumber.value.trim()) return;
    
    // Validate before saving
    const lengthValidation = phoneLength(newPhoneNumber.value);
    const formatValidation = indonesianPhoneFormat(newPhoneNumber.value);
    
    if (lengthValidation !== true || formatValidation !== true) {
        return;
    }
    
    // Save directly as 08xxx format
    if (editingIndex.value !== null) {
        formData.value.nomorTelepon[editingIndex.value] = newPhoneNumber.value;
    } else {
        formData.value.nomorTelepon.push(newPhoneNumber.value);
    }
    
    showModal.value = false;
    newPhoneNumber.value = '';
    editingIndex.value = null;
    phoneError.value = true;
};

const deletePhoneNumber = (index: number) => {
    formData.value.nomorTelepon.splice(index, 1);
};
</script>

<template>
    <v-card elevation="10">
        <v-card-item>
            <h5 class="text-h5 font-weight-bold">Data Biodata Pasien</h5>
        </v-card-item>
        <v-divider></v-divider>
        <v-card-text>
            <v-row>
                <!-- No Rekam Medis -->
                <v-col cols="12" md="6">
                    <v-label class="mb-2 font-weight-medium">No Rekam Medis <span
                            class="text-error">*</span></v-label>
                    <v-autocomplete
                        v-model="formData.noRekamMedis"
                        :items="patientItems"
                        item-title="select"
                        item-value="nomr"
                        placeholder="Masukan Nomor RM / Nama Pasien"
                        variant="outlined"
                        density="comfortable"
                        :rules="[rules.required]"
                        hide-details="auto"
                        max="8"
                        :readonly="readonly"
                        :disabled="readonly"
                        :bg-color="readonly ? 'grey-lighten-3' : undefined"
                        :loading="loadingPatients"
                        no-filter
                        clearable
                        @update:search="handleSearchInput"
                        @update:model-value="(value: string) => {
                            const patient = patientItems.find(p => p.nomr === value);
                            handlePatientSelect(patient || null);
                        }"
                    >
                        <template #no-data>
                            <v-list-item>
                                <v-list-item-title>
                                    Ketik minimal 3 karakter untuk mencari pasien
                                </v-list-item-title>
                            </v-list-item>
                        </template>
                    </v-autocomplete>
                </v-col>

                <!-- No KTP -->
                <v-col cols="12" md="6">
                    <v-label class="mb-2 font-weight-medium">No Ktp</v-label>
                    <v-text-field v-model="formData.noKtp" variant="outlined" density="comfortable"
                     hide-details="auto" readonly style="background-color: #f5f5f5; border-radius: 4px;"></v-text-field>
                </v-col>

                <!-- Nama Pasien -->
                <v-col cols="12" md="6">
                    <v-label class="mb-2 font-weight-medium">Nama Pasien</v-label>
                    <v-text-field v-model="formData.namaPasien" variant="outlined" density="comfortable"
                        hide-details="auto" readonly style="background-color: #f5f5f5; border-radius: 4px;"></v-text-field>
                </v-col>

                <!-- Jenis Kelamin -->
                <v-col cols="12" md="6">
                    <v-label class="mb-2 font-weight-medium">Jenis Kelamin</v-label>
                    <v-radio-group readonly v-model="formData.jenisKelamin" inline hide-details="auto" :disabled="readonly">
                        <v-radio label="Laki-Laki" value="L" color="primary"></v-radio>
                        <v-radio label="Perempuan" value="P" color="primary"></v-radio>
                    </v-radio-group>
                </v-col>

                <!-- Tanggal Lahir -->
                <v-col cols="12" md="6">
                    <v-label class="mb-2 font-weight-medium">Tanggal Lahir</v-label>
                    <v-text-field v-model="formData.tanggalLahir" type="date" variant="outlined"
                        density="comfortable" hide-details="auto" readonly
                        style="background-color: #f5f5f5; border-radius: 4px;"></v-text-field>
                </v-col>

                <!-- Umur -->
                <v-col cols="12" md="6">
                    <v-label class="mb-2 font-weight-medium">Umur</v-label>
                    <v-text-field v-model="formData.umur" variant="outlined" density="comfortable"
                        hide-details="auto" readonly style="background-color: #f5f5f5; border-radius: 4px;"></v-text-field>
                </v-col>

                <!-- Alamat -->
                <v-col cols="12">
                    <v-label class="mb-2 font-weight-medium">Alamat</v-label>
                    <v-textarea v-model="formData.alamat" variant="outlined" rows="3" hide-details="auto"
                        readonly style="background-color: #f5f5f5; border-radius: 4px;"></v-textarea>
                </v-col>

                <!-- Nomor Telepon -->
                <v-col cols="12">
                    <v-label class="mb-2 font-weight-medium">Nomor Telepon</v-label>
                    
                    <!-- Alert when no phone numbers -->
                    <v-alert
                        v-if="formData.nomorTelepon.length === 0"
                        type="info"
                        variant="tonal"
                        class="mb-3"
                        density="compact"
                    >
                        <div class="d-flex align-center">
                            <span>No items</span>
                        </div>
                    </v-alert>

                    <!-- List of phone numbers -->
                    <v-list v-if="formData.nomorTelepon.length > 0" class="mb-3" density="compact">
                        <v-list-item
                            v-for="(phone, index) in formData.nomorTelepon"
                            :key="index"
                            class="px-4 mb-2"
                            border
                            @click="!readonly && editPhoneNumber(index)"
                            :style="readonly ? 'cursor: default;' : 'cursor: pointer;'"
                        >
                            <template #default>
                                <div class="d-flex align-center justify-space-between w-100">
                                    <span>{{ phone }}</span>
                                    <v-btn
                                        v-if="!readonly"
                                        icon
                                        size="small"
                                        variant="text"
                                        color="error"
                                        @click.stop="deletePhoneNumber(index)"
                                    >
                                        <v-icon>mdi-delete</v-icon>
                                    </v-btn>
                                </div>
                            </template>
                        </v-list-item>
                    </v-list>

                    <!-- Add Button -->
                    <v-btn
                        v-if="!readonly"
                        color="primary"
                        variant="flat"
                        prepend-icon="mdi-plus" 
                        @click="openAddModal"
                    >
                        Tambah Nomor Telepon
                    </v-btn>
                </v-col>
            </v-row>
        </v-card-text>
    </v-card>

    <!-- Modal for adding phone number -->
    <v-dialog v-model="showModal" max-width="600px">
        <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">{{ editingIndex !== null ? 'Edit' : 'Tambah' }} Item  Data Telepon Pasien Operasi</span>
                </div>
                <v-btn
                    icon
                    variant="text"
                    @click="showModal = false"
                >
                    <v-icon>mdi-close</v-icon>
                </v-btn>
            </v-card-title>
            
            <v-divider></v-divider>
            
            <v-card-text class="pa-6">
                <v-label class="mb-2 font-weight-medium">Nomor Telepon</v-label>
                <v-text-field
                    v-model="newPhoneNumber"
                    placeholder="Contoh: 08123456789"
                    variant="outlined"
                    density="comfortable"
                    type="tel"
                    @input="handlePhoneInput"
                    :error-messages="phoneError !== true ? [phoneError as string] : []"
                >
                </v-text-field>
                <div class="text-caption text-medium-emphasis mt-2">
                    Format: 08xxxxxxxxx (9-15 digit)
                </div>
            </v-card-text>
            
            <v-divider></v-divider>
            
            <v-card-actions class="pa-4 justify-end">
                <v-btn
                    color="primary"
                    variant="flat"
                    @click="savePhoneNumber"
                    :disabled="!newPhoneNumber.trim() || phoneError !== true"
                >
                    <v-icon start>mdi-check</v-icon>
                    Simpan
                </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>
