<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 && canCreateBuilding">
          Add Block
        </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="getBuildings()">
              <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="getBuildings()" />
            </v-row>
          </template>
        </v-toolbar>

        <v-data-table :headers="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.createdAt="{ value }">
            {{ new Date(value).toLocaleDateString() }}
          </template>
          <template #item.levels="{ item }">
            {{ item.levels.length }}
          </template>
        </v-data-table>
      </v-card>
    </v-col>

    <!-- Create Dialog -->
    <v-dialog v-model="createDialog" width="450" persistent>
      <BuildingForm :site="site" mode="add" :blocks="items" @cancel="createDialog = false" @success="successCreate()"
        @success:create-more="getBuildings()" />
    </v-dialog> 

    <!-- Edit Dialog -->
    <v-dialog v-model="editDialog" width="450" persistent>
      <BuildingForm :site="site" :blocks="items" mode="edit" @cancel="editDialog = false" @success="successUpdate()"
        :building="selectedBuilding" @refresh="getBuildings()" />
    </v-dialog>

    <!-- Preview Dialog -->
    <v-dialog v-if="canViewBuildingDetails" v-model="previewDialog" width="450" persistent>
      <v-card width="100%">
        <v-card-text style="max-height: 100vh; overflow-y: auto" class="pb-0">
          <v-row no-gutters class="mb-4">
            <v-col cols="12">
              <strong>Name:</strong> {{ selectedBuilding?.name ?? "N/A" }}
            </v-col>

            <v-col cols="12">
              <strong>Block:</strong>
              {{ selectedBuilding?.block ?? "N/A" }}
            </v-col>

            <v-col cols="12">
              <strong>Levels:</strong>
              {{ selectedBuilding?.levels.length ?? "N/A" }}
            </v-col>
            <v-col cols="12">
              <strong>Files:</strong>
              <div v-if="selectedBuilding?.buildingFiles?.length" class="">
                <AttachmentsViewer :files="selectedBuilding.buildingFiles" title="" show-file-type-title />
              </div>
              <span v-else> None</span>
            </v-col>
          </v-row>
        </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="previewDialog = false" height="48">
                Close
              </v-btn>
            </v-col>

            <v-col cols="6" class="pa-0" v-if="canUpdate">
              <v-menu>
                <template #activator="{ props }">
                  <v-btn block variant="flat" color="black" class="text-none" height="48" v-bind="props" tile
                    :disabled="!canUpdateBuilding && !canDeleteBuilding">
                    More actions
                  </v-btn>
                </template>

                <v-list class="pa-0">
                  <v-list-item v-if="canUpdateBuilding" @click="openEditDialog()">
                    <v-list-item-title class="text-subtitle-2">
                      Edit Building
                    </v-list-item-title>
                  </v-list-item>

                  <v-list-item v-if="canDeleteBuilding" @click="openDeleteDialog()" class="text-red">
                    <v-list-item-title class="text-subtitle-2">
                      Delete Building
                    </v-list-item-title>
                  </v-list-item>
                </v-list>
              </v-menu>
            </v-col>
          </v-row>
        </v-toolbar>
      </v-card>
    </v-dialog>

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

        <v-card-text>
          <p class="text-subtitle-2 text-center">
            Are you sure you want to delete this building? 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="confirmDialog = 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="handleDeleteBuilding"
                :loading="deleteLoading">
                Delete Building
              </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">
definePageMeta({
  middleware: ["01-auth", "02-org"],
  memberOnly: true,
});

const props = defineProps({
  headers: {
    type: Array as PropType<Array<Record<string, any>>>,
    default: () => [
      {
        title: "Name",
        value: "name",
      },
      {
        title: "Block",
        value: "block",
        align: "center",
      },
      {
        title: "Levels",
        value: "levels",
        align: "center",
      },
      // { title: "Action", value: "action-table" },
    ],
  },
  canCreate: {
    type: Boolean,
    default: true,
  },
  canUpdate: {
    type: Boolean,
    default: true,
  },
  canDelete: {
    type: Boolean,
    default: true,
  },
  canCreateBuilding: {
    type: Boolean,
    default: true,
  },
  canUpdateBuilding: {
    type: Boolean,
    default: true,
  },
  canDeleteBuilding: {
    type: Boolean,
    default: true,
  },
  canViewBuildingDetails: {
    type: Boolean,
    default: true,
  },
});

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

const { headerSearch } = useLocal();
const { getAll: _getBuildings, deleteById } = useBuilding();

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: getBuildings,
  status: getBuildingReqStatus,
} = useLazyAsyncData(
  "buildings-get-all",
  () =>
    _getBuildings({
      page: page.value,
      search: headerSearch.value,
      status,
      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;
  }
});

const createDialog = ref(false);
const editDialog = ref(false);
const previewDialog = ref(false);
const selectedBuilding = ref<TBuilding>({
  _id: "",
  site: "",
  name: "",
  block: null,
  levels: [],
  buildingFiles: [],
});

function tableRowClickHandler(_: any, data: any) {
  selectedBuilding.value = data.item as TBuilding;
  previewDialog.value = true;
}

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

function successUpdate() {
  editDialog.value = false;
  previewDialog.value = false;
  getBuildings();
  showMessage("Building updated successfully!", "success");
}

function openEditDialog() {
  editDialog.value = true;
}

const confirmDialog = ref(false);
const selectedBuildingId = ref<string | null>(null);
const deleteLoading = ref(false);

function openDeleteDialog() {
  confirmDialog.value = true;
  message.value = "";
}

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

async function handleDeleteBuilding() {
  deleteLoading.value = true;
  try {
    await deleteById(selectedBuilding.value._id ?? "");
    await getBuildings();
    selectedBuildingId.value = null;
    confirmDialog.value = false;
    previewDialog.value = false
  } catch (error: any) {
    message.value =
      error?.response?._data?.message || "Failed to delete region";
  } finally {
    deleteLoading.value = false;
  }
}

function setBuilding({
  mode = "create",
  dialog = true,
  data = {} as TBuilding,
} = {}) {
  if (mode === "create") {
    createDialog.value = dialog;
  } else if (mode === "edit") {
    editDialog.value = dialog;
    selectedBuilding.value = data;
  } else if (mode === "preview") {
    previewDialog.value = dialog;
    selectedBuilding.value = data;
  }
}
</script>
<style scoped>
.v-data-table :deep(thead th) {
  font-weight: bold !important;
}
</style>
