<template>
  <v-row no-gutters align="center" justify="center">
    <v-col cols="12" lg="12">
      <TableMain
        :title="'Cleaner Checklist'"
        :headers="headers"
        :items="items"
        :loading="loading"
        :show-header="true"
        v-model:page="page"
        :pages="pages"
        :pageRange="pageRange"
        @update:items="items = $event"
        @refresh="getAreaChecklistHistoryRefresh"
        @row-click="handleRowClick"
      >
        <template #actions>
          <v-row class="w-100" align="center" no-gutters>
            <v-col cols="auto">
              <v-btn
                variant="text"
                color="primary"
                class="text-none"
                @click="back"
              >
                <v-icon left>mdi-arrow-left</v-icon>
                Back
              </v-btn>
            </v-col>
          </v-row>
        </template>

        <template #extension>
          <v-row no-gutters class="w-100 d-flex flex-column">
            <v-card
              class="w-100 px-3 d-flex align-center ga-5 py-2"
              flat
              :height="60"
            >
              <v-text-field
                v-model="searchInput"
                density="compact"
                placeholder="Search"
                clearable
                max-width="300"
                append-inner-icon="mdi-magnify"
                hide-details
              />
              <v-select
                v-model="status"
                :items="statusOptions"
                item-title="label"
                item-value="value"
                density="compact"
                clearable
                hide-details
                max-width="200"
              />
            </v-card>
          </v-row>
        </template>

        <template #item.createdAt="{ value, item }">
          <div>
            {{
              formatDate
                ? formatDate(value)
                : value
                ? new Date(value).toLocaleString()
                : ""
            }}
            <span v-if="item?.endedAt">
              -
              {{
                formatDate
                  ? formatDate(item.endedAt)
                  : new Date(item.endedAt).toLocaleString()
              }}</span
            >
          </div>
        </template>
        <template #item.status="{ value }">
          <v-chip class="text-capitalize">{{ value || "No Status" }}</v-chip>
        </template>
      </TableMain></v-col
    >
  </v-row>

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

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

const props = defineProps({
  orgId: { type: String, required: true, default: "" },
  site: { type: String, required: true, default: "" },
  scheduleAreaId: { type: String, required: true, default: "" },
  type: { type: String, required: true, default: "cleaner" },
  scheduleRoute: { type: String, default: "pest-schedule" },
});

const { formatDate, back, debounce } = useUtils();

const loading = ref(false);
const message = ref("");
const messageSnackbar = ref(false);
const messageColor = ref("");
const searchInput = ref("");
const page = ref(1);
const pages = ref(0);
const pageRange = ref("-- - -- of --");

const headers = [
  { title: "Area / Created Date", value: "name" },
  { title: "Time In / Time Out", value: "createdAt" },
  { title: "Status", value: "status" },
  { title: "No. Of Visits", value: "set" },
  { title: "Type", value: "type" },
];

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

const route = useRoute();
const router = useRouter();

const status = ref<string>((route.query.status as string) ?? "ongoing");
const statusOptions = [
  { label: "Ongoing", value: "ongoing" },
  { label: "Completed", value: "completed" },
];

watch(status, (v) => {
  const newQuery: Record<string, any> = {
    ...(route.query as Record<string, any>),
  };
  if (v) {
    newQuery.status = v;
  } else {
    delete newQuery.status;
  }
  router.replace({ query: newQuery }).catch(() => {});
});

const { getAreaChecklistHistory } = useCleaningSchedules();

const {
  data: getAreaChecklistHistoryReq,
  refresh: getAreaChecklistHistoryRefresh,
} = await useLazyAsyncData(
  "get-area-checklist-history",
  () =>
    getAreaChecklistHistory({
      parentChecklistId: props.scheduleAreaId,

      page: page.value,
      status: status.value,
      search: searchInput.value,
    }),
  {
    watch: [
      page,
      () => status.value,
      () => props.site,
      () => props.scheduleAreaId,
      () => props.type,
    ],
  }
);

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

const debouncedSearchRefresh = debounce(() => {
  const wasPage = page.value;
  page.value = 1;
  if (wasPage === 1) {
    getAreaChecklistHistoryRefresh();
  }
}, 450);

watch(searchInput, () => {
  debouncedSearchRefresh();
});

function handleRowClick(data: any) {
  const item = data?.item ?? data;
  const id = item?._id || item?.id || item?.areaId;

  if (id) {
    if (props.type === "toilet") {
      const path = `/${props.orgId}/${props.site}/toilet-checklist/${props.scheduleAreaId}/history/${id}`;
      navigateTo(path);
      return;
    }
    const path = `/${props.orgId}/${props.site}/${props.scheduleRoute}/${props.scheduleAreaId}/history/${id}`;
    navigateTo(path);
  }
}
</script>
