<template>
  <v-card width="100%">
    <v-toolbar>
      <v-row no-gutters class="fill-height px-6" align="center">
        <span class="font-weight-bold text-h5"> Add Unit </span>
      </v-row>
    </v-toolbar>
    <v-card-text style="max-height: 100vh; overflow-y: auto">
      <v-form v-model="validForm" :disabled="disable">
        <v-row no-gutters>
          <!-- <v-col cols="12" class="mt-2">
            <v-row no-gutters>
              <InputLabel class="text-capitalize" title="Name" required />
              <v-col cols="12">
                <v-text-field
                  v-model="buildingUnit.name"
                  density="comfortable"
                  :rules="[requiredRule]"
                ></v-text-field>
              </v-col>
            </v-row>
          </v-col> -->

          <v-col cols="12">
            <v-row>
              <v-col cols="12" md="6" class="mt-2">
                <v-row no-gutters>
                  <InputLabel class="text-capitalize" title="Block" required />
                  <v-col cols="12">
                    <v-autocomplete v-model="buildingUnit.building" :items="buildings" item-title="name"
                      item-value="_id" v-model:search="searchBuilding" :hide-no-data="false" density="comfortable"
                      :rules="[requiredRule]" variant="outlined">
                      <template v-slot:item="{ props: itemProps, item }">
                        <v-list-item v-bind="itemProps" :title="item?.raw?.name">

                        </v-list-item>
                      </template>
                      <template v-slot:selection="{ item }">
                        {{ buildingUnit.building && `${item?.raw?.name}` }}
                      </template>
                    </v-autocomplete>
                  </v-col>
                </v-row>
              </v-col>

              <v-col cols="12" md="6" class="mt-2">
                <v-row no-gutters>
                  <InputLabel class="text-capitalize" title="Level" required />
                  <v-col cols="12">
                    <v-select v-model="buildingUnit.level" :items="buildingLevels" item-title="name" item-value="_id"
                      density="comfortable" :rules="[requiredRule]"></v-select>
                  </v-col>
                </v-row>
              </v-col>

              <v-col cols="12" md="6" class="mt-2">
                <v-row no-gutters>
                  <InputLabel class="text-capitalize" title="No. of Units to be added" required />
                  <v-col cols="12">
                    <v-text-field v-model.number="buildingUnitQty" density="comfortable" :rules="[requiredRule]"
                      type="number" @update:model-value="setBuildingLevels()"></v-text-field>
                  </v-col>
                </v-row>
              </v-col>

              <!-- <v-col cols="12" md="6" class="mt-2">
                <v-row no-gutters>
                  <InputLabel class="text-capitalize" title="Category" required />
                  <v-col cols="12">
                    <v-autocomplete v-model="buildingUnit.category" :items="unitCategories" density="comfortable"
                      :rules="[requiredRule]"></v-autocomplete>
                  </v-col>
                </v-row>
              </v-col> -->
            </v-row>
          </v-col>

          <!-- <v-col cols="12">
            <v-row>
              <v-col cols="12" class="mt-2">
                <v-row no-gutters>
                  <InputLabel
                    class="text-capitalize"
                    title="Company Name"
                    required
                  />
                  <v-col cols="12">
                    <v-text-field
                      v-model="buildingUnit.companyName"
                      density="comfortable"
                      :rules="[requiredRule]"
                    ></v-text-field>
                  </v-col>
                </v-row>
              </v-col>
            </v-row>
          </v-col> -->

          <!-- <v-col cols="12">
            <v-row>
              <v-col cols="12" class="mt-2">
                <v-row no-gutters>
                  <InputLabel
                    class="text-capitalize"
                    title="Company Registration Number"
                  />
                  <v-col cols="12">
                    <v-text-field
                      v-model="buildingUnit.companyRegistrationNumber"
                      density="comfortable"
                      :rules="[]"
                    ></v-text-field>
                  </v-col>
                </v-row>
              </v-col>
            </v-row>
          </v-col> -->

          <!-- <v-col cols="12">
            <v-row>
              <v-col cols="12" class="mt-2">
                <v-row no-gutters>
                  <InputLabel
                    class="text-capitalize"
                    title="Lease Start"
                    required
                  />
                  <v-col cols="12">
                    <InputDateTimePicker
                      ref="startDateRef"
                      v-model="buildingUnit.leaseStart"
                      :rules="[requiredRule]"
                    />
                  </v-col>
                </v-row>
              </v-col>
            </v-row>
          </v-col>

          <v-col cols="12">
            <v-row>
              <v-col cols="12" class="mt-2">
                <v-row no-gutters>
                  <InputLabel
                    class="text-capitalize"
                    title="Lease End"
                    required
                  />
                  <v-col cols="12">
                    <InputDateTimePicker
                      ref="endDateRef"
                      v-model="buildingUnit.leaseEnd"
                      :rules="[requiredRule]"
                    />
                  </v-col>
                </v-row>
              </v-col>
            </v-row>
          </v-col> -->
          <v-col v-if="buildingLevels" cols="12">
            <v-row justify="center">
              <v-col cols="6">
                <v-btn block color="primary" variant="text" class="text-none font-weight-bold" text="Set unit labels"
                  @click="show = !show"></v-btn>
              </v-col>
            </v-row>
          </v-col>

          <v-expand-transition>
            <v-row v-show="show" no-gutters>
              <v-row>
                <template v-for="(unitLabel, unitLabelIndex) in unitLabels" :key="unitLabelIndex">
                  <v-col cols="12" md="4">
                    <v-row>
                      <v-col cols="12">
                        <v-row no-gutters>
                          <!-- <InputLabel class="text-capitalize font-weight-bold" :title="`#${unitLabelIndex + 1}`" /> -->
                          <v-col cols="12">
                            <v-text-field v-model.trim="unitLabels[unitLabelIndex]"
                              density="comfortable"></v-text-field>
                          </v-col>
                        </v-row>
                      </v-col>
                    </v-row>
                  </v-col>
                </template>
              </v-row>
            </v-row>
          </v-expand-transition>

          <!-- <v-col cols="12" class="mt-5">
            <InputLabel
              class="text-capitalize"
              title="Upload Files (Lease of Contract, Cert. of Occupancy)"
            />
            <InputFileV2
              v-model="buildingUnit.buildingUnitFiles"
              :multiple="false"
              :max-length="10"
              title="Upload PDF Files"
              accept="application/pdf"
            />
          </v-col> -->

          <v-col cols="12" class="mt-2">
            <v-checkbox v-model="createMore" density="comfortable" hide-details>
              <template #label>
                <span class="text-subtitle-2 font-weight-bold">
                  Create more
                </span>
              </template>
            </v-checkbox>
          </v-col>

          <v-col cols="12" class="my-2">
            <v-row no-gutters>
              <v-col cols="12" class="text-center">
                <span class="text-none text-subtitle-2 font-weight-medium text-error">
                  {{ message }}
                </span>
              </v-col>
            </v-row>
          </v-col>
        </v-row>
      </v-form>
    </v-card-text>

    <v-toolbar density="compact">
      <v-row no-gutters>
        <v-col cols="6">
          <v-btn tile block variant="text" class="text-none" size="48" @click="cancel" :disabled="disable">
            Cancel
          </v-btn>
        </v-col>

        <v-col cols="6">
          <v-btn tile block variant="flat" color="black" class="text-none" size="48" :disabled="!validForm || disable"
            @click="submit" :loading="disable">
            Submit
          </v-btn>
        </v-col>
      </v-row>
    </v-toolbar>

    <Snackbar v-model="messageSnackbar" :text="message" :color="messageColor" />
  </v-card>
</template>

<script setup lang="ts">
const prop = defineProps({
  site: {
    type: String,
    default: "",
  },
});

const searchBuilding = ref("");

const emit = defineEmits(["cancel", "success", "success:create-more"]);

const validForm = ref(false);

const { getAll } = useBuilding();

const buildings = ref<TBuilding[]>([]);

const { data: getBuildingReq } = useLazyAsyncData(
  "get-all-buildings",
  async () => getAll({ site: prop.site, status: "active" })
);

watchEffect(() => {
  if (getBuildingReq.value) {
    buildings.value = getBuildingReq.value.items;
  }
});

const buildingUnitQty = ref(1);

const buildingUnit = ref<TBuildingUnitPayload>({
  site: "",
  name: "Unit",
  building: "",
  buildingName: "",
  block: 0,
  level: "",
  // category: "",
  status: "active",
  buildingUnitFiles: [],
  companyName: "",
  companyRegistrationNumber: "",
  leaseStart: "",
  leaseEnd: "",
});


const startDateRef = ref<HTMLInputElement | null>(null);
const expiryDateRef = ref<HTMLInputElement | null>(null);

buildingUnit.value.site = prop.site;

const selectedBuilding = computed(() => {
  return buildings.value.find((b) => b._id === buildingUnit.value.building);
});

watchEffect(() => {
  if (buildingUnit.value.building) {
    buildingUnit.value.buildingName = selectedBuilding.value?.name;
    buildingUnit.value.block = selectedBuilding.value?.block || 0;
  } else {
    buildingUnit.value.buildingName = "";
    buildingUnit.value.block = 0;
  }
});

const buildingLevels = computed(() => {
  return selectedBuilding.value?.levels || [];
});

const unitLabels = ref<string[]>([]);
unitLabels.value.push("Unit 1");

const show = ref(false);

function setBuildingLevels() {
  unitLabels.value.length = 0;
  for (let index = 0; index < buildingUnitQty.value; index++) {
    unitLabels.value.push(`Unit ${index + 1}`);
  }
}

const name = ref("");
const directorName = ref("");
const createMore = ref(false);
const disable = ref(false);

const { requiredRule, validateDate } = useUtils();

const message = ref("");
const messageSnackbar = ref(false);
const messageColor = ref("");

const { add, categories: unitCategories } = useBuildingUnit();

function showMessage(msg: string, color: string) {
  message.value = msg;
  messageColor.value = color;
  messageSnackbar.value = true;
}

function setBuildingUnit() {
  buildingUnit.value.site = prop.site ?? "";
  buildingUnit.value.name = "Unit";
  buildingUnit.value.building = "";
  buildingUnit.value.buildingName = "";
  buildingUnit.value.level = "";
  // buildingUnit.value.category = "";
  buildingUnit.value.status = "active";
  buildingUnit.value.buildingUnitFiles = [];
  buildingUnitQty.value = 1;
  message.value = "";
  buildingUnit.value.companyName = "";
  buildingUnit.value.companyRegistrationNumber = "";
  buildingUnit.value.leaseStart = "";
  buildingUnit.value.leaseEnd = "";
}

async function submit() {
  disable.value = true;
  const { buildingUnitFiles, companyName, companyRegistrationNumber, leaseStart, leaseEnd, ...rest } = buildingUnit.value;
  try {
    await add({
      labels: unitLabels.value,
      unit: rest,
      qty: buildingUnitQty.value,
    });

    if (createMore.value) {
      setBuildingUnit();
      message.value = "";
      showMessage("Unit created successfully!", "success");
      emit("success:create-more");
      return;
    }

    emit("success");
  } catch (error: any) {
    message.value =
      error.response?._data?.message || "Failed to create building";
    showMessage(message.value, "error");
  } finally {
    disable.value = false;
  }
}

watch(buildingUnitQty, (newVal) => {
  setTimeout(() => {
    show.value = newVal > 0 && !!newVal;
  }, 500);
});


function cancel() {
  name.value = "";
  directorName.value = "";
  createMore.value = false;
  message.value = "";
  emit("cancel");
}
</script>
