<template>
  <v-row no-gutters>
    <TableMain :headers="headers" :items="items" :loading="loading || getVehiclesPending" :page="page" :pages="pages"
      :pageRange="pageRange" :extension-height="70" :canCreate="canCreateVehicle" @refresh="getVehiclesRefresh"
      createLabel="Add Vehicle" show-header @row-click="handleRowClick" @create="handleAddVehicleClick"
      @update:page="handleUpdatePage">

      <template #extension>
        <v-row no-gutters class="px-5 py-1 d-flex align-center justify-end ga-3">
          <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="vehicleTypeFilter" density="compact" item-title="label" item-value="value"
            placeholder="Filter by Type" clearable max-width="200" hide-details :items="typeOptions" /> -->
        </v-row>
      </template>

      <template #item.block="{ value }">
        {{ value ? `Blk ${value}` : "" }}
      </template>
      <template #item.nric="{ value }">
       {{ maskNRIC(value) }}
      </template>

      <template #item.plates="{ value, item }">
        <PlateNumberDisplay :plate-numbers="value" :default-value="item.plateNumber" />
      </template>
    </TableMain>

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

    <v-dialog v-model="dialog.showSelection" width="450" persistent>
      <VehicleAddSelection @cancel="dialog.showSelection = false" @select="handleSelectVehicleStatus" />
    </v-dialog>

    <v-dialog v-model="dialog.createVehicle" v-if="vehicleType" width="450" persistent>
      <VehicleForm :type="vehicleType" :mode="mode" :vehicle-data="selectedVehicleObject"
        :plate-number-id="selectedPlateNumberId" @back="handleBackToSelection" @done="handleAddVehicleComplete"
        :org="org" :site="props.site" @close:all="handleCloseAll" />
    </v-dialog>

    <v-dialog v-model="dialog.updateVehicle" v-if="vehicleType" width="450" persistent>
      <VehicleForm :type="vehicleType" :mode="mode" :vehicle-data="selectedPlateNumberObject"
        :plate-number-id="selectedPlateNumberId" @back="handleBackToSelection" @done="handleAddVehicleComplete"
        :org="org" :site="props.site" @close:all="handleCloseAll" @close="handleCloseAll" />
    </v-dialog>

    <!-- <v-dialog v-model="dialog.updateVehicle" v-if="vehicleType" width="450" persistent>
      <VehicleForm :type="vehicleType" mode="edit" :vehicle-data="selectedVehicleObject"
        @back="dialog.updateVehicle = false" @close="dialog.updateVehicle = false" @done="handleUpdateVehicleComplete"
        :org="org" :site="site" @close:all="handleCloseAll" />
    </v-dialog> -->

    <v-dialog v-if="canViewVehicleDetails" v-model="dialog.showMoreActions" width="800" persistent>
      <DialogUpdateMoreAction title="Preview" :can-update="false" :can-delete="false"
        @close="dialog.showMoreActions = false">
        <template v-slot:content>
          <v-row no-gutters class="ga-1 mb-5">

            <template v-for="(label, key) in formattedFields" :key="key">

              <v-col v-if="key === 'nric' && selectedVehicleObject['nric']" cols="12">
                <span class="d-flex ga-3 align-center"><strong>{{ label }}:</strong> {{ maskNRIC(selectedVehicleObject[key]) }}</span>
              </v-col>

              <v-col v-else-if="key === 'plates'" class="d-flex flex-column ga-2">
                <span class="d-flex ga-3 align-center"><strong>{{ label }}:</strong></span>
                <!-- <PlateNumberDisplay :plate-numbers="selectedVehicleObject[key]" show-all :default-value="selectedVehicleObject.plateNumber" />   -->
                <v-col cols="12">
                  <v-card flat outlined class="pa-2" border="sm black" :loading="loadingPlateNumberDetails">
                    <v-data-table :items="selectedVehicleObject[key]" :headers="plateHeaders" hide-default-footer>
                      <template #item.status="{ value }">
                        <v-chip :color="formatVehicleStatus(value).color" size="x-small" dark>
                          {{ formatVehicleStatus(value).label }}
                        </v-chip>
                      </template>
                      <template #item.action="{ item: plateNumberItem, value }">
                        <v-menu>
                          <template #activator="{ props: menuProps }">
                            <v-btn icon="mdi-dots-vertical" v-bind="menuProps" flat size="x-small" />
                          </template>
                          <v-list density="compact">
                            <v-list-item v-if="(plateNumberItem as TPlateNumber)?.status == 'active'"
                              title="Edit Vehicle" prepend-icon="mdi-pencil"
                              @click="handleEditVehicleAction(plateNumberItem as TPlateNumber)" />
                            <v-list-item
                              v-if="props.app === 'property_management_agency' && (plateNumberItem as TPlateNumber)?.status == 'pending'"
                              title="Approve" prepend-icon="mdi-check-circle" base-color="success"
                              @click="handleApproveVehicle(plateNumberItem as TPlateNumber)" />
                            <v-list-item v-if="(plateNumberItem as TPlateNumber)?.status == 'deleted'" title="Restore"
                              prepend-icon="mdi-restore" base-color="orange"
                              @click="handleRestoreVehicle(plateNumberItem as TPlateNumber)" />
                            <v-list-item
                              v-if="((plateNumberItem as TPlateNumber)?.type === 'whitelist' || (plateNumberItem as TPlateNumber)?.type === 'blocklist') && plateNumberItem?.status == 'active'"
                              :title="(plateNumberItem as TPlateNumber)?.type === 'blocklist' ? 'Whitelist' : 'Blocklist'"
                              prepend-icon="mdi-swap-horizontal"
                              :base-color="(plateNumberItem as TPlateNumber)?.type === 'blocklist' ? 'primary' : 'red'"
                              @click="handleUpdateType(plateNumberItem as TPlateNumber)" />

                            <v-list-item
                              v-if="canDeleteVehicle && (plateNumberItem as TPlateNumber)?.status == 'active'"
                              title="Delete" prepend-icon="mdi-delete" base-color="error"
                              @click="handleDeleteVehicleAction(plateNumberItem as TPlateNumber)" />
                          </v-list>
                        </v-menu>
                      </template>
                    </v-data-table>
                    <v-btn text="Add Vehicle Number" class="mt-6 text-capitalize" prepend-icon="mdi-plus"
                      @click="addNewPlateNumbers" color="primary" />
                  </v-card>
                </v-col>

              </v-col>

              <v-col v-else-if="selectedVehicleObject[key]" cols="12">
                <span class="d-flex ga-3 align-center"><strong>{{ label }}:</strong> {{ formatValues(key,
                  selectedVehicleObject[key])
                  }}</span>
              </v-col>
            </template>
          </v-row>
        </template>
      </DialogUpdateMoreAction>
    </v-dialog>
    <v-dialog v-model="dialog.deleteVehicle" persistent width="540">
      <DialogDeleteConfirmation :loading="deletingVehicle"
        :prompt-title="`Are you sure want to delete this vehicle - ${selectedPlateNumberObject?.plateNumber}?`"
        @delete="submitDelete" @close="closeDeleteDialog" />
    </v-dialog>
    <v-dialog v-model="dialog.approveVehicle" persistent width="540">
      <DialogReusablePrompt :loading="approvingVehicle"
        :prompt-title="`Are you sure want to approve this vehicle - ${selectedPlateNumberObject?.plateNumber}?`"
        @proceed="submitApprove" @close="dialog.approveVehicle = false" />
    </v-dialog>
    <v-dialog v-model="dialog.restoreVehicle" persistent width="540">
      <DialogReusablePrompt :loading="restoringVehicle"
        :prompt-title="`Are you sure want to restore this vehicle - ${selectedPlateNumberObject?.plateNumber}?`"
        @proceed="submitRestore" @close="dialog.restoreVehicle = false" />
    </v-dialog>
    <v-dialog v-model="dialog.updateVehicleType" persistent width="540">
      <DialogReusablePrompt :loading="updatingType"
        :prompt-title="`Are you sure want to update the type of this vehicle - ${selectedPlateNumberObject?.plateNumber}?`"
        @proceed="submitUpdateType" @close="dialog.updateVehicleType = false" />
    </v-dialog>
    <Snackbar v-model="messageSnackbar" :text="message" :color="messageColor" />
  </v-row>
</template>

<script lang="ts" setup>
import useUtils from '../composables/useUtils';
import useVehicle from '../composables/useVehicle';

definePageMeta({
  middleware: ["01-auth", "02-org"],
  memberOnly: true,
})


const props = defineProps({
  canCreateVehicle: { type: Boolean, default: false },
  canUpdateVehicle: { type: Boolean, default: true },
  canDeleteVehicle: { type: Boolean, default: true },
  canViewVehicleDetails: { type: Boolean, default: true },
  site: { type: String, required: true },
  org: { type: String, required: true },
  app: { type: String, required: true },
});


const headers = [
  { title: "Name", value: "name" },
  { title: "Vehicle Numbers", value: "plates" },
  { title: "NRIC", value: "nric" },
  { title: "Block", value: "block.name" },
  { title: "Floor", value: "level.name" },
  { title: "Unit", value: "unit.name" },
  { title: "Category", value: "category" },
  // { title: "Type", value: "type" },
  // { title: "Status", value: "status" },
]

const plateHeaders = [
  { title: "Plate Number", value: "plateNumber" },
  { title: "Type", value: "type" },
  { title: "Status", value: "status" },
  { title: "", value: "action" },
]



const { formatCamelCaseToWords, formatDate, debounce, maskNRIC } = useUtils();
const { getVehicles, deleteVehicle, formatVehicleStatus, approveVehicle, updateVehicle, getSpecificVehicleById } = useVehicle();

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

const mode = ref<"add" | "edit">("add");

const searchInput = ref("")

const loading = ref(false);
const loadingPlateNumberDetails = ref(false);
const deletingVehicle = ref(false);
const approvingVehicle = ref(false);
const restoringVehicle = ref(false);
const updatingType = ref(false);

const selectedVehicleId = ref<string | null>(null)
const vehicleType = ref<TVehicleType | 'seasonpass' | null>(null);
const vehicleTypeFilter = ref<TVehicleType | null>(null);

const selectedPlateNumberObject = ref<TPlateNumber | null>(null);
const selectedPlateNumberId = ref<string | null>(null); // individual plate number

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

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

const dialog = reactive({
  createVehicle: false,
  updateVehicle: false,
  showSelection: false,
  deleteVehicle: false,
  showMoreActions: false,
  approveVehicle: false,
  restoreVehicle: false,
  updateVehicleType: false
});


const typeOptions = [
  { label: "Whitelist", value: "whitelist" },
  { label: "Blocklist", value: "blocklist" },
]

const formattedFields: Partial<Record<keyof TVehicle, string>> = {
  name: "Name",
  phoneNumber: "Phone Number",
  nric: "NRIC",
  block: "Block",
  level: "Level",
  unit: "Unit",
  start: "Start",
  end: "End",
  category: "Category",
  type: "Type",
  remarks: "Remarks",
  plates: "Vehicle Numbers",
}

function formatValues(key: string, value: any) {
  if (!value) return ""
  switch (key) {
    case "unit":
      return value.name || "";
    case "level":
      return value.name || "";
    case "block":
      return value.name || "";
    case "start":
      return formatDate(value)
    case "end":
      return formatDate(value)
    case "type":
    case "category":
      return String(value).charAt(0).toUpperCase() + String(value).slice(1).toLowerCase();
  }

  return value;
}

const closeDeleteDialog = () => {
  dialog.deleteVehicle = false;
};

const handleCloseAll = () => {
  dialog.createVehicle = false;
  dialog.updateVehicle = false;
  dialog.showSelection = false;
  dialog.updateVehicleType = false;
  mode.value = "add";
  vehicleType.value = null;
}

const selectedVehicleObject = computed(() => {
  return items.value.find(item => item?._id === selectedVehicleId.value) || {}
})

const { data: getVehiclesReq, refresh: getVehiclesRefresh, pending: getVehiclesPending } =
  await useLazyAsyncData(
    `get-all-vehicles-${props.site}`,
    () =>
      getVehicles({
        page: page.value,
        search: searchInput.value,
        type: vehicleTypeFilter.value ?? "",
        site: props.site,
      }),
    {
      watch: [page],
    }
  );


watch(getVehiclesReq, (newData: any) => {
  items.value = newData?.items || [];
  pages.value = newData?.pages || 0;
  pageRange.value = newData?.pageRange || "-- - -- of --";
})

function handleRowClick(data: any) {
  selectedVehicleId.value = data?.item?._id;
  dialog.showMoreActions = true;
  message.value = "";
}

function addNewPlateNumbers() {
  if (!selectedVehicleId.value) return;
  dialog.showSelection = true;
}

async function handleEditVehicleAction(item: TPlateNumber) {

  selectedPlateNumberId.value = item?._id as string;

  try {
    loadingPlateNumberDetails.value = true;
    const res = await getSpecificVehicleById(selectedPlateNumberId.value as string)

    if (res.type === 'blocklist') {
      vehicleType.value = "blocklist";
    } else {
      if (res?.seasonPassType) {
        vehicleType.value = "seasonpass";
      } else {
        vehicleType.value = "whitelist";
      }
    }


    selectedPlateNumberObject.value = res || null;
    dialog.showMoreActions = false;
    mode.value = "edit";
    dialog.updateVehicle = true;

  } catch (error) {
    console.error("Error fetching vehicle details:", error);
  } finally {
    loadingPlateNumberDetails.value = false;
  }

}

function handleDeleteVehicleAction(item: TPlateNumber) {
  selectedPlateNumberObject.value = item || null;
  dialog.deleteVehicle = true;
}

function handleApproveVehicle(item: TPlateNumber) {
  selectedPlateNumberObject.value = item || null;
  dialog.approveVehicle = true;
}
function handleRestoreVehicle(item: TPlateNumber) {
  selectedPlateNumberObject.value = item || null;
  dialog.restoreVehicle = true;
}

function handleUpdateType(item: TPlateNumber) {
  selectedPlateNumberObject.value = item || null;
  dialog.updateVehicleType = true;
}

function handleSelectVehicleStatus(value: TVehicleType) {
  vehicleType.value = value;
  dialog.showSelection = false;
  dialog.createVehicle = true;
}

function handleBackToSelection() {
  dialog.showSelection = true;
  dialog.createVehicle = false;
  vehicleType.value = null;
}

function handleAddVehicleComplete() {
  dialog.showSelection = false;
  dialog.createVehicle = false;
  vehicleType.value = null;
  getVehiclesRefresh();
}

function handleUpdateVehicleComplete() {
  dialog.showSelection = false;
  dialog.updateVehicle = false;
  dialog.showMoreActions = false;
  vehicleType.value = null;
  getVehiclesRefresh();
}


function handleUpdatePage(newPageNum: number) {
  page.value = newPageNum;
}

function handleAddVehicleClick() {
  mode.value = "add";
  dialog.showSelection = true;
  selectedVehicleId.value = null;
}

const formatPlateNumbers = (value: any) => {
  if (!value || value.length === 0) return "";

  const firstTwo = value.slice(0, 2).map((item: any) => item.plateNumber || "");
  return firstTwo.join(", ");
};

async function submitDelete() {

  const plateNumberId = selectedPlateNumberObject.value?._id;
  const type = selectedPlateNumberObject.value?.type as TVehicleType;
  const recNo = selectedPlateNumberObject.value?.recNo;
  if (!plateNumberId) {
    showMessage("Invalid plate number selected for deletion.", "error");
    return;
  }

  try {
    deletingVehicle.value = true;
    const res = await deleteVehicle({ site: props.site, recno: recNo, id: plateNumberId as string, type }
    );
    dialog.deleteVehicle = false;
    showMessage(res.message, "success");
    await getVehiclesRefresh();
  } catch (error: any) {
    console.error("Error deleting vehicle:", error);
    message.value = error.response._data.message;
  } finally {
    deletingVehicle.value = false;
  }
}



async function submitRestore() {

  const vehicleId = selectedPlateNumberObject.value?._id;

  if (!vehicleId) {
    showMessage("Invalid vehicle Id selected for restoration.", "error");
    return;
  }

  try {
    restoringVehicle.value = true;
    // reactivate and restore will use the same endpoint, just with different payload
    const res = await approveVehicle({ site: props.site, org: props.org, id: vehicleId as string }
    );
    dialog.restoreVehicle = false;
    showMessage(res.message, "success");
    await getVehiclesRefresh();
  } catch (error: any) {
    console.error("Error restoring vehicle:", error);
    const errMessage = error?.response?._data?.message || "Failed to restore vehicle";
    showMessage(errMessage, "error");
    // message.value = error.response._data.message;
  } finally {
    restoringVehicle.value = false;
  }
}


async function submitUpdateType() {


  const vehicleId = selectedPlateNumberObject.value?._id;
  const type = selectedPlateNumberObject.value?.type as TVehicleType;
  const recNo = selectedPlateNumberObject.value?.recNo;


  if (!type) {
    showMessage("Invalid vehicle type.", "error");
    return;
  }

  // if(!recNo){
  //   showMessage("Invalid vehicle record number.", "error");
  //   return;
  // }


  const payload = {
    site: props.site,
    plateNumber: selectedPlateNumberObject.value?.plateNumber as string,
    type: type === "whitelist" ? "blocklist" : "whitelist" as TVehicleType,
    // recno: recNo
  }


  if (!vehicleId) {
    showMessage("Invalid vehicle Id selected for updating type.", "error");
    return;
  }

  try {
    updatingType.value = true;
    const res = await updateVehicle(vehicleId as string, payload);
    dialog.updateVehicleType = false;
    showMessage(res.message, "success");
    await getVehiclesRefresh();
  } catch (error: any) {
    console.error("Error updating vehicle type:", error);
    const errMessage = error?.response?._data?.message || "Failed to update vehicle type";
    showMessage(errMessage, "error");
    // message.value = error.response._data.message;
  } finally {
    updatingType.value = false;
  }
}


async function submitApprove() {

  const plateNumberId = selectedPlateNumberObject.value?._id;
  if (!plateNumberId) {
    showMessage("Invalid plate number selected for approval.", "error");
    return;
  }

  try {
    approvingVehicle.value = true;
    const res = await approveVehicle({ site: props.site, org: props.org, id: plateNumberId as string }

    );
    dialog.approveVehicle = false;
    showMessage(res.message, "success");
    await getVehiclesRefresh();
  } catch (error: any) {
    console.error("Error approving vehicle:", error);
    const errMessage = error?.response?._data?.message || "Failed to approve vehicle";
    showMessage(errMessage, "error");
  } finally {
    approvingVehicle.value = false;
  }
}

const debouncedSearch = debounce(getVehiclesRefresh, 500);
watch([searchInput, vehicleTypeFilter], () => {
  page.value = 1;
  debouncedSearch()
})


</script>
