<template>
  <v-row no-gutters align="center" justify="center">
    <v-col cols="12" lg="12">
      <TableMain
        :title="`${siteName} Units`"
        :items="items"
        :headers="headers"
        :loading="loading"
        :show-header="true"
        v-model:page="page"
        :pages="pages"
        :pageRange="pageRange"
        :no-data-text="`No Equipment Items found for ${siteName}.`"
        @refresh="getEquipmentItemsRefresh"
        :canCreate="canCreateEquipmentItem"
        createLabel="Equipment Item"
        @row-click="handleRowClick"
      >
        <template #actions>
          <v-row no-gutters align="center" class="w-100">
            <v-col cols="auto" v-if="canCreateEquipmentItem">
              <v-btn
                class="text-none"
                rounded="pill"
                variant="tonal"
                size="large"
                @click="openEquipmentItemDialog()"
              >
                Checkout Item
              </v-btn>
            </v-col>

            <v-spacer />

            <v-col cols="auto">
              <v-text-field
                v-model="searchInput"
                density="compact"
                placeholder="Search"
                clearable
                width="300"
                append-inner-icon="mdi-magnify"
                hide-details
              />
            </v-col>
          </v-row>
        </template>

        <template #item.createdAt="{ value }">
          <span>{{ formatDate(value) }}</span>
        </template>
      </TableMain>
    </v-col>
  </v-row>

  <v-dialog v-model="dialogShowMoreActions" width="400" persistent>
    <HygieneUpdateMoreAction
      :title="selectedSupply?.name"
      :canDelete="false"
      :canUpdate="false"
      :canApprove="false"
      :canDisapprove="false"
      :disabled="true"
      @close="dialogShowMoreActions = false"
    >
      <template #content>
        <v-row no-gutters>
          <v-col v-if="selectedSupply" cols="12" class="mb-2">
            <v-row
              no-gutters
              class="mb-3"
              v-if="
                selectedSupply.attachment && selectedSupply.attachment.length
              "
            >
              <v-col cols="12" class="d-flex justify-center">
                <v-sheet
                  rounded="lg"
                  class="overflow-hidden"
                  style="width: 100%; max-width: 360px; cursor: pointer"
                >
                  <v-img
                    :src="getFileUrl(selectedSupply.attachment[0])"
                    height="180"
                    cover
                    class="rounded-lg"
                    @click="viewAttachment(selectedSupply.attachment[0])"
                  >
                    <template v-slot:placeholder>
                      <v-row
                        class="fill-height ma-0"
                        align="center"
                        justify="center"
                      >
                        <v-progress-circular
                          indeterminate
                          color="grey-lighten-4"
                        />
                      </v-row>
                    </template>
                  </v-img>
                </v-sheet>
              </v-col>
            </v-row>

            <v-row
              no-gutters
              class="mb-3"
              v-if="
                selectedSupply.attachment &&
                selectedSupply.attachment.length > 1
              "
            >
              <v-col cols="12">
                <v-row no-gutters>
                  <v-col
                    v-for="(attId, i) in selectedSupply.attachment.slice(1)"
                    :key="attId + '-' + i"
                    cols="auto"
                    class="pa-1"
                  >
                    <v-sheet
                      rounded="sm"
                      style="
                        width: 72px;
                        height: 56px;
                        overflow: hidden;
                        cursor: pointer;
                      "
                      @click="viewAttachment(attId)"
                    >
                      <v-img :src="getFileUrl(attId)" height="56" cover />
                    </v-sheet>
                  </v-col>
                </v-row>
              </v-col>
            </v-row>

            <v-row no-gutters class="mb-2">
              <v-col cols="5" class="text-subtitle-2 font-weight-bold">
                Name:
              </v-col>
              <v-col cols="7" class="text-subtitle-2">
                {{ selectedSupply.supplyName || "N/A" }}
              </v-col>
            </v-row>

            <v-row no-gutters class="mb-2">
              <v-col cols="5" class="text-subtitle-2 font-weight-bold">
                Equipment Quantity:
              </v-col>
              <v-col cols="7" class="text-subtitle-2">
                {{ selectedSupply.qty || "N/A" }}
              </v-col>
            </v-row>

            <v-row no-gutters class="mb-2">
              <v-col cols="5" class="text-subtitle-2 font-weight-bold">
                Unit of Measurement:
              </v-col>
              <v-col cols="7" class="text-subtitle-2">
                {{ selectedSupply.unitOfMeasurement || "N/A" }}
              </v-col>
            </v-row>

            <v-row no-gutters class="mb-2">
              <v-col cols="5" class="text-subtitle-2 font-weight-bold">
                Stock Quantity:
              </v-col>
              <v-col cols="7" class="text-subtitle-2">
                {{ selectedSupply.stockQty || "N/A" }}
              </v-col>
            </v-row>
          </v-col>
        </v-row>
      </template>
    </HygieneUpdateMoreAction>
  </v-dialog>

  <!-- Main Equipment Item Dialog -->
  <v-dialog v-model="dialogEquipmentItem" max-width="540" persistent>
    <v-card>
      <v-card-title class="d-flex align-center pa-4">
        <span class="text-h6 font-weight-bold">Equipment Item</span>
        <v-spacer />
        <v-btn
          icon="mdi-close"
          variant="text"
          size="small"
          @click="dialogEquipmentItem = false"
        />
      </v-card-title>

      <v-divider />

      <v-card-text class="pa-6">
        <v-form ref="equipmentItemFormRef">
          <!-- Add Equipment Section -->
          <v-row no-gutters class="mb-4">
            <v-col cols="12">
              <InputLabel for="equipment" title="Add Equipment" class="mb-2" />
              <v-autocomplete
                v-model="selectedSupplyForAdd"
                :items="supplyItems"
                :loading="loading"
                item-title="name"
                item-value="value"
                density="comfortable"
                variant="outlined"
                placeholder="Select equipment"
                @update:model-value="addSupplyToList"
              />
            </v-col>
          </v-row>

          <!-- Selected Equipment List -->
          <v-row no-gutters v-if="equipmentItems.length > 0" class="mb-4">
            <v-col cols="12">
              <v-divider class="mb-4" />

              <div class="text-subtitle-2 font-weight-bold mb-3">
                Selected Supplies
              </div>

              <v-sheet
                v-for="(item, index) in equipmentItems"
                :key="index"
                rounded="lg"
                variant="outlined"
                class="pa-3 mb-3"
              >
                <v-row no-gutters align="center">
                  <v-col cols="12" md="8" class="pr-md-4 mb-2 mb-md-0">
                    <div class="text-body-2 font-weight-medium">
                      <span class="text-capitalize">{{ item.supplyName }}</span>
                      - (Available:
                      <span class="font-weight-bold">{{ item.stockQty }}</span
                      >)
                    </div>
                  </v-col>

                  <v-col
                    cols="12"
                    md="4"
                    class="d-flex justify-end align-center"
                  >
                    <v-text-field
                      v-model.number="item.qty"
                      :rules="[requiredRule]"
                      density="compact"
                      variant="outlined"
                      type="number"
                      min="1"
                      hide-details
                      style="max-width: 120px"
                      class="mr-2"
                    />

                    <v-menu location="bottom end">
                      <template #activator="{ props }">
                        <v-btn
                          v-bind="props"
                          icon="mdi-dots-vertical"
                          variant="text"
                          size="small"
                        />
                      </template>

                      <v-list density="compact" min-width="180">
                        <v-list-item @click="openPhotoDialog(index)">
                          <template #prepend>
                            <v-icon size="18">mdi-camera-outline</v-icon>
                          </template>
                          <v-list-item-title>Upload Photo/s</v-list-item-title>
                        </v-list-item>

                        <v-list-item
                          @click="removeSupplyFromList(index)"
                          class="text-error"
                        >
                          <template #prepend>
                            <v-icon size="18" color="error"
                              >mdi-delete-outline</v-icon
                            >
                          </template>
                          <v-list-item-title
                            >Remove Equipment</v-list-item-title
                          >
                        </v-list-item>
                      </v-list>
                    </v-menu>
                  </v-col>
                </v-row>

                <!-- Photo Preview -->
                <v-row
                  v-if="item.photoIds && item.photoIds.length"
                  no-gutters
                  class="mt-3"
                >
                  <v-col
                    v-for="(pid, pidx) in item.photoIds"
                    :key="pid + '-' + pidx"
                    cols="auto"
                    class="pa-1"
                  >
                    <v-sheet
                      rounded="sm"
                      class="photo-thumb"
                      @click="viewAttachment(pid)"
                    >
                      <v-img
                        :src="getFileUrl(pid)"
                        height="64"
                        width="88"
                        cover
                      />
                    </v-sheet>
                  </v-col>
                </v-row>

                <!-- Empty photo hint -->
                <v-row v-else no-gutters class="mt-2">
                  <v-col cols="12">
                    <div class="text-caption text-medium-emphasis">
                      No photos attached
                    </div>
                  </v-col>
                </v-row>
              </v-sheet>
            </v-col>
          </v-row>
        </v-form>
      </v-card-text>

      <v-divider />

      <v-card-actions class="pa-0">
        <v-row no-gutters>
          <v-col cols="6">
            <v-btn
              block
              variant="text"
              size="large"
              height="56"
              class="text-none font-weight-medium rounded-0"
              @click="dialogEquipmentItem = false"
            >
              Cancel
            </v-btn>
          </v-col>
          <v-col cols="6">
            <v-btn
              block
              variant="flat"
              color="black"
              size="large"
              height="56"
              class="text-none font-weight-bold rounded-0"
              :loading="submitting"
              @click="_equipmentItem()"
            >
              Equipment Item
            </v-btn>
          </v-col>
        </v-row>
      </v-card-actions>
    </v-card>
  </v-dialog>

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

  <v-dialog v-model="dialogPhotoForItem" max-width="720" persistent>
    <v-card rounded="lg">
      <v-card-title class="d-flex align-center pa-4">
        <div>
          <div class="text-h6 font-weight-bold">Item Photos</div>
          <div class="text-caption text-medium-emphasis">
            {{ equipmentItems[activePhotoIndex ?? 0]?.supplyName || "Item" }}
          </div>
        </div>

        <v-spacer />

        <v-btn
          icon="mdi-close"
          variant="text"
          size="small"
          @click="dialogPhotoForItem = false"
        />
      </v-card-title>

      <v-divider />

      <!-- Body -->
      <v-card-text class="pa-6" v-if="activePhotoIndex !== null">
        <PhotoUpload
          title="Add / Take Photos"
          v-model="currentPhotos"
          v-model:photo-ids="currentPhotoIds"
          @error="showMessage($event, 'error')"
        />
      </v-card-text>

      <v-divider />

      <!-- Footer -->
      <v-card-actions class="pa-0">
        <v-row no-gutters class="w-100">
          <v-col cols="6">
            <v-btn
              block
              variant="text"
              size="large"
              height="56"
              class="text-none font-weight-medium rounded-0"
              @click="dialogPhotoForItem = false"
            >
              Cancel
            </v-btn>
          </v-col>

          <v-col cols="6">
            <v-btn
              block
              variant="flat"
              color="black"
              size="large"
              height="56"
              class="text-none font-weight-bold rounded-0"
              @click="dialogPhotoForItem = false"
            >
              Done
            </v-btn>
          </v-col>
        </v-row>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import useEquipmentItem from "../composables/useEquipmentItem";
import useEquipmentManagement from "../composables/useEquipmentManagement";
import useFile from "../composables/useFile";
import useUtils from "../composables/useUtils";

const props = defineProps({
  orgId: { type: String, default: "" },
  site: { type: String, default: "" },
  serviceType: { type: String, default: "" },
  canViewAllEquipmentItems: { type: Boolean, default: true },
  canCreateEquipmentItem: { type: Boolean, default: false },
});

const canViewAllEquipmentItems = computed(() => props.canViewAllEquipmentItems);
const canCreateEquipmentItem = computed(() => props.canCreateEquipmentItem);

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

const headers = [
  { title: "Date", value: "createdAt" },
  { title: "Name", value: "supplyName" },
  { title: "Checkout Qty", value: "checkOutQty" },
  { title: "Checkout By", value: "checkOutByName" },
  { title: "Available Stock Qty", value: "supplyQty" },
];

const {
  getEquipmentItems,
  getEquipmentItemById,
  equipmentItems: equipmentItemApi,
} = useEquipmentItem();
const { debounce, requiredRule, formatDate } = useUtils();

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

const selectedEquipmentItemId = ref("");

const {
  data: getEquipmentItemsReq,
  refresh: getEquipmentItemsRefresh,
  pending: loading,
} = await useLazyAsyncData(
  "get-all-equipment-items",
  () =>
    getEquipmentItems({
      page: page.value,
      search: searchInput.value,
      site: props.site,
      serviceType: props.serviceType,
    }),
  {
    watch: [page, () => props.site],
  }
);

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

const debounceSearch = debounce(getEquipmentItemsRefresh, 500);
watch(
  [searchInput, endDate, startDate],
  ([]) => {
    debounceSearch();
  },
  { immediate: false, deep: true }
);

const { data: getEquipmentItemByIdReq, refresh: getEquipmentItemByIdRefresh } =
  await useLazyAsyncData<any>(
    "get-equipment-item-by-id",
    () => getEquipmentItemById(selectedEquipmentItemId.value),
    {
      immediate: false,
    }
  );

watchEffect(() => {
  if (getEquipmentItemByIdReq.value) {
    selectedSupply.value = {
      _id: getEquipmentItemByIdReq.value._id,
      supplyName: getEquipmentItemByIdReq.value.supplyName || "N/A",
      qty: getEquipmentItemByIdReq.value.qty || 0,
      unitOfMeasurement:
        getEquipmentItemByIdReq.value.supply?.unitOfMeasurement || "N/A",
      status: getEquipmentItemByIdReq.value.status || "N/A",
      site: getEquipmentItemByIdReq.value.site || "N/A",
      supply:
        getEquipmentItemByIdReq.value.supply ||
        getEquipmentItemByIdReq.value.supply?._id ||
        "N/A",
      attachment: Array.isArray(getEquipmentItemByIdReq.value.attachment)
        ? [...getEquipmentItemByIdReq.value.attachment]
        : [],
      stockQty:
        getEquipmentItemByIdReq.value.stockQty ||
        getEquipmentItemByIdReq.value.supply?.stockQty ||
        "N/A",
    };
  }
});

const { getSupplies } = useEquipmentManagement();

const { data: getSuppliesReq } = await useLazyAsyncData(
  "get-supplies-for-equipment-item",
  () =>
    getSupplies({
      site: props.site,
      limit: 100,
      serviceType: props.serviceType,
    }),
  {}
);

watchEffect(() => {
  if (getSuppliesReq.value) {
    supplyItems.value = getSuppliesReq.value.items.map((item: any) => ({
      name: item.name,
      value: item._id,
      stockQty: item.qty ?? 0,
    }));
  }
});

const supplyItems = ref<
  Array<{ name: string; value: string; stockQty: number }>
>([]);
const selectedSupplyForAdd = ref<string>("");
const equipmentItems = ref<TEquipmentItem[]>([]);

const selectedSupply = ref<Record<string, any>>({});
const message = ref("");
const messageSnackbar = ref(false);
const messageColor = ref("");

const dialogShowMoreActions = ref(false);
const dialogEquipmentItem = ref(false);
const dialogPhotoForItem = ref(false);
const activePhotoIndex = ref<number | null>(null);

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

function openEquipmentItemDialog() {
  equipmentItems.value = [];
  selectedSupplyForAdd.value = "";
  dialogEquipmentItem.value = true;
}

function addSupplyToList(supplyId: string) {
  if (!supplyId) return;

  const exists = equipmentItems.value.find((item) => item.supply === supplyId);
  if (exists) {
    showMessage("Equipment already added.");
    selectedSupplyForAdd.value = "";
    return;
  }

  const supply = supplyItems.value.find((s) => s.value === supplyId);
  if (supply) {
    equipmentItems.value.push({
      supply: supplyId,
      supplyName: supply.name,
      qty: 1,
      stockQty: supply.stockQty,
      photos: [],
      photoIds: [],
    });
  }
  selectedSupplyForAdd.value = "";
}

function removeSupplyFromList(index: number) {
  equipmentItems.value.splice(index, 1);
}

function openPhotoDialog(index: number) {
  activePhotoIndex.value = index;
  dialogPhotoForItem.value = true;
}

async function handleRowClick(data: any) {
  message.value = "";

  selectedEquipmentItemId.value = data?.item?._id;

  if (selectedEquipmentItemId.value) {
    await getEquipmentItemByIdRefresh();
  }

  dialogShowMoreActions.value = true;
}

async function _equipmentItem() {
  submitting.value = true;
  try {
    if (!equipmentItems.value.length) {
      showMessage("Add at least one equipment.");
      submitting.value = false;
      return;
    }

    const items = equipmentItems.value.map((item) => ({
      supply: item.supply,
      qty: item.qty,
      ...(item.photoIds && item.photoIds.length
        ? { attachment: [...item.photoIds] }
        : {}),
    }));

    await equipmentItemApi(props.site, { items, serviceType: props.serviceType });

    showMessage(
      `Checked out ${equipmentItems.value.length} item(s).`,
      "success"
    );
    dialogEquipmentItem.value = false;
    equipmentItems.value = [];

    await getEquipmentItemsRefresh();
  } catch (error: any) {
    console.error(error);
    showMessage(error?.data?.message, "error");
  } finally {
    submitting.value = false;
  }
}

const { getFileUrl } = useFile();

function viewAttachment(attachmentId: string) {
  if (!attachmentId) return;
  const url = getFileUrl(attachmentId);
  window.open(url, "_blank");
}

const currentPhotos = computed({
  get() {
    if (activePhotoIndex.value === null) return [];
    return equipmentItems.value[activePhotoIndex.value]?.photos || [];
  },
  set(val) {
    if (activePhotoIndex.value === null) return;
    equipmentItems.value[activePhotoIndex.value].photos = val || [];
  },
});

const currentPhotoIds = computed({
  get() {
    if (activePhotoIndex.value === null) return [];
    return equipmentItems.value[activePhotoIndex.value]?.photoIds || [];
  },
  set(val) {
    if (activePhotoIndex.value === null) return;
    equipmentItems.value[activePhotoIndex.value].photoIds = val || [];
  },
});
</script>

<style scoped></style>
