<template>
  <div>
    <q-breadcrumbs
      v-if="displayBreadcrumbs != null"
      class="q-mb-xs"
      :class="$q.screen.lt.sm ? '' : 'q-pl-lg'"
    >
      <q-breadcrumbs-el
        v-for="crumb in displayBreadcrumbs"
        :key="crumb.name || crumb.label"
        :label="crumb.title"
        :to="crumb.name ? { name: crumb.name, params: crumb.params } : null"
      />
    </q-breadcrumbs>
    <div
      v-else
      style="max-width: 180px"
      :class="$q.screen.lt.sm ? '' : 'q-pl-lg'"
    >
      <q-skeleton type="text" />
    </div>

    <div class="flex items-center justify-between">
      <div
        class="flex items-center q-pl-xs"
        :class="$q.screen.lt.sm ? '' : 'q-pt-md'"
      >
        <span
          v-if="displayTitle"
          class="text-h6 text-primary text-weight-regular"
        >
          {{ displayTitle }}
        </span>
        <div v-else style="width: 280px">
          <q-skeleton type="text" height="40px" />
        </div>
        <q-icon
          v-if="showFilterIcon"
          name="mdi-filter-outline"
          color="background"
          size="sm"
          class="q-ml-sm bg-primary"
          style="border-radius: 8px; padding: 2px"
        />
      </div>
      <div
        class="flex items-center q-pr-sm"
        :class="$q.screen.lt.sm ? '' : 'q-pt-md'"
      >
        <slot name="after" />
      </div>
    </div>
    <q-separator class="q-my-sm" />
  </div>
</template>

<script setup>
import { computed } from "vue";
import { useRoute } from "vue-router";
import { useI18n } from "vue-i18n";

const { title, breadcrumbs } = defineProps({
  title: {
    type: Object,
    default: null,
  },
  breadcrumbs: {
    type: Object,
    default: null,
  },
  showFilterIcon: {
    type: Boolean,
    default: false,
  },
});

const route = useRoute();
const { t } = useI18n();

const displayTitle = computed(() => {
  if (title) {
    if (title.translate) {
      return t(title.value);
    } else {
      return title.value;
    }
  } else if (route.meta?.title) {
    if (route.meta?.title.translate) {
      return t(route.meta?.title.value);
    } else {
      return route.meta?.title.value;
    }
  }
  return null;
});

const displayBreadcrumbs = computed(() => {
  if (!breadcrumbs && breadcrumbs?.length <= 0) {
    return null;
  } else if (breadcrumbs && breadcrumbs?.length > 0) {
    return (breadcrumbs || []).map((b) => {
      if (b.translate) {
        return t(b.title);
      } else {
        return b.title;
      }
    });
  }
  if (!route.meta?.breadcrumbs && route.meta?.breadcrumbs?.length <= 0) {
    return null;
  } else if (route.meta?.breadcrumbs && route.meta?.breadcrumbs?.length > 0) {
    return (route.meta?.breadcrumbs || []).map((b) => {
      if (b.translate) {
        return {
          ...b,
          title: t(b.title),
        };
      } else {
        return {
          ...b,
          title: b.title,
        };
      }
    });
  }
  return null;
});
</script>
