<script lang="ts" setup>
import { ref } from 'vue';
import AppBox from './app/AppBox.vue';

defineExpose({ browse });
defineProps<{
  clearButtonDisabled?: boolean;
  clearButton?: boolean;
  hiddenFooter?: boolean;
  defaultUrl?: string;
}>();
const emit = defineEmits<{
  (e: 'save', file: File | null, url: string | null): void;
}>();

const imageUrl = defineModel<string>('imageUrl', {
  required: false,
  default: '',
});
const fallbackUrl = defineModel<string>('fallbackUrl', {
  required: false,
  default: '',
});
const dialogState = defineModel<boolean>('dialogState', {
  required: false,
  default: true,
});
const file = defineModel<File | null>('file', {
  required: true,
});

const reader = new FileReader();
const inputFile = (() => {
  const _element = document.createElement('input');
  _element.type = 'file';
  _element.accept = 'image/*';
  _element.addEventListener('change', change);
  return _element;
})();
const headless = ref(false);

reader.addEventListener('load', () => {
  if (typeof reader.result === 'string') imageUrl.value = reader.result;
});

function browse() {
  inputFile?.click();
  headless.value = true;
}

function change(e: Event) {
  const _element = e.target as HTMLInputElement | null;
  const _file = _element?.files?.[0];

  if (_file) {
    file.value = _file;
    reader.readAsDataURL(_file);
    if (headless) emit('save', _file, imageUrl.value);
  }

  headless.value = false;
}
</script>
<template>
  <q-dialog v-model="dialogState">
    <AppBox class="image-dialog-content">
      <div class="row items-center q-py-sm q-px-md bordered-b">
        <div style="flex: 1"><slot name="title" /></div>
        <div>
          <q-btn
            round
            flat
            icon="mdi-close"
            padding="xs"
            class="close-btn"
            :class="{ dark: $q.dark.isActive }"
            v-close-popup
          />
        </div>
      </div>
      <div class="image-dialog-body">
        <img
          :src="imageUrl || fallbackUrl"
          v-if="imageUrl || fallbackUrl"
          class="image-container"
          style="object-fit: contain"
          @error="imageUrl = ''"
        />
        <div class="image-container" v-if="!imageUrl && !fallbackUrl">
          <slot name="error"></slot>
        </div>
        <div style="position: fixed; padding: var(--size-2)">
          <q-btn
            class="upload-image-btn"
            icon="mdi-camera"
            size="md"
            unelevated
            round
            @click="inputFile?.click()"
          ></q-btn>
        </div>
      </div>
      <div
        class="row items-center justify-end q-py-sm q-px-md bordered-t"
        v-if="!hiddenFooter"
      >
        <q-btn
          dense
          unelevated
          :color="$q.dark.isActive ? 'grey-9' : 'grey-4'"
          :text-color="$q.dark.isActive ? 'grey-1' : 'grey-10'"
          :label="$t('clear')"
          @click="
            inputFile && (inputFile.value = ''),
              (imageUrl = defaultUrl || fallbackUrl || ''),
              (file = null)
          "
          class="q-px-md q-mr-auto"
          :disable="
            clearButtonDisabled ||
            imageUrl === fallbackUrl ||
            imageUrl === defaultUrl ||
            !imageUrl
          "
          v-if="clearButton"
        />
        <q-btn
          dense
          unelevated
          :color="$q.dark.isActive ? 'grey-9' : 'grey-4'"
          :text-color="$q.dark.isActive ? 'grey-1' : 'grey-10'"
          :label="$t('cancel')"
          @click="inputFile && (inputFile.value = ''), (file = null)"
          class="q-px-md q-mr-sm"
          v-close-popup
        />
        <q-btn
          dense
          unelevated
          id="submit-btn"
          type="submit"
          color="primary"
          class="q-px-md"
          @click="$emit('save', inputFile?.files?.[0] || null, imageUrl)"
          :label="$t('save')"
        />
      </div>
    </AppBox>
  </q-dialog>
</template>

<style scoped>
.image-dialog-content {
  padding: 0;
  border-radius: var(--radius-2);
  flex-wrap: nowrap;
  width: 100%;
  max-width: 80%;
}

@media (min-width: 768px) {
  .image-dialog-content {
    max-width: 60%;
  }
}

.image-dialog-body {
  overflow-y: auto;
  background-color: var(--surface-2) !important;
  position: relative;
  display: flex;
  flex-direction: column;
  flex: 1;
  height: calc(100vh - 200px);
}

.upload-image-btn {
  transition: 0.3s background-color ease-in-out;
  background-color: hsla(0 0% 0% / 0.2);

  backdrop-filter: blur(1px);

  &:not(:hover) {
    color: hsla(0 0% 40% / 1);
    background-color: hsla(0 0% 0% / 0.2);
  }
}

.image-container {
  width: 100%;
  height: calc(100vh - 200px);
  min-height: 480px;

  & > :deep(*) {
    height: 100%;
    width: 100%;
  }
}

.image-container > :deep(*:not(:first-child)) {
  display: none;
}

.close-btn {
  color: hsl(var(--negative-bg));
  background-color: hsla(var(--negative-bg) / 0.1);

  &.dark {
    background-color: transparent;
    border: 1px solid hsl(var(--negative-bg));
  }
}
</style>
