<template>
  <FormDialog v-model="dialog" @close="closeDialog">
    <template #title>
      <span class="text-h6 font-weight-medium pt-1 text-capitalize">
        {{ isEditMode ? "Edit Work Order" : "Create Work Order" }}
      </span>
    </template>

    <InputFile
      :attachments="displayedAttachments"
      :errored-images="localErroredImages"
      :max-files="maxFiles"
      :created-from="props.createdFrom"
      @add="handleFileAdded"
      @delete="deleteFile"
      @errored="onImageError"
    />

    <v-autocomplete
      v-model="workOrder.subject"
      :items="subjects"
      item-title="title"
      item-value="value"
      item-props
      label="Subject"
      variant="outlined"
      density="compact"
      class="mb-2"
      :clearable="
        props.createdFrom === 'feedback' && workOrder.subject !== ''
          ? false
          : true
      "
      :readonly="
        props.createdFrom === 'feedback' && workOrder.subject !== ''
          ? true
          : false
      "
      :custom-filter="customFilter"
      :rules="[requiredRule]"
    >
      <template #label> Subject <span class="text-red">*</span> </template>
    </v-autocomplete>

    <v-autocomplete
      v-model="workOrder.category"
      :items="categories"
      item-title="title"
      item-value="value"
      item-props
      label="Category"
      variant="outlined"
      density="compact"
      class="mb-2"
      :clearable="
        props.createdFrom === 'feedback' && workOrder.category !== ''
          ? false
          : true
      "
      :readonly="
        props.createdFrom === 'feedback' && workOrder.category !== ''
          ? true
          : false
      "
      :rules="[requiredRule]"
    >
      <template #label> Category <span class="text-red">*</span> </template>
    </v-autocomplete>

    <v-checkbox v-model="workOrder.highPriority" density="compact" class="ma-0">
      <template #label>
        <span class="text-caption">
          Set work order as High Priority (Optional)
        </span>
      </template>
    </v-checkbox>

    <!-- <v-autocomplete
      label="Block"
      variant="outlined"
      density="compact"
      v-model="workOrder.block"
      :items="blocks"
      class="mt-1"
      clearable
    /> -->

    <!-- <v-autocomplete
      label="Level"
      variant="outlined"
      density="compact"
      v-model="workOrder.level"
      :items="levels"
      class="mt-1"
      clearable
    /> -->

    <v-autocomplete
      label="Unit"
      variant="outlined"
      density="compact"
      v-model="workOrder.unit"
      :items="units"
      class="mt-1"
      clearable
      :rules="[requiredRule]"
    >
      <template #label> Unit <span class="text-red">*</span> </template>
    </v-autocomplete>

    <!-- <v-text-field
      label="Specific Location"
      variant="outlined"
      density="compact"
      v-model="workOrder.location"
      class="mt-1"
      dense
      :readonly="
        props.createdFrom === 'feedback' && workOrder.location !== ''
          ? true
          : false
      "
    /> -->

    <v-textarea
      label="Work Order Description"
      variant="outlined"
      density="compact"
      v-model="workOrder.description"
      class="mt-1"
      rows="4"
      clearable
      auto-grow
      :rules="[requiredRule]"
    >
      <template #label> Description <span class="text-red">*</span> </template>
    </v-textarea>

    <template #footer>
      <v-btn
        color="primary-button"
        class="text-capitalize mb-4"
        block
        height="40"
        :loading="loading"
        :disabled="loading || !isFormValid"
        @click="submitWorkOrder"
      >
        Submit
      </v-btn>
    </template>
  </FormDialog>
</template>

<script setup lang="ts">
import useBuildingUnit from "../../composables/useBuildingUnit";

const props = defineProps<{
  modelValue: boolean;
  createdFrom: string;
  isEditMode: boolean;
  loading: boolean;
  categories: { title: string; value: string }[];
  erroredImages?: string[];
  maxFiles?: number;
  blocks?: string[];
  levels?: string[];
  units?: string[];
  specificLocations?: string[];
}>();

const workOrder = defineModel("workOrder", {
  default: {
    subject: "",
    category: "",
    highPriority: false,
    unit: "",
    location: "",
    description: "",
    attachments: [],
  },
});

const emit = defineEmits([
  "update:modelValue",
  "update:workOrder",
  "close",
  "submit",
  "fileAdded",
  "fileDeleted",
]);

const dialog = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

const localErroredImages = ref<string[]>(props.erroredImages || []);

watch(
  () => props.erroredImages,
  (val) => {
    if (val) localErroredImages.value = val;
  }
);

const displayedAttachments = computed(() => {
  return workOrder.value.attachments || [];
});

const { requiredRule } = useUtils();

const isFormValid = computed(() => {
  return (
    workOrder.value.subject &&
    workOrder.value.category &&
    workOrder.value.unit &&
    workOrder.value.description
  );
});

function handleFileAdded(file: File) {
  emit("fileAdded", file);
}

function deleteFile(url: string) {
  emit("fileDeleted", url);
}

function onImageError(file: string) {
  if (!localErroredImages.value.includes(file)) {
    localErroredImages.value.push(file);
  }
}

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

function submitWorkOrder() {
  emit("submit", { ...workOrder.value });
}

const units = ref<Array<{ title: string; value: string }>>([]);

const { getAll } = useBuildingUnit();
const { data } = await useLazyAsyncData("get-building-units-by-status", () =>
  getAll({ status: "active" })
);

watchEffect(() => {
  if (data.value && data.value.items && data.value.items.length > 0) {
    units.value = data.value.items.map((item: any) => {
      return {
        title: `${item.name} - ${item.level} - ${item.buildingName}`,
        value: item._id,
      };
    });
  }
});

const workOrderUnit = computed(() => {
  return workOrder.value.unit;
});

watch(workOrderUnit, (val: string) => {
  if (val) {
    const unit = units.value.find((unit: any) => unit.value === val);
    if (unit) {
      workOrder.value.location = unit.title;
    }
  }
});

const { subjects } = useLocal();

const customFilter = (value: string, query: string, item: any) => {
  const title = item?.raw?.title?.toLowerCase() || "";
  const subtitle = item?.raw?.subtitle?.toLowerCase() || "";
  const search = query.toLowerCase();
  return title.includes(search) || subtitle.includes(search);
};
</script>
