<template>
  <v-row no-gutters>
    <TableMain :headers="headers" :items="items" :loading="loading" :page="page" :pages="pages" :pageRange="pageRange"
      :createLabel="createLabel" :show-header="true" :extension-height="extensionHeight" :offset="offset"
      v-model:search="searchInput" @refresh="emits('refresh')" @create="emits('create')" @row-click="handleRowClick"
      @update:page="handleUpdatePage">

      <template #extension>
        <v-row no-gutters class="w-100 d-flex align-center justify-end ga-4 pa-2">
          <v-select v-model="statusFilter" label="Filter by types" item-title="label" item-value="value"
            :items="filterOptions" density="compact" clearable max-width="200" hide-details>
          </v-select>
        </v-row>
      </template>

      <template v-slot:item.name="{ item }">
        <span class="d-flex align-center ga-2">
          <span>
            <AvatarMain :name="item?.name" :size="20" :id="item?._id" />
          </span>
          <span class="text-capitalize">{{ item?.name }}</span>
        </span>
      </template>

      <template v-slot:item.emailContact="{ item }">
        <span class="d-flex align-center ga-2">
          <v-icon icon="mdi-email" size="15" />
          <span class="text-capitalize">{{ item?.email || "N/A" }}</span>
        </span>
        <span class="d-flex align-center ga-2">
          <v-icon icon="mdi-phone" size="15" />
          <span class="text-capitalize">{{ item?.contact || "N/A" }}</span>
        </span>
      </template>

      <template #item.createdAt="{ value }">
        {{ formatDateDDMMYYYYLocal(value) }}
      </template>

      <template #item.status="{ value }">
        <v-chip class="text-capitalize" :color="formatStatus(value).color" density="compact" variant="flat" pill>
          {{ formatStatus(value).label }}
        </v-chip>
      </template>

      <template #item.action="{ item }">
        <v-menu v-if="item?.status === 'pending'" activator="parent" transition="scale-transition">
          <template #activator="{ props }">
            <v-btn variant="flat" density="compact" icon="mdi-dots-vertical" v-bind="props"></v-btn>
          </template>
          <v-list>
            <v-list-item @click="openActionDialog(item, 'approved')">
              <v-list-item-title>
                <v-icon class="text-success mr-2 text-subtitle-1">mdi-check</v-icon>Approve</v-list-item-title>
            </v-list-item>
            <v-list-item @click="openActionDialog(item, 'rejected')">
              <v-list-item-title>
                <v-icon class="text-error mr-2 text-subtitle-1">mdi-close</v-icon>Reject</v-list-item-title>
            </v-list-item>
          </v-list>
        </v-menu>
      </template>

      <template v-if="$slots.footer" #footer>
        <slot name="footer" />
      </template>
    </TableMain>

    <v-dialog v-model="viewDialog" width="450" persistent>
      <VehicleUpdateMoreAction title="Preview" :can-update="false" :can-delete="false"
        @close="viewDialog = false">
        <template v-slot:content>
          <v-row no-gutters class="mb-4">
            <v-col v-for="(label, key) in formattedFields" :key="key" cols="12">
              <span v-if="selectedItem?.[key] !== undefined && selectedItem?.[key] !== null && selectedItem?.[key] !== ''" class="d-flex ga-3 align-center">
                <strong>{{ label }}:</strong>
                {{ formatItemValue(key, selectedItem[key]) }}
              </span>
            </v-col>
          </v-row>
        </template>
      </VehicleUpdateMoreAction>
    </v-dialog>

    <v-dialog v-model="actionDialog.open" max-width="520" persistent>
      <v-card>
        <v-card-title class="text-subtitle-1 font-weight-bold pt-4 px-4">
          {{ actionDialog.action === 'approved' ? 'Approve Request' : 'Reject Request' }}
        </v-card-title>
        <v-card-text class="px-4 pb-2">
          <p class="text-caption text-medium-emphasis mb-3">
            Add remarks before {{ actionDialog.action === 'approved' ? 'approving' : 'rejecting' }} this request.
          </p>
          <v-textarea v-model="remarks" label="Remarks" rows="3" auto-grow :rules="[requiredRule]"
            :disabled="actionLoading" />
        </v-card-text>
        <v-card-actions class="px-4 pb-4">
          <v-spacer />
          <v-btn variant="text" :disabled="actionLoading" @click="closeActionDialog">Cancel</v-btn>
          <v-btn color="primary" variant="flat" :loading="actionLoading" :disabled="!remarks.trim()"
            @click="confirmAction">
            Confirm
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-row>
</template>

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

const props = defineProps({
  site: {
    type: String,
    default: "",
    required: false,
  },
  loading: {
    type: Boolean,
    default: false,
  },


});

const emits = defineEmits(["refresh", "create", "update:page"]);

const searchInput = defineModel<string>("search", { default: "" });

const { requiredRule, standardFormatDate, formatDateDDMMYYYYLocal } = useUtils();
const { getOvernightParkingRequests, updateOvernightParkingRequest } = useOvernightParking();

const items = ref<TOvernightParkingRequest[]>([])
const page = ref(1)
const pages = ref(1)
const pageRange = ref("-- - -- of --");
const extensionHeight = ref(0)
const offset = ref(0)
const createLabel = "New Overnight Parking Request"

const viewDialog = ref(false)
const selectedItem = ref<TOvernightParkingRequest | null>(null)

const formattedFields = {
  name: "Name",
  email: "Email",
  contact: "Contact",
  isOvernightParking: "Overnight Parking",
  numberOfPassengers: "No. of Passengers",
  purposeOfVisit: "Purpose of Visit",
  status: "Status",
  remarks: "Remarks",
  createdAt: "Date Requested",
} as const

function formatItemValue(key: string, value: any) {
  if (value === undefined || value === null || value === '') return ''
  switch (key) {
    case 'createdAt':
    case 'updatedAt':
      return formatDateDDMMYYYYLocal(value)
    case 'isOvernightParking':
      return value ? 'Yes' : 'No'
    case 'status':
      return formatStatus(value as TOvernightParkingRequest['status']).label
  }
  return value
}

const remarks = ref('')
const actionLoading = ref(false)
const actionDialog = reactive<{
  open: boolean
  requestId: string
  action: 'approved' | 'rejected'
}>({
  open: false,
  requestId: '',
  action: 'approved',
})

const statusFilter = ref<TOvernightParkingRequestStatus>("pending")

const filterOptions: { label: string; value: TOvernightParkingRequestStatus }[] = [
  { label: "Pending", value: "pending" },
  { label: "Approved", value: "approved" },
  { label: "Rejected", value: "rejected" },
  { label: "Expired", value: "expired" },
]

const headers = [
  { title: "Name", value: "name" },
  { title: "Email/Contact", value: "emailContact" },
  { title: "Date Requested", value: "createdAt" },
  { title: "Invited By", value: "invitedBy" },
  { title: "Status", value: "status" },
  { title: "Action", value: "action" },
];


function formatStatus(status: TOvernightParkingRequest["status"]) {
  switch (String(status || "").toLowerCase()) {
    case "approved":
      return { color: "success", label: "Approved" };
    case "expired":
      return { color: "grey", label: "Expired" };
    case "rejected":
      return { color: "error", label: "Rejected" };
    case "pending":
      return { color: "warning", label: "Pending" };
    default:
      return { color: "secondary", label: status || "N/A" };
  }
}

const { data: overnightParkingRequests, pending: isPendingOvernightParkingRequests, refresh: refreshOvernightParkingRequests } = await useLazyAsyncData<TOvernightParkingRequest[]>(() => getOvernightParkingRequests({ site: props.site, status: statusFilter.value }), { immediate: true })


watch(overnightParkingRequests, (data: any) => {
  // items.value = Array.isArray(data?.items)
  //   ? data.items
  //   : Array.isArray(data)
  //     ? data
  //     : []
  pages.value = data?.pages ?? 0;
  pageRange.value = data?.pageRange ?? "-- - -- of --"
}, { immediate: true })


// function formatTimeValue(value: TOvernightParkingRequest["start"] | TOvernightParkingRequest["end"]) {
//   if (!value) return "N/A";

//   const date = new Date(value);
//   if (Number.isNaN(date.getTime())) return String(value);

//   return date.toLocaleTimeString("en-US", {
//     hour: "2-digit",
//     minute: "2-digit",
//   });
// }

function handleRowClick(data: { item?: TOvernightParkingRequest }) {
  selectedItem.value = data?.item ?? null
  viewDialog.value = true
}

function handleUpdatePage(value: number) {
  emits("update:page", value);
}

function openActionDialog(item: TOvernightParkingRequest, action: 'approved' | 'rejected') {
  actionDialog.requestId = item?._id || ''
  actionDialog.action = action
  remarks.value = ''
  actionDialog.open = true
}

function closeActionDialog() {
  if (actionLoading.value) return
  actionDialog.open = false
}

async function confirmAction() {
  if (!actionDialog.requestId || !remarks.value.trim()) return

  try {
    actionLoading.value = true
    await updateOvernightParkingRequest(actionDialog.requestId, {
      status: actionDialog.action,
      remarks: remarks.value.trim(),
    })
    actionDialog.open = false
    await refreshOvernightParkingRequests()
    refreshOvernightParkingRequests()
  } finally {
    actionLoading.value = false
  }
}

watch([statusFilter], ([newStatus], [oldStatus]) => {
  if (newStatus === oldStatus) return
  refreshOvernightParkingRequests()
}, { immediate: false })
</script>