<template>
  <v-card width="100%" max-width="800">
    <v-toolbar color="white" elevation="0">
      <v-row no-gutters class="fill-height px-6" align="center">
        <span class="font-weight-bold text-h5">
          {{ title }}
        </span>
      </v-row>
    </v-toolbar>

    <v-divider />

    <v-card-text style="max-height: 70vh; overflow-y: auto" class="pa-6">
      <v-form ref="formRef" v-model="valid" @submit.prevent="submit">
        <v-row no-gutters>
          <!-- Route Name -->
          <v-col cols="12" class="mb-4">
            <label class="text-caption text-grey-darken-1 mb-1 d-block">
              Route Name <span class="text-red">*</span>
            </label>
            <v-text-field
              v-model="form.name"
              placeholder="Enter route name"
              variant="outlined"
              density="comfortable"
              :rules="[rules.required]"
              hide-details="auto"
            />
          </v-col>

          <!-- Checkpoints, Tolerance, Repeat Every -->
          <v-col cols="12" md="4" class="mb-4 pr-md-2">
            <label class="text-caption text-grey-darken-1 mb-1 d-block">
              Checkpoints <span class="text-red">*</span>
            </label>
            <v-select
              v-model="form.checkPointNumber"
              :items="checkpointOptions"
              variant="outlined"
              density="comfortable"
              hide-details
              @update:model-value="updateCheckpointsCount"
            />
          </v-col>

          <v-col cols="12" md="4" class="mb-4 px-md-1">
            <label class="text-caption text-grey-darken-1 mb-1 d-block">
              Tolerance (mins) <span class="text-red">*</span>
            </label>
            <v-text-field
              v-model="form.tolerance"
              placeholder="60 mins"
              variant="outlined"
              density="comfortable"
              hide-details
            />
          </v-col>

          <v-col cols="12" md="4" class="mb-4 pl-md-2">
            <label class="text-caption text-grey-darken-1 mb-1 d-block">
              Days <span class="text-red">*</span>
            </label>
            <v-select
              v-model="form.days"
              :items="dayOptions"
              multiple
              variant="outlined"
              density="comfortable"
              hide-details
              chips
            />
          </v-col>

          <!-- Start Times -->
          <v-col cols="12" class="mb-4">
            <v-card variant="outlined" class="pa-4" rounded="lg">
              <div class="d-flex align-center justify-space-between mb-3">
                <span class="text-h6 font-weight-medium">Start Times</span>
                <span class="text-body-2 text-grey-darken-1">Schedule</span>
              </div>

              <!-- Start Time Slots -->
              <div
                v-for="(startTime, index) in form.startTimes"
                :key="startTimeKeys[index]"
              >
                <v-divider v-if="index > 0" class="mb-3" />
                <v-row no-gutters class="mb-2 align-center">
                  <v-col cols="12" md="" lg="" class="pr-2">
                    <v-text-field
                      v-model="form.startTimes[index]"
                      label="Start Time"
                      placeholder="08:00"
                      variant="filled"
                      density="comfortable"
                      prepend-inner-icon="mdi-clock-outline"
                      hide-details
                      type="time"
                      bg-color="grey-lighten-4"
                      rounded="lg"
                      @update:model-value="syncEndTimeAt(index)"
                    />
                  </v-col>
                  <v-col
                    cols="12"
                    md=""
                    lg=""
                    class="pr-2 mt-4 mt-sm-2 mt-md-0"
                  >
                    <v-text-field
                      v-model="form.endTimes[index]"
                      label="End Time"
                      placeholder="08:00"
                      variant="filled"
                      density="comfortable"
                      prepend-inner-icon="mdi-clock-outline"
                      hide-details
                      type="time"
                      bg-color="grey-lighten-2"
                      rounded="lg"
                      readonly
                    />
                  </v-col>
                  <v-col
                    cols="12"
                    md="auto"
                    lg="auto"
                    class="d-flex justify-end mt-4 mt-sm-2 mt-md-0"
                  >
                    <v-btn
                      v-if="index === form.startTimes.length - 1"
                      icon
                      size="small"
                      color="primary"
                      variant="flat"
                      rounded="lg"
                      @click="addStartTime"
                    >
                      <v-icon size="large">mdi-plus</v-icon>
                    </v-btn>
                    <v-btn
                      v-else
                      icon
                      size="small"
                      color="error"
                      variant="flat"
                      rounded="lg"
                      @click="removeStartTime(index)"
                    >
                      <v-icon size="large">mdi-delete-outline</v-icon>
                    </v-btn>
                  </v-col>
                </v-row>
              </div>
            </v-card>
          </v-col>

          <!-- Checkpoints Table -->
          <v-col cols="12" class="mb-2">
            <v-row no-gutters class="mb-2">
              <v-col
                cols="2"
                class="text-caption text-grey-darken-1 font-weight-medium"
              >
                Checkpoints
              </v-col>
              <v-col
                cols="6"
                class="text-caption text-grey-darken-1 font-weight-medium pl-4"
              >
                NFC Tag
              </v-col>
              <v-col
                cols="4"
                class="text-caption text-grey-darken-1 font-weight-medium text-right"
              >
                Travel time
              </v-col>
            </v-row>
          </v-col>

          <v-col cols="12" class="mb-4">
            <v-row
              v-for="(checkpoint, index) in form.checkPoints"
              :key="index"
              no-gutters
              class="mb-3 align-center"
            >
              <v-col cols="1" class="text-body-2">
                {{ index + 1 }}
              </v-col>
              <v-col cols="7" class="pr-2">
                <v-select
                  v-model="checkpoint.nfcTag_id"
                  :items="nfcTags"
                  item-title="name"
                  item-value="_id"
                  placeholder="Select NFC Tag"
                  variant="outlined"
                  density="compact"
                  hide-details
                />
              </v-col>
              <v-col cols="4">
                <v-text-field
                  v-model.number="checkpoint.travelTime"
                  placeholder="10"
                  variant="outlined"
                  density="compact"
                  hide-details
                  suffix="min"
                  type="number"
                />
              </v-col>
            </v-row>
          </v-col>

          <!-- Summary -->
          <v-col cols="12">
            <v-row no-gutters class="mb-2">
              <v-col cols="6" class="text-body-2 text-grey-darken-1">
                Tolerance Balance:
                <span class="font-weight-bold text-grey-darken-3"
                  >{{ toleranceBalance }} min</span
                >
              </v-col>
              <v-col cols="6" class="text-body-2 text-grey-darken-1 text-right">
                Total Travel Time:
                <span class="font-weight-bold text-grey-darken-3"
                  >{{ totalTravelTime }} min</span
                >
              </v-col>
            </v-row>
          </v-col>
        </v-row>
      </v-form>
    </v-card-text>

    <v-divider />

    <v-toolbar class="pa-0" density="compact" color="white" elevation="0">
      <v-row no-gutters>
        <v-col cols="6" class="pa-0">
          <v-btn
            block
            variant="text"
            class="text-none"
            size="large"
            @click="handleCancel"
            height="56"
            :disabled="loading"
            rounded="0"
          >
            Cancel
          </v-btn>
        </v-col>

        <v-col cols="6" class="pa-0">
          <v-btn
            block
            variant="flat"
            class="text-none"
            size="large"
            height="56"
            color="primary"
            @click="submit"
            :loading="loading"
            :disabled="!valid || loading"
            rounded="0"
          >
            Submit
          </v-btn>
        </v-col>
      </v-row>
    </v-toolbar>
    <Snackbar v-model="messageSnackbar" :text="message" :color="messageColor" />
  </v-card>
</template>

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

const props = defineProps({
  title: {
    type: String,
    default: "Add Route",
  },
  site: {
    type: String,
    required: true,
  },
  orgId: {
    type: String,
    required: true,
  },
  mode: {
    type: String as PropType<"create" | "edit">,
    default: "create",
  },
  route: {
    type: Object as PropType<any>,
    default: () => ({
      routeName: "",
      numberOfCheckpoints: 5,
      tolerance: "",
      repeatDays: "Mon, Tue, Wed, Thu, Friday",
      schedules: [{ start: "13:00", end: "14:00" }],
      checkpoints: [],
    }),
  },
});

const emit = defineEmits(["cancel", "success", "error"]);

const message = ref<string>("");
const messageSnackbar = ref<boolean>(false);
const messageColor = ref<string>("");

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

// Reset form initialized flag when canceling
function handleCancel() {
  formInitialized.value = false;
  emit("cancel");
}

const formRef = ref();
const valid = ref(false);
const loading = ref(false);

interface Checkpoint {
  nfcTag_id: string;
  travelTime: number;
}

const form = ref({
  name: "",
  checkPointNumber: 5,
  tolerance: "60",
  days: [1, 6] as number[],
  startTimes: ["08:00"] as string[],
  endTimes: ["09:00"] as string[],
  checkPoints: [] as Checkpoint[],
});

const startTimeKeys = ref<number[]>([Date.now()]);

const checkpointOptions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const dayOptions = [
  { title: "Monday", value: 1 },
  { title: "Tuesday", value: 2 },
  { title: "Wednesday", value: 3 },
  { title: "Thursday", value: 4 },
  { title: "Friday", value: 5 },
  { title: "Saturday", value: 6 },
  { title: "Sunday", value: 0 },
];

const rules = {
  required: (v: any) => !!v || "This field is required",
};

// Fetch NFC Tags
const nfcTags = ref<Array<any>>([]);
const { getAll: getAllNFCTags } = useNFCPatrolTag();

async function fetchNFCTags() {
  try {
    const response = await getAllNFCTags({ site: props.site, limit: 100 });
    nfcTags.value = response.items || [];
  } catch (error) {
    console.error("Error fetching NFC tags:", error);
  }
}

// Initialize checkpoints based on number
function updateCheckpointsCount(count: number) {
  const currentLength = form.value.checkPoints.length;

  if (count > currentLength) {
    // Add new checkpoints
    for (let i = currentLength; i < count; i++) {
      form.value.checkPoints.push({
        nfcTag_id: "",
        travelTime: 10,
      });
    }
  } else if (count < currentLength) {
   
    form.value.checkPoints = form.value.checkPoints.slice(0, count);
  }

}


const hasDuplicateStartTimes = computed(() => {
  const uniqueTimes = new Set(form.value.startTimes);
  return uniqueTimes.size !== form.value.startTimes.length;
});

function getEndTime(timeStr: string, minutesToAdd: number | null): string {
  if (!timeStr) return "";

  const [hh, mm] = timeStr.split(":").map(Number);
  if (Number.isNaN(hh) || Number.isNaN(mm)) return timeStr;

  const total = hh * 60 + mm + Number(minutesToAdd || 0);
  const wrapped = ((total % 1440) + 1440) % 1440;

  const outH = String(Math.floor(wrapped / 60)).padStart(2, "0");
  const outM = String(wrapped % 60).padStart(2, "0");
  return `${outH}:${outM}`;
}

function syncEndTimeAt(index: number) {
  form.value.endTimes[index] = getEndTime(
    form.value.startTimes[index],
    minutesToAddForEndTime.value
  );
}

const minutesToAddForEndTime = computed(() => {
  return Number.parseInt(form.value.tolerance || "0", 10) || 0;
});

function syncAllEndTimes() {
  if (hasDuplicateStartTimes.value)
    return showMessage("Duplicate start times are not allowed.", "error");

  const mins = minutesToAddForEndTime.value;
  form.value.endTimes = form.value.startTimes.map((t) => getEndTime(t, mins));
}

watch(
  [() => form.value.startTimes, () => minutesToAddForEndTime.value],
  () => syncAllEndTimes(),

  { deep: true, immediate: true }
);

function addStartTime() {
  if (hasDuplicateStartTimes.value)
    return showMessage("Duplicate start times are not allowed.", "error");

  const times = form.value.startTimes;
  let candidateTime = times.length > 0 ? times[times.length - 1] : "08:00";

  if (times.length > 0) {
    candidateTime = getEndTime(candidateTime, 1);
  }

  let safetyCounter = 0;
  while (times.includes(candidateTime) && safetyCounter < 1440) {
    candidateTime = getEndTime(candidateTime, 1);
    safetyCounter++;
  }

  form.value.startTimes = [...times, candidateTime];
  startTimeKeys.value = [...startTimeKeys.value, Date.now() + Math.random()];
}

function removeStartTime(index: number) {
  form.value.startTimes.splice(index, 1);
  form.value.endTimes.splice(index, 1);
  startTimeKeys.value.splice(index, 1);
}

// Computed values
const totalTravelTime = computed(() => {
  const total = form.value.checkPoints.reduce((sum, checkpoint) => {
    return sum + (checkpoint.travelTime || 0);
  }, 0);
  return total;
});

const toleranceBalance = computed(() => {
  const tolerance = parseInt(form.value.tolerance) || 0;
  const balance = tolerance - totalTravelTime.value;
  return balance;
});

// Initialize form
onMounted(() => {
  fetchNFCTags();

  if (props.mode === "create") {
    updateCheckpointsCount(form.value.checkPointNumber);
  }
});


const formInitialized = ref(false);

// Function to initialize form for edit mode
async function initializeEditForm(newRoute: any) {
  if (!newRoute || !newRoute._id) return;
  
  // Ensure NFC tags are loaded first
  if (nfcTags.value.length === 0) {
    await fetchNFCTags();
  }
  
  const startTimes =
    Array.isArray(newRoute.startTimes) && newRoute.startTimes.length > 0
      ? [...newRoute.startTimes]
      : ["08:00"];

  const endTimes = startTimes.map((t) =>
    getEndTime(t, minutesToAddForEndTime.value)
  );

  const existingCheckPoints =
    Array.isArray(newRoute.checkPoints) && newRoute.checkPoints.length > 0
      ? newRoute.checkPoints.map((cp: any) => ({
          nfcTag_id: cp.nfcTag_id || "",
          travelTime: cp.travelTime || 10
        }))
      : [];

  // Set form values
  form.value.name = newRoute.name || "";
  form.value.checkPointNumber = newRoute.checkPointNumber || existingCheckPoints.length || 5;
  form.value.tolerance = newRoute.tolerance?.toString() || "60";
  form.value.days = Array.isArray(newRoute.days) ? [...newRoute.days] : [1, 6];
  form.value.startTimes = startTimes;
  form.value.endTimes = endTimes;
  form.value.checkPoints = existingCheckPoints;

  // Reinitialize keys for each start time
  startTimeKeys.value = startTimes.map(() => Date.now() + Math.random());

  formInitialized.value = true;
}

watch(
  () => props.route,
  (newRoute) => {
    if (props.mode === "edit" && newRoute && newRoute._id) {
      // Reset initialized flag to allow re-initialization
      formInitialized.value = false;
      // Initialize form with route data
      nextTick(() => {
        initializeEditForm(newRoute);
      });
    }
  },
  { immediate: true, deep: true }
);

const { add: addRoute, updateById: updateRoute } = useNFCPatrolRoute();

async function submit() {
  const { valid: isValid } = await formRef.value.validate();

  if (!isValid) return;

  try {
    loading.value = true;

  
    const uniqueStartTimes = [
      ...new Set(
        form.value.startTimes.filter((time) => time && time.trim() !== "")
      ),
    ];

    const payload = {
      name: form.value.name,
      checkPointNumber: form.value.checkPointNumber,
      tolerance: form.value.tolerance,
      days: form.value.days,
      startTimes: uniqueStartTimes,
      checkPoints: form.value.checkPoints,
      site: props.site,
    };

    if (props.mode === "create") {
      await addRoute(payload);
    } else {
      await updateRoute(props.route._id, payload);
    }

    formInitialized.value = false;
    emit("success");
  } catch (error) {
    emit("error", error);
  } finally {
    loading.value = false;
  }
}
</script>
