<template>
  <v-dialog v-model="showDialog" max-width="450">
    <v-card>
      <v-toolbar>
        <v-row no-gutters class="fill-height px-6" align="center">
          <span class="font-weight-bold text-h6 text-capitalize">
            {{ prop.mode === "edit" ? "Edit Equipment" : "Add New Equipment" }}
          </span>
        </v-row>
      </v-toolbar>

      <v-card-text class="pa-4">
        <v-form ref="formRef" v-model="valid">
          <v-row no-gutters class="pa-0">
            <v-col cols="12" class="pa-0 mb-2">
              <InputLabel for="name" title="Name" required class="mb-1" />
              <v-text-field
                v-model="nameModel"
                :rules="[requiredRule]"
                density="comfortable"
                variant="outlined"
                placeholder="Enter equipment name"
                hide-details="auto"
                class="mb-0"
              />
            </v-col>

            <v-col cols="12" class="pa-0 mb-0">
              <InputLabel
                for="unitOfMeasurement"
                title="Unit of Measurement"
                required
                class="mb-1"
              />
              <v-select
                v-model="unitOfMeasurementModel"
                :items="unitOfMeasurementOptions"
                :rules="[requiredRule]"
                density="comfortable"
                variant="outlined"
                placeholder="Select unitOfMeasurement"
                hide-details="auto"
                class="mb-0"
              />
            </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"
            >
              {{ prop.mode === "edit" ? "Save" : "Create" }}
            </v-btn>
          </v-col>
        </v-row>
      </v-toolbar>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
const nameModel = defineModel("name", { type: String, default: "" });
const unitOfMeasurementModel = defineModel("unitOfMeasurement", {
  type: String,
  default: "",
});
const showDialog = defineModel({ type: Boolean, default: false });

const prop = defineProps({
  mode: {
    type: String,
    default: "add",
  },
  equipmentData: {
    type: Object,
    default: null,
  },
});

const emit = defineEmits(["saved", "close"]);

const formRef = ref<any>(null);
const valid = ref(false);
const submitting = ref(false);

const { requiredRule } = useUtils();

const unitOfMeasurementOptions = [
  "Pieces",
  "Boxes",
  "Bottles",
  "Liters",
  "Kilograms",
  "Grams",
  "Rolls",
  "Packs",
  "Sets",
  "Units",
];

watchEffect(() => {
  nameModel.value = prop.equipmentData?.name || "";
  unitOfMeasurementModel.value = prop.equipmentData?.unitOfMeasurement || "";
});

function close() {
  showDialog.value = false;
  emit("close");
}

async function submit() {
  const form = formRef.value as any;
  let ok = valid.value;
  if (form && typeof form.validate === "function") {
    const result = await form.validate();
    ok = result.valid;
  }

  if (!ok) return;

  submitting.value = true;
  try {
    await new Promise((r) => setTimeout(r, 500));

    emit("saved", {
      name: nameModel.value,

      unitOfMeasurement: unitOfMeasurementModel.value,
    });

    nameModel.value = "";
    unitOfMeasurementModel.value = "";

    showDialog.value = false;
    emit("close");
  } catch (e) {
    console.error("Error submitting form:", e);
  } finally {
    submitting.value = false;
  }
}
</script>
