<script setup lang="ts">
import { ref, watch } from 'vue';
import { Head, router } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Search, Eye, Clock, User, HardDrive, Calendar } from 'lucide-vue-next';

interface Causer {
    name: string;
    email: string;
}

interface ActivityLog {
    id: number;
    log_name: string | null;
    description: string;
    event: string | null;
    subject_type: string | null;
    subject_id: number | null;
    causer: Causer | null;
    properties: Record<string, any> | null;
    created_at: string;
    created_at_exact: string;
}

interface PaginatedLogs {
    data: ActivityLog[];
    current_page: number;
    last_page: number;
    prev_page_url: string | null;
    next_page_url: string | null;
    total: number;
    links: { url: string | null; label: string; active: boolean }[];
}

const props = defineProps<{
    logs: PaginatedLogs;
    filters: {
        search?: string;
    };
}>();

const search = ref(props.filters.search || '');
const selectedLog = ref<ActivityLog | null>(null);
const isModalOpen = ref(false);

// Debounce search input
let timeoutId: ReturnType<typeof setTimeout> | null = null;
watch(search, (newSearch) => {
    if (timeoutId) clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
        router.get(
            route('logs.index'),
            { search: newSearch },
            { preserveState: true, replace: true }
        );
    }, 400);
});

const openDetails = (log: ActivityLog) => {
    selectedLog.value = log;
    isModalOpen.value = true;
};

const closeDetails = () => {
    isModalOpen.value = false;
    selectedLog.value = null;
};

const getEventBadgeClass = (event: string | null) => {
    if (!event) return 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300';
    switch (event.toLowerCase()) {
        case 'created':
            return 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-950/30 dark:text-emerald-400 dark:border-emerald-900/50';
        case 'updated':
            return 'bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-950/30 dark:text-amber-400 dark:border-amber-900/50';
        case 'deleted':
            return 'bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-950/30 dark:text-rose-400 dark:border-rose-900/50';
        default:
            return 'bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-950/30 dark:text-blue-400 dark:border-blue-900/50';
    }
};

const formatJson = (json: any): string => {
    try {
        return JSON.stringify(json, null, 2);
    } catch {
        return String(json);
    }
};
</script>

<template>
    <Head title="Activity Logs" />

    <AdminLayout>
        <div class="space-y-6">
            <!-- Header Section -->
            <div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                <div>
                    <h1 class="text-2xl font-bold tracking-tight text-slate-900 dark:text-slate-50">Activity Logs</h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Monitor system actions, security events, and audit trails.
                    </p>
                </div>
            </div>

            <!-- Filters Card -->
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl p-4 shadow-sm flex flex-col md:flex-row gap-4 items-center justify-between">
                <div class="relative w-full md:max-w-sm">
                    <Search class="absolute left-3 top-2.5 h-4 w-4 text-slate-400 dark:text-slate-500" />
                    <input
                        v-model="search"
                        type="text"
                        placeholder="Search logs, events, or users..."
                        class="w-full pl-9 pr-4 py-2 text-sm bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-slate-950 dark:text-slate-50 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent transition-all"
                    />
                </div>
                <div class="text-sm text-slate-500 dark:text-slate-400">
                    Showing {{ logs.data.length }} of {{ logs.total }} events
                </div>
            </div>

            <!-- Activity Logs Table/Timeline -->
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-sm overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full border-collapse text-left">
                        <thead>
                            <tr class="border-b border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/50 text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
                                <th class="px-6 py-4">Causer</th>
                                <th class="px-6 py-4">Event</th>
                                <th class="px-6 py-4">Description</th>
                                <th class="px-6 py-4">Subject</th>
                                <th class="px-6 py-4">Time</th>
                                <th class="px-6 py-4 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-200 dark:divide-slate-800 text-sm">
                            <tr v-if="logs.data.length === 0">
                                <td colspan="6" class="px-6 py-12 text-center text-slate-500 dark:text-slate-400">
                                    <div class="flex flex-col items-center justify-center space-y-2">
                                        <Clock class="h-8 w-8 text-slate-300 dark:text-slate-700" />
                                        <p class="font-medium text-slate-700 dark:text-slate-300">No activity logs found</p>
                                        <p class="text-xs text-slate-400 dark:text-slate-500">Try adjusting your search criteria</p>
                                    </div>
                                </td>
                            </tr>
                            <tr 
                                v-for="log in logs.data" 
                                :key="log.id"
                                class="hover:bg-slate-50/50 dark:hover:bg-slate-900/50 transition-colors"
                            >
                                <td class="px-6 py-4">
                                    <div class="flex items-center gap-3">
                                        <div class="h-8 w-8 rounded-full bg-red-50 dark:bg-red-950/30 flex items-center justify-center border border-red-100 dark:border-red-900/40">
                                            <User class="h-4 w-4 text-red-600 dark:text-red-400" />
                                        </div>
                                        <div>
                                            <div class="font-medium text-slate-900 dark:text-slate-100">
                                                {{ log.causer ? log.causer.name : 'System' }}
                                            </div>
                                            <div class="text-xs text-slate-400 dark:text-slate-500">
                                                {{ log.causer ? log.causer.email : 'system@internal' }}
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <span 
                                        :class="[
                                            'inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border',
                                            getEventBadgeClass(log.event)
                                        ]"
                                    >
                                        {{ log.event || 'action' }}
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-slate-700 dark:text-slate-300 font-medium">
                                    {{ log.description }}
                                </td>
                                <td class="px-6 py-4 text-slate-500 dark:text-slate-400">
                                    <span v-if="log.subject_type" class="inline-flex items-center gap-1">
                                        <HardDrive class="h-3.5 w-3.5" />
                                        {{ log.subject_type }} <span class="text-xs font-semibold bg-slate-100 dark:bg-slate-800 px-1.5 py-0.5 rounded text-slate-600 dark:text-slate-400">#{{ log.subject_id }}</span>
                                    </span>
                                    <span v-else class="text-xs text-slate-400 italic">None</span>
                                </td>
                                <td class="px-6 py-4 text-slate-500 dark:text-slate-400 whitespace-nowrap">
                                    <span :title="log.created_at_exact" class="flex items-center gap-1.5 cursor-help">
                                        <Clock class="h-3.5 w-3.5 text-slate-400" />
                                        {{ log.created_at }}
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-right whitespace-nowrap">
                                    <button
                                        @click="openDetails(log)"
                                        class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900 text-slate-700 dark:text-slate-300 transition-all focus:outline-none focus:ring-2 focus:ring-red-500"
                                    >
                                        <Eye class="h-3.5 w-3.5 text-slate-500" />
                                        View Details
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination Footer -->
                <div 
                    v-if="logs.last_page > 1"
                    class="border-t border-slate-200 dark:border-slate-800 px-6 py-4 flex items-center justify-between bg-slate-50/50 dark:bg-slate-900/50"
                >
                    <div class="flex-1 flex justify-between sm:hidden">
                        <button
                            :disabled="!logs.prev_page_url"
                            @click="logs.prev_page_url && router.visit(logs.prev_page_url)"
                            class="relative inline-flex items-center px-4 py-2 border border-slate-300 dark:border-slate-800 text-sm font-medium rounded-md text-slate-700 dark:text-slate-300 bg-white dark:bg-slate-950 hover:bg-slate-50 dark:hover:bg-slate-900 disabled:opacity-50 transition-colors"
                        >
                            Previous
                        </button>
                        <button
                            :disabled="!logs.next_page_url"
                            @click="logs.next_page_url && router.visit(logs.next_page_url)"
                            class="ml-3 relative inline-flex items-center px-4 py-2 border border-slate-300 dark:border-slate-800 text-sm font-medium rounded-md text-slate-700 dark:text-slate-300 bg-white dark:bg-slate-950 hover:bg-slate-50 dark:hover:bg-slate-900 disabled:opacity-50 transition-colors"
                        >
                            Next
                        </button>
                    </div>
                    <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                        <div>
                            <p class="text-sm text-slate-700 dark:text-slate-400">
                                Showing page <span class="font-medium text-slate-900 dark:text-slate-50">{{ logs.current_page }}</span> of <span class="font-medium text-slate-900 dark:text-slate-50">{{ logs.last_page }}</span>
                            </p>
                        </div>
                        <div>
                            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                                <button
                                    v-for="(link, idx) in logs.links"
                                    :key="idx"
                                    :disabled="!link.url"
                                    @click="link.url && router.visit(link.url)"
                                    v-html="link.label"
                                    :class="[
                                        link.active 
                                            ? 'z-10 bg-red-500 border-red-500 text-white focus:ring-red-500' 
                                            : 'bg-white dark:bg-slate-950 border-slate-300 dark:border-slate-800 text-slate-500 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-900',
                                        'relative inline-flex items-center px-3 py-2 border text-xs font-medium disabled:opacity-50 transition-colors cursor-pointer',
                                        idx === 0 ? 'rounded-l-md' : '',
                                        idx === logs.links.length - 1 ? 'rounded-r-md' : ''
                                    ]"
                                />
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Details Modal -->
        <div 
            v-if="isModalOpen" 
            class="fixed inset-0 z-50 flex items-center justify-center p-4 animate-fade-in"
        >
            <!-- Backdrop -->
            <div 
                @click="closeDetails"
                class="fixed inset-0 bg-slate-950/60 backdrop-blur-sm transition-opacity"
            />

            <!-- Modal Content -->
            <div class="relative bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-2xl w-full max-w-2xl overflow-hidden flex flex-col max-h-[85vh] animate-in zoom-in-95 duration-200">
                <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between bg-slate-50/50 dark:bg-slate-900/50">
                    <h3 class="text-base font-semibold text-slate-900 dark:text-slate-50">Log Details #{{ selectedLog?.id }}</h3>
                    <button 
                        @click="closeDetails"
                        class="rounded-lg p-1 text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-900 hover:text-slate-600 dark:hover:text-slate-300 transition-colors"
                    >
                        <span class="sr-only">Close</span>
                        &times;
                    </button>
                </div>

                <div class="p-6 overflow-y-auto space-y-6">
                    <!-- Event Details Summary -->
                    <div class="grid grid-cols-2 gap-4">
                        <div class="space-y-1">
                            <span class="text-xs text-slate-400 dark:text-slate-500 uppercase tracking-wider block">Description</span>
                            <span class="text-sm font-semibold text-slate-950 dark:text-slate-50">{{ selectedLog?.description }}</span>
                        </div>
                        <div class="space-y-1">
                            <span class="text-xs text-slate-400 dark:text-slate-500 uppercase tracking-wider block">Log Group</span>
                            <span class="text-sm font-semibold text-slate-950 dark:text-slate-50">{{ selectedLog?.log_name || 'default' }}</span>
                        </div>
                        <div class="space-y-1">
                            <span class="text-xs text-slate-400 dark:text-slate-500 uppercase tracking-wider block">Performed By</span>
                            <span class="text-sm font-medium text-slate-950 dark:text-slate-50 flex items-center gap-1.5">
                                <User class="h-4 w-4 text-red-500" />
                                {{ selectedLog?.causer?.name || 'System' }} ({{ selectedLog?.causer?.email || 'system@internal' }})
                            </span>
                        </div>
                        <div class="space-y-1">
                            <span class="text-xs text-slate-400 dark:text-slate-500 uppercase tracking-wider block">Logged At</span>
                            <span class="text-sm font-medium text-slate-950 dark:text-slate-50 flex items-center gap-1.5">
                                <Calendar class="h-4 w-4 text-slate-400" />
                                {{ selectedLog?.created_at_exact }}
                            </span>
                        </div>
                    </div>

                    <!-- JSON Properties -->
                    <div class="space-y-2">
                        <span class="text-xs text-slate-400 dark:text-slate-500 uppercase tracking-wider block">Changes & Metadata</span>
                        <div v-if="selectedLog?.properties && Object.keys(selectedLog.properties).length > 0" class="relative">
                            <pre class="bg-slate-950 text-slate-350 dark:bg-slate-900 border border-slate-800 rounded-lg p-4 font-mono text-xs overflow-x-auto text-slate-300 leading-relaxed max-h-60">{{ formatJson(selectedLog.properties) }}</pre>
                        </div>
                        <div v-else class="text-xs italic text-slate-400 dark:text-slate-500 py-3 border border-dashed border-slate-200 dark:border-slate-800 rounded-lg text-center">
                            No additional metadata stored with this event.
                        </div>
                    </div>
                </div>

                <div class="px-6 py-4 border-t border-slate-200 dark:border-slate-800 flex justify-end bg-slate-50/50 dark:bg-slate-900/50">
                    <button
                        @click="closeDetails"
                        class="px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-300 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-lg hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors focus:outline-none"
                    >
                        Close
                    </button>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
