<script setup lang="ts">
import BaseBreadcrumb from '@/components/shared/BaseBreadcrumb.vue';
import BiodataPasien from '@/components/pendaftaran/BiodataPasien.vue';
import MedisPasien from '@/components/pendaftaran/MedisPasien.vue';
import RencanaOperasi from '@/components/pendaftaran/RencanaOperasi.vue';
import StatusPasienOperasi from '@/components/pendaftaran/StatusPasienOperasi.vue';
import { usePendaftaranStore } from '@/store/pendaftaran';
import { storeToRefs } from 'pinia';
import type { PageMode } from '~/types/common';

definePageMeta({
    middleware: 'auth'
});

const router = useRouter();
const route = useRoute();
const pendaftaranStore = usePendaftaranStore();

// Use storeToRefs to make state reactive
const {
    formData,
    diagnosisItems,
    tindakanItems,
    rencanaOperasiData,
    dokterPelaksanaItems,
    statusPasienData,
    loading,
    snackbar,
    snackbarMessage,
    snackbarColor
} = storeToRefs(pendaftaranStore);

const form = ref();
const valid = ref(true);

// Detect mode from route query
const mode = computed<PageMode>(() => {
    const modeParam = route.query.mode as string;
    if (modeParam === 'edit') return 'edit';
    if (modeParam === 'view') return 'view';
    return 'create';
});

// Computed readonly state
const isReadonly = computed(() => mode.value === 'view');

// Dynamic page title based on mode
const pageTitle = computed(() => {
    switch (mode.value) {
        case 'edit':
            return 'Edit Pendaftaran Antrean Operasi';
        case 'view':
            return 'Detail Pendaftaran Antrean Operasi';
        default:
            return 'Tambah Pendaftaran Antrean Operasi';
    }
});

// Dynamic breadcrumbs based on mode
const breadcrumbText = computed(() => {
    switch (mode.value) {
        case 'edit':
            return 'Edit Pendaftaran';
        case 'view':
            return 'Detail Pendaftaran';
        default:
            return 'Tambah Pendaftaran';
    }
});

const page = ref({ title: pageTitle });
const breadcrumbs = computed(() => [
    {
        text: 'Antrean',
        disabled: false,
        href: '/antrean/all'
    },
    {
        text: breadcrumbText.value,
        disabled: true,
        href: '#'
    }
]);

// Auto-select spesialis dan sub spesialis dari query parameter
onMounted(async () => {
    // Reset form terlebih dahulu
    pendaftaranStore.resetForm();
    
    // Set default tanggal daftar ke now
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    pendaftaranStore.rencanaOperasiData.tanggalDaftar = `${year}-${month}-${day}T${hours}:${minutes}`;
    
    // Auto-select spesialis dan sub spesialis jika ada query parameter
    const kodeSpesialis = route.query.kodeSpesialis as string;
    const kodeSubSpesialis = route.query.kodeSubSpesialis as string;
    
    await pendaftaranStore.initializeFromQuery(kodeSpesialis, kodeSubSpesialis);
});

const handleSimpan = async () => {
    const { valid } = await form.value.validate();
    
    if (valid) {
        // Validate using store method
        const validation = pendaftaranStore.validateForm();
        
        if (!validation.valid) {
            const errorMessage = `Data berikut harus diisi:\n\n${validation.errors.join(', ')}`;
            pendaftaranStore.showSnackbar(errorMessage, 'error');
            return;
        }
        
        // Submit form using store action
        const result = await pendaftaranStore.submitForm();
        
        if (result.success) {
            // Navigate back or to list page
            // router.push('/antrean/list');
        }
    } else {
        // Validate using store method
        const validation = pendaftaranStore.validateForm();
        const errorMessage = `Data berikut harus diisi:\n\n${validation.errors.join(', ')}`;
        pendaftaranStore.showSnackbar(errorMessage, 'error');
    }
};

const handleReset = () => {
    if (confirm('Apakah Anda yakin ingin mereset form?')) {
        form.value.reset();
        pendaftaranStore.resetForm();
         // Set default tanggal daftar ke now
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        pendaftaranStore.rencanaOperasiData.tanggalDaftar = `${year}-${month}-${day}T${hours}:${minutes}`;
        
    }
};

const handleKembali = () => {
    router.back();
};
</script>
<template>
    <v-form ref="form" v-model="valid" lazy-validation>
        <v-row>
            <v-col cols="12">
                <BaseBreadcrumb :button-back="true" :title="pageTitle" :breadcrumbs="breadcrumbs"></BaseBreadcrumb>
            </v-col>
            
            <!-- Data Biodata Pasien -->
        <v-col cols="12">
            <BiodataPasien v-model="formData" :readonly="isReadonly" />
        </v-col>

        <!-- Data Medis Pasien -->
        <v-col cols="12">
            <MedisPasien 
                v-model:diagnosis-items="diagnosisItems"
                v-model:tindakan-items="tindakanItems"
                :readonly="isReadonly"
            />
        </v-col>

        <!-- Data Rencana Operasi -->
        <v-col cols="12">
            <RencanaOperasi 
                v-model:rencana-operasi-data="rencanaOperasiData"
                v-model:dokter-pelaksana-items="dokterPelaksanaItems"
                :readonly="isReadonly"
            />
        </v-col>

        <!-- Data Status Pasien Operasi -->
        <v-col cols="12">
            <StatusPasienOperasi 
                v-model="statusPasienData" 
                :readonly="isReadonly"
                :rencana-operasi-data="rencanaOperasiData"
            />
        </v-col>

        <!-- Action Buttons -->
        <v-col cols="12">
            <v-card elevation="10">
                <v-card-text>
                    <div class="d-flex justify-end ga-3">
                        <v-btn 
                            color="default" 
                            size="large" 
                            variant="outlined"
                            prepend-icon="mdi-arrow-left"
                            @click="handleKembali"
                        >
                            Kembali
                        </v-btn>
                        <v-btn 
                            v-if="!isReadonly"
                            color="error" 
                            size="large" 
                            variant="outlined"
                            prepend-icon="mdi-reload"
                            @click="handleReset"
                        >
                            Reset
                        </v-btn>
                        <v-btn 
                            v-if="!isReadonly"
                            color="primary" 
                            size="large"
                            :loading="loading"
                            @click="handleSimpan"
                            prepend-icon="mdi-content-save"
                        >
                            Simpan
                        </v-btn>
                    </div>
                </v-card-text>
            </v-card>
        </v-col>
        </v-row>
    </v-form>

    <!-- Snackbar for notifications -->
    <v-snackbar
        v-model="snackbar"
        :color="snackbarColor"
        :timeout="3000"
        location="top"
    >
        {{ snackbarMessage }}
        <template #actions>
            <v-btn
                variant="text"
                @click="pendaftaranStore.closeSnackbar()"
            >
                Close
            </v-btn>
        </template>
    </v-snackbar>
</template>