<template>
  <v-dialog
    :model-value="modelValue"
    @update:model-value="(v) => emit('update:modelValue', v)"
    max-width="450"
  >
    <v-card>
      <v-toolbar>
        <template v-if="$slots.header">
          <slot
            name="header"
            :title="
              mode === 'edit' ? `Edit ${entityType}` : `Add New ${entityType}`
            "
            :onClose="onClose"
          />
        </template>
        <template v-else>
          <v-row no-gutters class="fill-height px-6" align="center">
            <span class="font-weight-bold text-h6 text-capitalize">{{
              mode === "edit" ? `Edit ${entityType}` : `Add New ${entityType}`
            }}</span>
          </v-row>
        </template>
      </v-toolbar>

      <v-card-text>
        <v-form ref="formRef" v-model="valid">
          <v-row>
            <v-col cols="12">
              <InputLabel for="name" :title="label" required />
              <v-text-field v-model="nameValue" :rules="[requiredRule]" />
            </v-col>
          </v-row>
        </v-form>
      </v-card-text>

      <v-toolbar class="pa-0" density="compact">
        <v-row no-gutters>
          <v-col cols="6" class="pa-0">
            <v-btn
              block
              variant="text"
              class="text-none"
              size="large"
              @click="close"
              height="48"
            >
              Cancel
            </v-btn>
          </v-col>

          <v-col cols="6" class="pa-0">
            <v-btn
              block
              variant="flat"
              color="black"
              class="text-none font-weight-bold rounded-0"
              height="48"
              :loading="submitting"
              @click="submit"
            >
              {{ mode === "edit" ? "Save" : "Create" }}
            </v-btn>
          </v-col>
        </v-row>
      </v-toolbar>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
const props = defineProps({
  modelValue: { type: Boolean, required: true },
  mode: { type: String as PropType<"add" | "edit">, default: "add" },
  area: { type: Object as PropType<Record<string, any> | null>, default: null },
  label: { type: String, default: "Name" },
  nameModel: { type: String as PropType<string | null>, default: null },
  entityType: { type: String, default: "Area" }, // values: "Area", "Unit"
});

const emit = defineEmits([
  "update:modelValue",
  "saved",
  "update:nameModel",
] as const);

const formRef = ref(null);
const valid = ref(false);
const submitting = ref(false);

const form = reactive({ name: "", description: "", status: "active" });

watchEffect(() => {
  if (props.area) {
    form.name = props.area.name || "";
    form.description = props.area.description || "";
    form.status = props.area.status || "active";
  } else {
    form.name = "";
    form.description = "";
    form.status = "active";
  }
});

const { requiredRule } = useUtils();

const nameValue = computed({
  get: () => {
    return props.nameModel !== null ? props.nameModel : form.name;
  },
  set: (v: string) => {
    if (props.nameModel !== null) {
      emit("update:nameModel", v);
    } else {
      form.name = v;
    }
  },
});

function close() {
  emit("update:modelValue", false);
}

const onClose = () => close();

async function submit() {
  if (!valid.value) return;
  submitting.value = true;
  try {
    await new Promise((r) => setTimeout(r, 500));
    emit("saved", { ...form, _id: props.area?._id || Date.now().toString() });

    form.name = "";
    form.description = "";
    form.status = "active";

    emit("update:modelValue", false);
  } catch (e) {
  } finally {
    submitting.value = false;
  }
}
</script>
