<script setup lang="ts">
import { useLocale } from 'vuetify';

defineProps({
  error: {
    type: String,
    default: '',
  },
  block: {
    type: Boolean,
    default: false,
  },
  noBorder: {
    type: Boolean,
    default: false,
  },
});

const { t } = useLocale();

function parseError(e: string): string {
  if (e.includes('$vuetify', 0)) {
    return e;
  }

  if (e.includes('validator')) {
    const errs = e.split(' || ');
    for (const err of errs) {
      if (err.includes('validator', 0)) {
        const splitted = err.split(':');
        if (splitted?.length) {
          const right = splitted.pop();
          if (right && right.includes('/')) {
            const [field, key] = right.split('/');
            return t(
              `$vuetify.validator.field`,
              field.toLowerCase(),
              t(`$vuetify.validator.${key.replace(/'/gm, '')}`),
            );
          }
        }
      }
    }
  }

  const te = t(`$vuetify.${e}`);
  if (!te.includes('$vuetify', 0)) {
    return te;
  }

  return e;
}
</script>

<template>
  <span
    v-if="error?.length"
    class="text-sm text-error flex items-center"
    :class="{
      'error-block': block,
      'my-2': !block,
      'border-b': !noBorder,
    }"
    ><span class="mso mr-2 text-2xl">error</span> {{ parseError(error) }}</span
  >
</template>

<style scoped>
.error-block {
  background-color: rgba(var(--v-theme-error), var(--v-border-opacity));
  border-color: rgba(var(--v-theme-error), var(--v-border-opacity));
  padding: 0 0.8rem;
}
</style>
