<template>
  <v-dialog v-model="dialog" max-width="500">
    <v-card>
      <v-card-title class="d-flex justify-space-between align-center">
        <span class="text-h5">Tambah Penjamin Asuransi</span>
        <v-btn icon="mdi-close" variant="text" @click="closeDialog"></v-btn>
      </v-card-title>
      <v-divider></v-divider>

      <v-card-text class="pa-4">
        <v-form ref="form" v-model="isValid" @submit.prevent="submitForm">

          <v-select
              v-model="selectedType"
              :items="optionInsuranceType"
              label="Tipe Penjamin *"
              :rules = "requiredRules"
              variant="outlined"
              density="compact"
              class="mb-3"
          ></v-select>

          <v-text-field
              v-model="formData.nama"
              label="Nama Penjamin *"
              :rules="textRules"
              variant="outlined"
              density="compact"
              class="mb-3"
          ></v-text-field>

          <v-text-field
              v-model="formData.contact"
              label="No Telp *"
              :rules="phoneRules"
              variant="outlined"
              density="compact"
              class="mb-3"
              hint="Masukkan hanya angka, min 9 - max 15 digit."
          ></v-text-field>

          <v-textarea
              v-model="formData.alamat"
              label="Alamat Kantor"
              variant="outlined"
              density="compact"
              rows="3"
              class="mb-3"
          ></v-textarea>

          <v-switch
              v-model="formData.isActive"
              label="Aktifkan Sekarang"
              color="success"
              density="compact"
              hide-details
              class="mb-4"
          ></v-switch>

          <small class="text-caption text-error">* Bidang yang wajib diisi</small>
        </v-form>
      </v-card-text>

      <v-card-actions class="pa-4 pt-0">
        <v-spacer></v-spacer>
        <v-btn color="error" variant="flat" @click="closeDialog">Batal</v-btn>

        <v-btn
            color="primary"
            variant="flat"
            :disabled="!isValid"
            @click="submitForm"
        >
          Simpan Data
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import {ref, watch} from 'vue';

const form = ref(null);
const isValid = ref(false);

const {phoneRules, textRules, requiredRules} = useValidation();

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },

  guarantorType: {
    type: String,
    default: '--Silahkan Pilih--'
  }
});


const selectedType = ref(props.guarantorType);

// Pantau perubahan agar tidak terkunci di nilai pertama (null/default)
watch(() => props.guarantorType, (newVal) => {
  if (newVal) {
    selectedType.value = newVal;
  }
}, { immediate: true }); // immediate agar langsung sinkron saat awal


// Definisikan emit untuk mengirim event kembali ke parent
const emit = defineEmits(['update:modelValue', 'data-saved']);

// State lokal untuk dialog (sinkronisasi dengan modelValue)
const dialog = ref(props.modelValue);

const optionInsuranceType = [
  {title: 'Asuransi', value: 'insurance'},
  {title: 'Perusahaan', value: 'company'}
];

// Sinkronisasi dialog dengan prop modelValue
watch(() => props.modelValue, (newVal) => {
  dialog.value = newVal;
});
watch(dialog, (newVal) => {
  emit('update:modelValue', newVal);
});


const defaultFormData = {
  nama: '',
  alamat: '',
  isActive: true,
};
const formData = ref({});

function closeDialog() {
  dialog.value = false;
  // Reset formulir setelah ditutup
  Object.assign(formData.value, defaultFormData);
  if (form.value) {
    form.value.resetValidation();
  }
}

async function submitForm() {
  // Validasi manual
  const {valid} = await form.value.validate();

  if (valid) {
    console.log('Data yang akan dikirim:', formData.value);

    // TODO: Di sini Anda akan memanggil API untuk menyimpan data

    // Emit event ke parent bahwa data telah tersimpan
    emit('data-saved', formData.value);

    // Tutup dialog
    closeDialog();
  }
}


// Ekspos fungsi closeDialog agar dapat dipanggil dari luar (jika diperlukan)
defineExpose({
  closeDialog,
});
</script>
