<template>
  <v-row no-gutters>
    <v-col cols="12">
      <v-row no-gutters class="mb-4" align="center">
        <v-col cols="12" md="6">
          <v-btn
            rounded="pill"
            variant="outlined"
  
            size="large"
            class="text-none px-8"
            @click="dialogAdd = true"
          >
            Add Route
          </v-btn>
        </v-col>
        <v-col cols="12" md="6" class="d-flex justify-end">
          <v-text-field
            v-model="searchInput"
            density="comfortable"
            placeholder="Search"
            clearable
            append-inner-icon="mdi-magnify"
            hide-details
            variant="outlined"
            rounded="lg"
            style="max-width: 400px"
            bg-color="white"
          />
        </v-col>
      </v-row>

      <v-card width="100%" variant="outlined" border="thin" rounded="lg">

        <v-card-text class="pa-0">
          <v-data-table
            :headers="headers"
            :items="items"
            :items-per-page="20"
            fixed-header
            hide-default-footer
            @click:row="handleRowClick"
            style="max-height: calc(100vh - 300px)"
            class="nfc-route-table"
            hover
          >
            <template #item.numberOfCheckpoints="{ value }">
              <div class="text-center">{{ value || "--" }}</div>
            </template>

            <template #item.tolerance="{ item }">
              <div class="text-center">
                <div>{{ item.tolerance ? `${item.tolerance} mins` : "--" }}</div>
                <div class="text-grey">{{ item.totalTravelTime ? `${item.totalTravelTime} mins` : "--" }}</div>
              </div>
            </template>

            <template #item.schedules="{ value }">
              <span v-if="Array.isArray(value) && value.length > 0">
                {{ value.map(s => `${s.start}-${s.end}`).join(", ") }}
              </span>
              <span v-else>--</span>
            </template>

            <template #item.repeatDays="{ value }">
              <span>{{ value || "--" }} </span>
            </template>
          </v-data-table>
        </v-card-text>

        <v-toolbar density="compact" color="grey-lighten-4">
          <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" />
            </v-row>
          </template>
        </v-toolbar>
      </v-card>
    </v-col>

    <!-- Add Dialog -->
    <v-dialog v-model="dialogAdd" persistent max-width="900">
      <NFCPatrolRouteForm
        title="Add Route"
        :site="props.site"
        :org-id="props.orgId"
        @cancel="dialogAdd = false"
        @success="handleSuccess"
        @error="handleError"
      />
    </v-dialog>

    <!-- Edit Dialog -->
    <v-dialog v-model="dialogEdit" persistent max-width="900">
      <NFCPatrolRouteForm
        title="Edit Route"
        :site="props.site"
        :org-id="props.orgId"
        @cancel="dialogEdit = false"
        @success="handleSuccess"
        @error="handleError"
        mode="edit"
        :route="selectedRoute"
      />
    </v-dialog>

    <!-- Preview Dialog -->
    <v-dialog v-model="dialogPreview" persistent width="540">
      <v-card width="100%">
        <v-toolbar>
          <v-row no-gutters class="fill-height px-6" align="center">
            <span class="font-weight-bold text-h5 text-capitalize">
              Route Details
            </span>
          </v-row>
        </v-toolbar>

        <v-card-text
          style="max-height: 100vh; overflow-y: auto"
          class="pa-5 my-5 px-7"
        >
          <v-row no-gutters>
            <v-col cols="12" class="mb-2">
              Route Name:
              <span class="font-weight-bold">
                {{ selectedRoute.routeName }}
              </span>
            </v-col>

            <v-col cols="12" class="mb-2" v-if="selectedRoute.numberOfCheckpoints">
              Number of Checkpoints:
              <span class="font-weight-bold">
                {{ selectedRoute.numberOfCheckpoints }}
              </span>
            </v-col>

            <v-col cols="12" class="mb-2" v-if="selectedRoute.tolerance">
              Tolerance:
              <span class="font-weight-bold">
                {{ selectedRoute.tolerance }} mins
              </span>
            </v-col>

            <v-col
              cols="12"
              class="mb-2"
              v-if="selectedRoute.totalTravelTime"
            >
              Total Travel Time:
              <span class="font-weight-bold">
                {{ selectedRoute.totalTravelTime }} mins
              </span>
            </v-col>

            <v-col cols="12" class="mb-2" v-if="selectedRoute.repeatDays">
              Repeat Every:
              <span class="font-weight-bold">
                {{ selectedRoute.repeatDays }}
              </span>
            </v-col>

            <v-col
              cols="12"
              class="mb-2"
              v-if="selectedRoute.schedules && selectedRoute.schedules.length"
            >
              Security Check Schedule:
              <span class="font-weight-bold">
                {{ selectedRoute.schedules.map(s => `${s.start}-${s.end}`).join(", ") }}
              </span>
            </v-col>

            <v-col
              cols="12"
              class="mb-2"
              v-if="selectedRoute.checkpoints && selectedRoute.checkpoints.length"
            >
              Checkpoints:
              <div class="font-weight-bold">
                <div v-for="(cp, idx) in selectedRoute.checkpoints" :key="idx" class="my-1">
                  {{ idx + 1 }}. NFC Tag ID: {{ cp.nfcTagId }} - Travel Time: {{ cp.travelTime }} min
                </div>
              </div>
            </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="dialogPreview = false"
                height="48"
              >
                Close
              </v-btn>
            </v-col>

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

                <v-list class="pa-0">
                  <v-list-item @click="openDialogEdit()">
                    <v-list-item-title class="text-subtitle-2">
                      Edit Route
                    </v-list-item-title>
                  </v-list-item>

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

    <!-- Delete Dialog -->
    <v-dialog v-model="dialogDelete" persistent width="540">
      <v-card width="100%">
        <v-card-text
          style="max-height: 100vh; overflow-y: auto"
          class="pa-5 my-5 px-7 text-center"
        >
          Are you sure you want to delete this route?
        </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"
                tile
                @click="dialogDelete = false"
                height="48"
              >
                Cancel
              </v-btn>
            </v-col>

            <v-col cols="6" class="pa-0">
              <v-btn
                block
                tile
                variant="flat"
                class="text-none"
                size="large"
                height="48"
                color="black"
                @click="submitDelete()"
              >
                Delete
              </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 useNFCPatrolRoute from "../../composables/useNFCPatrolRoute";

const props = defineProps({
  site: {
    type: String,
    required: true,
  },
  siteName: {
    type: String,
    default: "",
  },
  orgId: {
    type: String,
    required: true,
  },
  headers: {
    type: Array as PropType<Array<any>>,
    default: () => [
      { title: "Route Name", value: "routeName", align: "start" },
      { title: "Checkpoints", value: "numberOfCheckpoints", align: "center" },
      { 
        title: "Tolerance (mins)\nTotal Travel Time (mins)", 
        value: "tolerance", 
        align: "center",
        sortable: false
      },
      { title: "Security Check Schedule", value: "schedules", align: "start" },
      { title: "Route Schedule", value: "repeatDays", align: "start" },
    ],
  },
});

const items = ref<Array<any>>([]);
const page = ref(1);
const pages = ref(0);
const pageRange = ref("1-20 of 1");
const searchInput = ref("");

const { getAll: getAllRoutes, getById: getRouteById, deleteById: deleteRouteById } =
  useNFCPatrolRoute();

function calculateEndTime(startTime: string, toleranceMinutes: number): string {
  if (!startTime) return '';
  
  const [hours, minutes] = startTime.split(':').map(Number);
  if (isNaN(hours) || isNaN(minutes)) return startTime;
  
  const totalMinutes = hours * 60 + minutes + toleranceMinutes;
  const wrappedMinutes = ((totalMinutes % 1440) + 1440) % 1440;
  
  const endHours = String(Math.floor(wrappedMinutes / 60)).padStart(2, '0');
  const endMins = String(wrappedMinutes % 60).padStart(2, '0');
  
  return `${endHours}:${endMins}`;
}

// Use a reactive trigger for manual refresh
const refreshTrigger = ref(0);

const { data: getRoutesReq, refresh: getRoutesRefresh } =
  await useLazyAsyncData(
    `get-nfc-routes-${props.site}`,
    () =>
      getAllRoutes({
        site: props.site,
        page: page.value,
        search: searchInput.value,
      }),
    {
      watch: [page, searchInput, refreshTrigger],
    }
  );

watchEffect(() => {
  if (getRoutesReq.value) {
    items.value = getRoutesReq.value.items?.map((item: any) => ({
      // Original API fields for editing
      _id: item._id,
      name: item.name,
      checkPointNumber: item.checkPointNumber,
      tolerance: item.tolerance,
      totalTravelTime: item.totalTravelTime,
      days: item.days,
      startTimes: item.startTimes || [],
      checkPoints: item.checkPoints || [],
      // Display fields for the table
      routeName: item.name,
      numberOfCheckpoints: item.checkPointNumber,
      schedules: item.startTimes?.map((time: string) => ({
        start: time,
        end: calculateEndTime(time, item.tolerance || 0)
      })) || [],
      repeatDays: item.days?.map((d: number) => {
        const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
        return dayNames[d];
      }).join(', ') || '--',
      checkpoints: item.checkPoints?.map((cp: any) => ({
        nfcTagId: cp.nfcTag_id,
        travelTime: cp.travelTime
      })) || []
    })) || [];
    
    pageRange.value = getRoutesReq.value.pageRange;
    pages.value = getRoutesReq.value.pages;
  }
});

const dialogAdd = ref(false);
const dialogEdit = ref(false);
const dialogPreview = ref(false);
const dialogDelete = ref(false);

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

async function openDialogEdit() {
  try {
    // Fetch the full route details from the API
    const response = await getRouteById(selectedRoute.value._id);
    
    // Extract the nfcPatrolRoute from the nested response
    const fullRouteData = response.data?.nfcPatrolRoute || response.nfcPatrolRoute || response;
    
    // Update selectedRoute with the full data from API
    selectedRoute.value = {
      ...selectedRoute.value,
      ...fullRouteData,
      // Ensure the display fields are preserved
      routeName: fullRouteData.name,
      numberOfCheckpoints: fullRouteData.checkPointNumber,
    };
    
    dialogEdit.value = true;
    if (dialogPreview.value) dialogPreview.value = false;
  } catch (error) {
    console.error('Error fetching route details:', error);
    handleError(error);
  }
}

function openDialogDelete() {
  dialogDelete.value = true;

  if (dialogPreview.value) dialogPreview.value = false;
}

async function handleSuccess() {
  try {
    // Small delay to ensure backend has processed the update
    await new Promise(resolve => setTimeout(resolve, 300));
    
    // Trigger refresh by incrementing the refresh trigger
    refreshTrigger.value++;
    
    // Also call refresh to ensure data is fetched
    await getRoutesRefresh();
    
    // Wait for next tick to ensure reactivity completes
    await nextTick();
    
    if (dialogAdd.value) {
      dialogAdd.value = false;
      showMessage("Route created successfully!", "success");
    }

    if (dialogEdit.value) {
      dialogEdit.value = false;
      showMessage("Route updated successfully!", "success");
    }

    if (dialogPreview.value) dialogPreview.value = false;

    if (dialogDelete.value) dialogDelete.value = false;
  } catch (error) {
    console.error('Error refreshing routes:', error);
  }
}

function handleError(error: any) {
  const errorMessage =
    error?.data?.message || error?.message || "An error occurred";
  showMessage(errorMessage, "error");
}

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

const selectedRoute = ref<any>({
  _id: "",
  name: "",
  routeName: "",
  checkPointNumber: 5,
  numberOfCheckpoints: 5,
  tolerance: undefined,
  totalTravelTime: undefined,
  days: [],
  repeatDays: "",
  startTimes: [],
  schedules: [],
  checkPoints: [],
  checkpoints: [],
});

function handleRowClick(_: any, data: any) {
  dialogPreview.value = true;
  selectedRoute.value = JSON.parse(JSON.stringify(data.item));
}

async function submitDelete() {
  try {
    await deleteRouteById(selectedRoute.value._id ?? "");
    await getRoutesRefresh();
    dialogDelete.value = false;
    showMessage("Route deleted successfully!", "success");
  } catch (error) {
    console.error("Error deleting route:", error);
    handleError(error);
  }
}
</script>

<style scoped>
.nfc-route-table :deep(.v-data-table__th) {
  background-color: rgb(250, 250, 250);
  font-weight: 500;
  white-space: pre-line;
  padding: 16px 12px !important;
  border-bottom: 1px solid rgba(0, 0, 0, 0.12);
}

.nfc-route-table :deep(.v-data-table__td) {
  padding: 16px 12px !important;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.nfc-route-table :deep(tbody tr:hover) {
  background-color: rgba(0, 0, 0, 0.02) !important;
  cursor: pointer;
}

.nfc-route-table :deep(.v-data-table__tr) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}
</style>
