<template>
  <v-row no-gutters>
    <v-col cols="12" class="mb-2">
      <v-row no-gutters>
        <v-btn class="text-none" rounded="pill" variant="tonal" @click="setBuilding()" size="large"
          v-if="canCreate && canCreateUnit">
          Add Unit
        </v-btn>
      </v-row>
    </v-col>
    <v-col cols="12">
      <v-card width="100%" variant="outlined" border="thin" rounded="lg" :loading="loading">
        <v-toolbar density="compact" color="grey-lighten-4">
          <template #prepend>
            <v-btn fab icon density="comfortable" @click="getBuildingUnit()">
              <v-icon>mdi-refresh</v-icon>
            </v-btn>
          </template>

          <template #append>
            <v-row no-gutters justify="end" align="center">
              <span class="mr-2 text-caption text-fontgray">
                {{ pageRange }}
              </span>
              <local-pagination v-model="page" :length="pages" @update:value="getBuildingUnit()" />
            </v-row>
          </template>
        </v-toolbar>

        <v-data-table :headers="props.headers" :items="items" item-value="_id" items-per-page="20" fixed-header
          hide-default-footer  @click:row="tableRowClickHandler"
          style="max-height: calc(100vh - (200px))">
          <template #item.block="{ value, item }">
            {{ value ? `Block ${value}` : "" }}
          </template>
        </v-data-table>
      </v-card>
    </v-col>

    <!-- Create Dialog -->
    <v-dialog v-model="createDialog" :width="smAndUp ? '50svw' : '100%'" persistent>
      <BuildingUnitFormAdd :site="site" @cancel="createDialog = false" @success="successCreate()"
        @success:create-more="getBuildingUnit()" />
    </v-dialog>
    
    <v-dialog v-if="canViewUnitDetails"  v-model="dialogPreview":width="smAndUp ? '70svw' : '100%'" persistent>
       <BuildingUnitFormEdit v-if="selectedBuildingUnit" @cancel="dialogPreview = false" @success="successUpdate()" @delete-unit="openDeleteDialog()"
        :roomFacility="selectedBuildingUnit" />
    </v-dialog>

    <v-dialog v-model="dialogDelete" :loading="deleteLoading" width="450" persistent>
      <v-card width="100%">
        <v-toolbar density="compact" class="pl-4">
          <span class="font-weight-medium text-h5">Delete Unit</span>
        </v-toolbar>

        <v-card-text>
          <p class="text-subtitle-2 text-center">
            Are you sure you want to delete this unit? This action cannot be
            undone.
          </p>

          <v-row v-if="message" no-gutters justify="center" class="mt-4">
            <span class="text-caption text-error text-center">
              {{ message }}
            </span>
          </v-row>
        </v-card-text>

        <v-toolbar density="compact">
          <v-row no-gutters>
            <v-col cols="6">
              <v-btn tile block size="48" variant="text" class="text-none" @click="dialogDelete = false"
                :disabled="deleteLoading">
                Close
              </v-btn>
            </v-col>
            <v-col cols="6">
              <v-btn tile block size="48" color="black" variant="flat" class="text-none"
                @click="handleDeleteBuildingUnit" :loading="deleteLoading">
                Delete Unit
              </v-btn>
            </v-col>
          </v-row>
        </v-toolbar>
      </v-card>
    </v-dialog>

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

<script setup lang="ts">
import { useDisplay } from 'vuetify/lib/composables/display.mjs';

const props = defineProps({
  headers: {
    type: Array as PropType<Array<Record<string, any>>>,
    default: () => [
      {
        title: "Unit Name",
        value: "name",
      },
       {
        title: "Level",
        value: "level.name",
      },
      // {
      //   title: "Block",
      //   value: "block",
      // },
      {
        title: "Block Name",
        value: "buildingName",
      },
     
      // {
      //   title: "Type",
      //   value: "type",
      // },
      // { title: "Action", value: "action-table" },
    ],
  },
  canCreate: {
    type: Boolean,
    default: true,
  },
  canUpdate: {
    type: Boolean,
    default: true,
  },
  canDelete: {
    type: Boolean,
    default: true,
  },
  canCreateUnit: {
    type: Boolean,
    default: true,
  },
  canUpdateUnit: {
    type: Boolean,
    default: true,
  },
  canDeleteUnit: {
    type: Boolean,
    default: true,
  },
  canViewUnitDetails: {
    type: Boolean,
    default: true,
  },
});

const site = (useRoute().params.site as string) ?? "";
const status = (useRoute().params.status as string) ?? "active";

const { smAndUp } = useDisplay();

const { toOrdinal } = useUtils();

const { headerSearch } = useLocal();
const { getAll, deleteById } = useBuildingUnit();
const { formatDateDDMMYYYYLocal } = useUtils();

const page = ref(1);
const pages = ref(0);
const pageRange = ref("-- - -- of --");

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

const items = ref<Array<Record<string, any>>>([]);

const {
  data: getBuildingReq,
  refresh: getBuildingUnit,
  status: getBuildingReqStatus,
} = useLazyAsyncData(
  "get-all-building-units",
  () =>
    getAll({
      page: page.value,
      search: headerSearch.value,
      status,
      site: site,
    }),
  {
    watch: [page, headerSearch],
  }
);

const loading = computed(() => getBuildingReqStatus.value === "pending");

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

function tableRowClickHandler(_: any, data: any) {
  selectedBuildingUnit.value = data.item;
  dialogPreview.value = true;
}

const createDialog = ref(false);
const dialogEdit = ref(false);
const dialogPreview = ref(false);
const selectedBuildingUnit = ref<TBuildingUnit | null>(null);

function successCreate() {
  createDialog.value = false;
  getBuildingUnit();
  showMessage("Unit created successfully!", "success");
}

function successUpdate() {
  dialogEdit.value = false;
  dialogPreview.value = false;
  getBuildingUnit();
  showMessage("Unit updated successfully!", "success");
}

function openEditDialog() {
  dialogEdit.value = true;
  if (dialogPreview.value) {
    dialogPreview.value = false;
  }
}

const dialogDelete = ref(false);
const deleteLoading = ref(false);

function openDeleteDialog() {
  dialogDelete.value = true;
  message.value = "";
  if (dialogPreview.value) {
    dialogPreview.value = false;
  }
}

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

async function handleDeleteBuildingUnit() {
  deleteLoading.value = true;
  try {
    await deleteById(selectedBuildingUnit.value?._id ?? "");
    await getBuildingUnit();
    dialogDelete.value = false;
    selectedBuildingUnit.value = null;
  } catch (error: any) {
    message.value = error?.response?._data?.message || "Failed to delete unit";
  } finally {
    deleteLoading.value = false;
  }
}

function setBuilding({
  mode = "create",
  dialog = true,
  data = {} as TBuildingUnit,
} = {}) {
  if (mode === "create") {
    createDialog.value = dialog;
  } else if (mode === "edit") {
    dialogEdit.value = dialog;
    selectedBuildingUnit.value = data;
  } else if (mode === "preview") {
    dialogPreview.value = dialog;
    selectedBuildingUnit.value = data;
  }
}
</script>

<style scoped>
  .v-data-table :deep(thead th) {
  font-weight: bold !important;
}
</style>
