<template>
  <v-dialog
    v-model="isOpen"
    max-width="600px"
    persistent
    scrollable
  >
    <v-card class="patient-data-dialog" rounded="xl">
      <!-- Header -->
      <v-card-title class="dialog-header d-flex justify-space-between align-center px-4 py-3 text-white">
        <span class="text-subtitle-1 font-weight-medium">Data Pasien</span>
        <v-btn icon="mdi-close" variant="text" size="small" color="white" @click="closeDialog" />
      </v-card-title>

      <v-card-text class="pa-6">
        <!-- Antrean Number Info -->
        <div class="text-center mb-6">
          <div class="text-subtitle-1 text-grey-darken-1 mb-1">Nomor Antrian</div>
          <div class="text-h3 font-weight-bold mb-1">{{ antrianNumber }}</div>
          <div class="text-caption text-grey-darken-1 mb-2">
            Barcode: <span class="font-weight-bold">{{ patient?.barcode || '-' }}</span>
          </div>
          
          <div v-if="alreadyLinked || isLinked" class="text-success mt-3 text-body-1 font-weight-medium d-flex align-center justify-center">
            <v-icon start size="20" color="success">mdi-check-circle</v-icon>
            {{ isLinked ? 'Berhasil dihubungkan ke RM baru' : `Sudah terhubung dengan RM: ${patient?.noRM}` }}
          </div>
          <div v-else-if="searchError" class="text-error mt-3 text-body-1 font-weight-medium d-flex align-center justify-center">
            <v-icon start size="20">mdi-close-circle</v-icon>
            {{ searchError }}
          </div>
          <div v-else-if="!patientData" class="text-error mt-3 text-body-1 font-weight-medium d-flex align-center justify-center">
            <v-icon start size="20">mdi-alert-circle</v-icon>
            Nomor Antrean belum terhubung ke pasien
          </div>
        </div>

        <!-- Search Form -->
        <div class="form-section pa-5 border rounded-xl mb-6">
          <div class="section-title text-caption font-weight-bold mb-3 text-uppercase text-navy-custom" style="letter-spacing: 0.5px;">
            Hubungkan Antrean
          </div>
          <v-text-field
            v-model="searchQuery"
            placeholder="Cari Nomor BPJS atau Nomor RM atau NIK.."
            variant="outlined"
            density="comfortable"
            hide-details
            prepend-inner-icon="mdi-magnify"
            bg-color="white"
            class="search-input"
            @keyup.enter="searchPatient"
          >
            <template #append-inner>
              <div class="d-flex align-center h-100 pr-1">
                <v-btn
                  variant="flat"
                  class="search-btn bg-navy-custom text-white text-none font-weight-bold"
                  height="36"
                  min-width="80"
                  rounded="lg"
                  :loading="isLoading"
                  @click="searchPatient"
                >
                  Cari
                </v-btn>
              </div>
            </template>
          </v-text-field>
        </div>

        <!-- Patient Info Display -->
        <v-expand-transition>
          <div v-if="patientData" class="info-section">
            <div class="section-title text-caption font-weight-bold text-primary mb-3 text-uppercase">
              Informasi Data Diri
            </div>
            
            <div class="info-grid">
              <!-- Nama Lengkap -->
              <div class="info-field">
                <div class="text-caption text-grey-darken-1 mb-1">Nama Lengkap</div>
                <div class="info-box">{{ patientData.nama }}</div>
              </div>

              <!-- TTL -->
              <div class="info-field">
                <div class="text-caption text-grey-darken-1 mb-1">Tempat / Tanggal Lahir</div>
                <div class="info-box">{{ patientData.ttl }}</div>
              </div>

              <!-- Jenis Kelamin -->
              <div class="info-field">
                <div class="text-caption text-grey-darken-1 mb-1">Jenis Kelamin</div>
                <div class="info-box">{{ patientData.jenisKelamin }}</div>
              </div>

              <!-- No Telepon -->
              <div class="info-field">
                <div class="text-caption text-grey-darken-1 mb-1">Nomor Telepon</div>
                <div class="info-box">{{ patientData.noTelepon }}</div>
              </div>

              <!-- Alamat -->
              <div class="info-field full-width">
                <div class="text-caption text-grey-darken-1 mb-1">Alamat</div>
                <div class="info-box">{{ patientData.alamat }}</div>
              </div>
            </div>
          </div>
        </v-expand-transition>
      </v-card-text>

      <!-- Footer Actions -->
      <v-card-actions v-if="patientData" class="pa-4 bg-grey-lighten-4 justify-end">
        <v-btn
          variant="flat"
          class="bg-navy-custom text-white px-6 text-none"
          prepend-icon="mdi-sync"
          :loading="isLinking"
          @click="linkPatient"
        >
          Hubungkan
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';

const props = defineProps<{
  modelValue: boolean;
  patient: any;
}>();

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void;
  (e: 'linked'): void;
}>();

// State
const isOpen = ref(props.modelValue);
const searchQuery = ref('');
const isLoading = ref(false);
const isLinking = ref(false);
const isLinked = ref(false);
const searchError = ref('');

const antrianNumber = computed(() => {
  return props.patient?.noAntrian ? props.patient.noAntrian.split(' |')[0] : '';
});

const alreadyLinked = computed(() => {
  return !!props.patient?.noRM;
});

// Tipe data mock
interface MockPatient {
  nama: string;
  ttl: string;
  jenisKelamin: string;
  noTelepon: string;
  alamat: string;
}

const patientData = ref<MockPatient | null>(null);

// Watchers
watch(() => props.modelValue, (newVal) => {
  isOpen.value = newVal;
  if (newVal) {
    // Reset state saat modal dibuka
    searchQuery.value = '';
    patientData.value = null;
    isLinked.value = false;
    searchError.value = '';
  }
});

watch(isOpen, (newVal) => {
  emit('update:modelValue', newVal);
});

// Methods
const resetState = () => {
  searchQuery.value = '';
  patientData.value = null;
  isLinked.value = false;
  isLoading.value = false;
  isLinking.value = false;
};

const closeDialog = () => {
  isOpen.value = false;
};

/**
 * Simulasi pencarian data pasien ke SIMRS.
 * NANTI BISA DIGANTI DENGAN $fetch KE SERVICE API ASLI.
 */
const searchPatient = async () => {
  if (!searchQuery.value.trim()) return;

  isLoading.value = true;
  patientData.value = null;

  try {
    // Reset state error sebelum pencarian
    searchError.value = '';
    
    // TODO: Ganti URL '/api/simrs/patient/' di bawah ini dengan URL API Service SIMRS yang sebenarnya
    const response = await $fetch(`/api/simrs/patient/${searchQuery.value}`);
    
    // @ts-ignore
    patientData.value = response.data;
  } catch (error: any) {
    console.error('Gagal mencari data pasien:', error);
    searchError.value = error.data?.statusMessage || `Pasien dengan nomor ${searchQuery.value} tidak ditemukan.`;
  } finally {
    isLoading.value = false;
  }
};

/**
 * Simulasi menghubungkan nomor antrean dengan data pasien di SIMRS.
 */
const linkPatient = async () => {
  isLinking.value = true;

  try {
    // TODO: Ganti dengan API call asli untuk menghubungkan antrean
    // await $fetch('/api/antrean/link', { method: 'POST', body: { ... } });
    
    // Simulasi delay
    await new Promise(resolve => setTimeout(resolve, 600));

    isLinked.value = true;
    emit('linked');
    closeDialog();
  } catch (error) {
    console.error('Gagal menghubungkan data pasien:', error);
  } finally {
    isLinking.value = false;
  }
};
</script>

<style scoped lang="scss">
.bg-navy-custom {
  background-color: #003482 !important;
  color: #ffffff !important;
}

.text-navy-custom {
  color: #003482 !important;
}

.patient-data-dialog {
  border-radius: 12px;
  overflow: hidden;

  .dialog-header {
    background-color: #003482 !important;
  }

  .text-error {
    color: #E53935;
  }

  .search-input {
    :deep(.v-field) {
      border-radius: 8px;
    }
    :deep(.v-field__append-inner) {
      padding-top: 0;
      padding-bottom: 0;
      align-items: center;
    }
  }

  .search-btn {
    border-radius: 6px;
    text-transform: none;
    letter-spacing: normal;
    font-weight: 500;
  }

  .info-section {
    background-color: #F8F9FA;
    border-radius: 12px;
    padding: 20px;
    border: 1px solid #E0E0E0;

    .info-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 16px;

      .info-field {
        &.full-width {
          grid-column: 1 / -1;
        }

        .info-box {
          background-color: #ECEFF1;
          border-radius: 6px;
          padding: 10px 14px;
          font-size: 14px;
          color: #333;
          min-height: 40px;
        }
      }
    }
  }
}
</style>
