<template>
    <v-card height="100%" width="100%" flat class="pa-2 pa-sm-5">
        <v-row no-gutters>
            <v-col cols="12">
                <v-row no-gutters class="d-flex ga-2 justify-space-between align-start mb-3 mb-sm-5 flex-wrap">

                    <div class="d-flex flex-column" style="min-width: 0;">
                        <span class="text-subtitle-1 font-weight-bold" style="word-break: break-word;">Visitor
                            Management - Visitor ({{ items.length }} visitors)</span>
                        <span style="font-size: clamp(11px, 1.1vw, 13px); word-break: break-word;">Date Range: {{
                            formatDateDDMMYYYY(dateFrom) }} - {{ formatDateDDMMYYYY(dateTo) ?? "" }}</span>
                        <span class="text-subtitle-1" style="word-break: break-word;">Site Name: {{ activeSiteName
                        }}</span>
                    </div>

                </v-row>
                <div style="overflow-x: auto; max-width: 100%;">
                    <v-data-table :headers="headers" :items="items" show-header :items-per-page="100"
                        hide-default-footer class="text-black" no-data-text="No entries to display">

                        <template v-slot:item.typeCompany="{ item }">
                            <span class="d-flex align-center ga-2" style="flex-wrap: wrap;">
                                <v-icon icon="mdi-user" size="15" />
                                <span v-if="item.type === 'contractor'" class="text-capitalize"
                                    style="word-break: break-word;">{{
                                        formatCamelCaseToWords(item.contractorType)
                                    }}</span>
                                <span v-else class="text-capitalize" style="word-break: break-word;">{{ formatType(item)
                                }}</span>
                            </span>
                            <span class="d-flex align-center ga-2" style="flex-wrap: wrap;">
                                <v-icon icon="mdi-domain" size="15" />
                                <span class="text-capitalize" style="word-break: break-word;">{{ item?.company || "N/A"
                                }}</span>
                            </span>
                        </template>

                        <template v-slot:item.location="{ item }">
                            <span class="d-flex align-center ga-2" style="flex-wrap: wrap;">
                                <v-icon icon="mdi-storefront-outline" size="15" />
                                <span class="text-capitalize" style="word-break: break-word;">{{
                                    formatLocation({
                                        block: item.block,
                                        level: item.level,
                                        unit: item.unitName,
                                    })
                                }}</span>
                            </span>
                        </template>

                        <template v-slot:item.contact-vehicleNumber="{ item }">
                            <span class="d-flex align-center ga-2" style="flex-wrap: wrap;">
                                <v-icon icon="mdi-phone" size="15" />
                                <span class="text-capitalize" style="word-break: break-word;">{{ item?.contact || "N/A"
                                }}</span>
                            </span>
                            <span class="d-flex align-center ga-2" style="flex-wrap: wrap;">
                                <v-icon icon="mdi-car-back" size="15" />
                                <span class="text-capitalize" style="word-break: break-word;">{{ item?.plateNumber ||
                                    "N/A" }}</span>
                            </span>
                        </template>

                        <template v-slot:item.checkInOut="{ item }">
                            <span class="d-flex align-center ga-2" style="flex-wrap: wrap;">
                                <v-icon icon="mdi-login" size="15" />
                                <span class="text-capitalize" style="word-break: break-word;">{{
                                    formatDate(item.checkIn) }}</span>
                            </span>
                            <span class="d-flex align-center ga-2" style="flex-wrap: wrap;">
                                <v-icon icon="mdi-logout" size="15" />
                                <span class="text-capitalize" style="word-break: break-word;">{{
                                    formatDate(item.checkOut) }}</span>
                            </span>
                        </template>

                        <template v-slot:item.checkInOutImage="{ item }">
                            <div class="d-flex flex-column ga-2">
                                <div v-if="item?.snapshotEntryImage" class="d-flex flex-column">
                                    <span class="text-caption font-weight-bold text-blue-darken-1">Check-In</span>
                                    <v-img :src="getFileUrlAnpr(`${siteId}/${item.snapshotEntryImage}`)"
                                        style="max-width: clamp(60px, 10vw, 100px); max-height: clamp(60px, 10vw, 100px);"
                                        class="border" />
                                </div>
                                <div v-if="item?.snapshotExitImage" class="d-flex flex-column">
                                    <span class="text-caption font-weight-bold text-red-darken-1">Check-Out</span>
                                    <v-img :src="getFileUrlAnpr(`${siteId}/${item.snapshotExitImage}`)"
                                        style="max-width: clamp(60px, 10vw, 100px); max-height: clamp(60px, 10vw, 100px);"
                                        class="border" />
                                </div>
                                <span v-if="!item?.snapshotEntryImage && !item?.snapshotExitImage"
                                    class="text-caption text-disabled">
                                    No images
                                </span>
                            </div>
                        </template>


                    </v-data-table>
                </div>
            </v-col>

        </v-row>
    </v-card>
</template>

<script setup lang="ts">
import moment from 'moment-timezone';
import useLocalAuth from '../composables/useLocalAuth';
import useVisitor from '../composables/useVisitor';
import useUtils from '../composables/useUtils';
import useSite from '../composables/useSite';


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


const props = defineProps({
    siteId: {
        type: String,
        required: true,
    },
})

const { getVisitors } = useVisitor();
const { formatCamelCaseToWords } = useUtils();
const { currentUser } = useLocalAuth();
const { getSiteById } = useSite(); const { getFileUrlAnpr } = useFile(); const route = useRoute();
const { org: orgId, site: siteId } = route.params as {
    org: string;
    site: string;
    reportId: string;
};

const activeSiteName = computed(() => {
    const site = sites.value.find(s => s._id === props.siteId)
    return site ? site.name : ''
})


const headers: Record<string, any>[] = [
    { title: "Name", value: "name", align: "start" },
    { title: "Type/Company", value: "typeCompany", align: "start" },
    { title: "Location", value: "location", align: "start" },
    { title: "Contact/Vehicle No", value: "contact-vehicleNumber", align: "start" },
    { title: "Check In/Out", value: "checkInOut", align: "center" },
    { title: "Check In/Out Image", value: "checkInOutImage", align: "start" },
]




const searchInput = ref("");
const dateFrom = ref<string | null>(null);
const dateTo = ref<string | null>(null);
const filterTypes = ref<string[]>([]);
const activeTab = ref("registered");
const displayNotCheckedOut = ref(false);

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

const items = ref<TVisitor[]>([])

const formatType = (item: any) =>
    (item.deliveryType ? item.deliveryType + "-" : "") + item.type;


const { data: getSitesReq } = await useLazyAsyncData(
    "get-customer-site-" + props.siteId,
    () =>
        getSiteById(props.siteId),
    {
        watch: [() => props.siteId],
    }
);

watch(getSitesReq, (newData: any) => {
    if (newData) {
        sites.value = newData ? [newData] : []
    }
})

const formatLocation = ({ block, level, unit }: { block: number, level: string, unit: string | TBuildingUnit }) => {
    const parts = [];

    if (block) parts.push(`Block ${block}`);
    if (level) parts.push(level);
    if (unit) parts.push(unit);

    return parts.join(" / ");
};

function formatDate(dateString: string) {
    if (!dateString) return "";

    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", {
        year: "numeric",
        month: "short",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
    });
}


const {
    data: getVisitorReq,
    refresh: getVisitorRefresh,
    pending: getVisitorPending,
} = await useLazyAsyncData(
    "get-all-visitors",
    async () => {
        const params: any = {
            page: 1,
            site: siteId,
            limit: 100,
            search: searchInput.value,
            dateTo: dateTo.value ? moment(dateTo.value).endOf("day").toISOString() : undefined,
            dateFrom: dateFrom.value ? moment(dateFrom.value).startOf("day").toISOString() : undefined,
            type:
                filterTypes.value.length === 0 && activeTab.value === "registered"
                    ? "contractor,delivery,walk-in,pick-up,drop-off,guest"
                    : filterTypes.value.filter(Boolean).join(","),
            checkedOut: displayNotCheckedOut.value ? false : undefined,
        };

        if (activeTab.value === "guests") {
            params.type = "guest";
            params.status = "approved";
        } else if (activeTab.value === "resident-transactions") {
            params.status = "registered";
            params.type = "resident,tenant";
        } else if (activeTab.value === "overnight-parking") {
            params.tab = "Overnight Parking";
        } else {
            params.status = activeTab.value;
        }

        if (activeTab.value !== 'registered') {
            delete params.type
            delete params.checkedOut
        }

        return await getVisitors(params);
    },
    {
        watch: [
            searchInput,
            dateFrom,
            dateTo,
            filterTypes,
            activeTab,
            displayNotCheckedOut,
        ],
        immediate: true,
    }
);

watch(getVisitorReq, (newData: any) => {
    if (newData) {
        items.value = newData.items || []
    }
})


function normalizeDateOnly(value: string) {
    if (!value) return "";
    if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return value;

    const parsedDate = new Date(value);
    if (Number.isNaN(parsedDate.getTime())) return "";

    const year = parsedDate.getFullYear();
    const month = String(parsedDate.getMonth() + 1).padStart(2, "0");
    const day = String(parsedDate.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
}


function formatDateDDMMYYYY(date: Date | string | null) {
    if (!date) return "";
    const parsedDate = typeof date === "string" ? new Date(date) : date;
    const day = String(parsedDate?.getDate()).padStart(2, '0')
    const month = String(parsedDate?.getMonth() + 1).padStart(2, '0')
    const year = parsedDate?.getFullYear()

    return `${day}/${month}/${year}`
}


onMounted(() => {
    activeTab.value = (route.query.tab as string) || "unregistered";
    searchInput.value = (route.query.search as string) || "";
    dateFrom.value = normalizeDateOnly((route.query.dateFrom as string) || "");
    dateTo.value = normalizeDateOnly((route.query.dateTo as string) || "");
    filterTypes.value = ((route.query.type as string)?.split(",") || []).filter(
        Boolean
    ) as TVisitorType[];
    displayNotCheckedOut.value =
        (route.query.checkedOut as string) == "true" || false;
});


</script>

<style scoped>
* {
    box-sizing: border-box;
}

:deep(.v-card) {
    overflow-x: auto;
}

:deep(.v-data-table-header__content) {
    background-color: #1976d2 !important;
    color: white !important;
    font-weight: bold;
}

:deep(.v-data-table thead tr th) {
    background-color: #1976d2 !important;
    color: white !important;
    border-right: 1px solid rgba(255, 255, 255, 0.2) !important;
    font-size: clamp(11px, 1.2vw, 14px) !important;
    padding: clamp(8px, 1vw, 12px) !important;
    word-break: break-word;
}

:deep(.v-data-table thead tr th:last-child) {
    border-right: none !important;
}

:deep(.v-data-table tbody tr td) {
    border-right: 1px solid #e0e0e0 !important;
    font-size: clamp(10px, 1.1vw, 13px) !important;
    padding: clamp(6px, 0.8vw, 10px) !important;
    word-break: break-word;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

:deep(.v-data-table tbody tr td:last-child) {
    border-right: none !important;
}

:deep(.v-data-table tbody tr:last-child td) {
    border-bottom: 1px solid #e0e0e0 !important;
}

:deep(.v-img) {
    max-width: clamp(60px, 10vw, 100px) !important;
    max-height: clamp(60px, 10vw, 100px) !important;
}

:deep(.text-caption) {
    font-size: clamp(9px, 1vw, 12px) !important;
}

:deep(.text-subtitle-1) {
    font-size: clamp(14px, 2vw, 18px) !important;
}

:deep(.text-h5) {
    font-size: clamp(16px, 2.5vw, 24px) !important;
}

:deep(.v-icon) {
    width: clamp(12px, 1.5vw, 20px) !important;
    height: clamp(12px, 1.5vw, 20px) !important;
}

:deep(.gap-2) {
    gap: clamp(4px, 0.5vw, 8px) !important;
}

/* Mobile optimization */
@media (max-width: 768px) {
    :deep(.v-data-table) {
        min-width: 100%;
    }

    :deep(.v-data-table thead tr th) {
        padding: 6px !important;
        font-size: 11px !important;
    }

    :deep(.v-data-table tbody tr td) {
        padding: 4px !important;
        font-size: 10px !important;
    }

    :deep(.v-img) {
        max-width: 60px !important;
        max-height: 60px !important;
    }
}

/* Tablet optimization */
@media (max-width: 1024px) {
    :deep(.v-data-table) {
        font-size: 12px;
    }

    :deep(.v-data-table thead tr th) {
        padding: 8px !important;
    }

    :deep(.v-data-table tbody tr td) {
        padding: 6px !important;
    }
}
</style>
