<script setup>
import { computed, ref, watch } from "vue";
import { useDialogPluginComponent } from "quasar";
const props = defineProps({
  initialSource: { type: String, required: false, default: "" },
  initialAlt: { type: String, required: false, default: "" },
  initialWidth: { type: [Number, null], required: false, default: null },
  initialHeight: { type: [Number, null], required: false, default: null }
});
defineEmits([
  ...useDialogPluginComponent.emits
]);
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();
const source = ref(props.initialSource);
const alt = ref(props.initialAlt);
const width = ref(props.initialWidth);
const height = ref(props.initialHeight);
const lockAspectRatio = ref(true);
const aspectRatio = ref(null);
const canSubmit = computed(() => source.value.trim().length > 0);
const toPositiveNumber = (value) => {
  const n = Number(value);
  return Number.isFinite(n) && n > 0 ? n : null;
};
const updateImageMeta = (src) => {
  return new Promise((resolve) => {
    if (!src) {
      aspectRatio.value = null;
      resolve();
      return;
    }
    const img = new Image();
    img.onload = () => {
      if (img.naturalWidth > 0 && img.naturalHeight > 0) {
        aspectRatio.value = img.naturalWidth / img.naturalHeight;
        if (!width.value) width.value = img.naturalWidth;
        if (!height.value) height.value = img.naturalHeight;
      }
      resolve();
    };
    img.onerror = () => resolve();
    img.src = src;
  });
};
watch(() => source.value, (value) => {
  updateImageMeta(value.trim());
}, { immediate: true });
const onWidthInput = (val) => {
  const newWidth = toPositiveNumber(val);
  width.value = newWidth;
  if (lockAspectRatio.value && aspectRatio.value && newWidth) {
    height.value = Math.round(newWidth / aspectRatio.value);
  }
};
const onHeightInput = (val) => {
  const newHeight = toPositiveNumber(val);
  height.value = newHeight;
  if (lockAspectRatio.value && aspectRatio.value && newHeight) {
    width.value = Math.round(newHeight * aspectRatio.value);
  }
};
const toggleLock = () => {
  lockAspectRatio.value = !lockAspectRatio.value;
  if (lockAspectRatio.value && aspectRatio.value && width.value) {
    height.value = Math.round(width.value / aspectRatio.value);
  }
};
const onConfirm = () => {
  if (!canSubmit.value) return;
  onDialogOK({
    source: source.value.trim(),
    alt: alt.value.trim(),
    width: width.value,
    height: height.value
  });
};
</script>

<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card style="min-width: 560px; max-width: 90vw;">
      <q-card-section class="text-h6">
        Insert/Edit Image
      </q-card-section>

      <q-card-section class="q-gutter-md">
        <q-input v-model="source" label="Source" outlined dense />
        <q-input v-model="alt" label="Alternative Description" outlined dense />

        <div class="row items-center q-col-gutter-sm">
          <div class="col">
            <q-input
              :model-value="width"
              @update:model-value="onWidthInput"
              type="number"
              min="1"
              label="Width"
              outlined
              dense
            />
          </div>
          <div class="col-auto">
            <q-btn
              flat
              round
              :icon="lockAspectRatio ? 'sym_o_lock' : 'sym_o_lock_open'"
              :color="lockAspectRatio ? 'primary' : 'grey'"
              @click="toggleLock"
            >
              <q-tooltip>Lock Aspect Ratio</q-tooltip>
            </q-btn>
          </div>
          <div class="col">
            <q-input
              :model-value="height"
              @update:model-value="onHeightInput"
              type="number"
              min="1"
              label="Height"
              outlined
              dense
            />
          </div>
        </div>
      </q-card-section>

      <q-card-actions align="right">
        <q-btn flat label="Cancel" @click="onDialogCancel" />
        <q-btn color="primary" label="Insert" :disable="!canSubmit" @click="onConfirm" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
