<script setup lang="ts">
import { computed, reactive, ref, useModel } from "vue";
import { useI18n } from "vue-i18n";
import {
  ACol,
  ARow,
  AContainer,
  ATextField,
  ASelect,
  ABaseDialog,
  ABtn,
  REQUIRED,
  useValidationErrors,
  AForm,
} from "@actindo/core-ui";
import type { ISampleEntity } from "@/services/api/Sample/Entity";
import { SAMPLE_STATUS_FLAGS } from "@/views/Sample/constants";

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

const emit = defineEmits<{
  (event: "update:modelValue", value: boolean): void;
  (event: "save", value: ISampleEntity): void;
}>();

const isVisible = useModel(props, "modelValue");

const { t } = useI18n();

const statuses = computed(() =>
  Object.entries(SAMPLE_STATUS_FLAGS).map(([value, { label }]) => ({
    value,
    title: t(label),
  })),
);

const localForm = ref({
  key: undefined,
  validFrom: undefined,
  status: undefined,
  name: undefined,
});

const rules = reactive({
  key: REQUIRED,
  validFrom: REQUIRED,
  status: REQUIRED,
  name: REQUIRED,
});

const { v$, keyErrors, validFromErrors, statusErrors, nameErrors } =
  useValidationErrors({
    rules,
    form: localForm,
  });

function save() {
  const entity = {
    key: localForm.value.key,
    validFrom: localForm.value.validFrom,
    status: localForm.value.status,
    sample: {
      name: localForm.value.name,
    },
  };
  emit("save", entity);
}
</script>

<template>
  <ABaseDialog
    v-model="isVisible"
    :title="$t('SampleView.newEntity')"
    min-width="480px"
    max-width="480px"
  >
    <AContainer fluid>
      <AForm @submit.prevent>
        <ARow>
          <ACol cols="12">
            <ATextField
              v-model="v$.key.$model"
              :label="$t('SampleView.key')"
              :error-messages="keyErrors"
            />
          </ACol>
          <ACol cols="12">
            <ATextField
              v-model="v$.validFrom.$model"
              :label="$t('SampleView.validFrom')"
              type="date"
              :error-messages="validFromErrors"
            />
          </ACol>
          <ACol cols="12">
            <ASelect
              v-model="v$.status.$model"
              :items="statuses"
              :label="$t('SampleView.status')"
              :error-messages="statusErrors"
            />
          </ACol>
          <ACol cols="12">
            <ATextField
              v-model="v$.name.$model"
              :label="$t('SampleView.name')"
              :error-messages="nameErrors"
            />
          </ACol>
        </ARow>
      </AForm>
    </AContainer>

    <template #actions>
      <ABtn
        variant="elevated"
        :text="$t('SampleView.save')"
        :disabled="v$.$invalid"
        :loading="loading"
        @click="save"
      />
    </template>
  </ABaseDialog>
</template>
