---
// Define the component's props and setup
interface Props {}
const {} = Astro.props;
---

<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 h-full">
    <!-- Left Column - Events List -->
    <div class="card bg-base-200 shadow-xl h-full">
        <div class="card-body p-6 flex flex-col h-full">
            <!-- Fixed Header Section -->
            <div class="flex-none">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="card-title text-2xl">Events</h2>
                </div>

                <!-- Event Check-in Section -->
                <div class="card bg-base-200 shadow-xl mb-8">
                    <div class="card-body p-6">
                        <h2 class="card-title text-2xl mb-4">Quick Check-in</h2>

                        <!-- Event Check-in Skeleton -->
                        <div id="eventCheckInSkeleton" class="animate-pulse">
                            <div class="h-6 bg-base-300 rounded w-2/3 mb-4">
                            </div>
                            <div class="flex items-center gap-2">
                                <div class="h-8 bg-base-300 rounded flex-1">
                                </div>
                                <div class="h-8 bg-base-300 rounded w-24"></div>
                            </div>
                        </div>

                        <!-- Event Check-in Content -->
                        <div id="eventCheckInContent" class="hidden">
                            <div id="eventCheckInSection" class="space-y-2">
                                <div class="flex items-center gap-2">
                                    <input
                                        type="text"
                                        id="eventCodeInput"
                                        placeholder="Enter event code"
                                        class="input input-bordered flex-1"
                                        value=""
                                    />
                                    <button
                                        id="checkInButton"
                                        class="btn btn-primary">Check In</button
                                    >
                                </div>
                                <p
                                    id="checkInStatus"
                                    class="text-sm mt-1 opacity-70"
                                >
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="divider mt-0 mb-4"></div>
            </div>

            <!-- Scrollable Events List -->
            <div class="flex-1 overflow-y-auto min-h-0">
                <div id="eventsList" class="space-y-4">
                    <!-- Loading Skeletons -->
                    {
                        Array(3)
                            .fill(0)
                            .map(() => (
                                <div class="card bg-base-100 shadow-sm animate-pulse">
                                    <div class="card-body p-4">
                                        <div class="flex justify-between items-start">
                                            <div class="space-y-3 w-full">
                                                <div class="h-6 bg-base-300 rounded w-3/4" />
                                                <div class="space-y-2">
                                                    <div class="h-4 bg-base-300 rounded w-1/2 opacity-70" />
                                                    <div class="h-4 bg-base-300 rounded w-2/3 opacity-70" />
                                                    <div class="h-4 bg-base-300 rounded w-1/3 opacity-70" />
                                                </div>
                                            </div>
                                            <div class="h-6 w-20 bg-base-300 rounded" />
                                        </div>
                                    </div>
                                </div>
                            ))
                    }
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column - Profile Information -->
    <div class="card bg-base-200 shadow-xl h-full">
        <div class="card-body p-6">
            <h2 class="card-title text-2xl mb-6">Past Events</h2>
            <div id="pastEventsList" class="space-y-4 overflow-y-auto">
                <!-- Loading Skeletons -->
                {
                    Array(3)
                        .fill(0)
                        .map(() => (
                            <div class="card bg-base-100 shadow-sm animate-pulse">
                                <div class="card-body p-4">
                                    <div class="flex justify-between items-start">
                                        <div class="space-y-3 w-full">
                                            <div class="h-6 bg-base-300 rounded w-3/4" />
                                            <div class="space-y-2">
                                                <div class="h-4 bg-base-300 rounded w-1/2 opacity-70" />
                                                <div class="h-4 bg-base-300 rounded w-2/3 opacity-70" />
                                                <div class="h-4 bg-base-300 rounded w-1/3 opacity-70" />
                                            </div>
                                        </div>
                                        <div class="h-6 w-20 bg-base-300 rounded" />
                                    </div>
                                </div>
                            </div>
                        ))
                }
            </div>
        </div>
    </div>
</div>

<script>
    // TypeScript declarations
    declare global {
        interface Window {
            showEventFiles: (eventId: string) => Promise<void>;
        }
    }

    import { Authentication } from "../pocketbase/Authentication";
    import { Get } from "../pocketbase/Get";
    import { SendLog } from "../pocketbase/SendLog";
    import { FileManager } from "../pocketbase/FileManager";

    const auth = Authentication.getInstance();
    const get = Get.getInstance();
    const logger = SendLog.getInstance();
    const fileManager = FileManager.getInstance();

    // Initialize the modal state
    window.fileViewerModal = {
        isOpen: false,
        files: [],
        setIsOpen: (isOpen: boolean) => {
            window.fileViewerModal.isOpen = isOpen;
            const modal = document.querySelector("file-viewer-modal") as any;
            if (modal) {
                modal.setAttribute("isOpen", isOpen.toString());
            }
        },
        setFiles: (files) => {
            window.fileViewerModal.files = files;
            const modal = document.querySelector("file-viewer-modal") as any;
            if (modal) {
                modal.setAttribute("files", JSON.stringify(files));
            }
        },
    };

    // Track if we're currently fetching events
    let isFetchingEvents = false;
    let lastFetchPromise: Promise<void> | null = null;

    // Define interfaces
    interface BaseRecord {
        id: string;
        [key: string]: any;
    }

    interface Event extends BaseRecord {
        id: string;
        event_id: string;
        event_name: string;
        start_date: string;
        end_date: string;
        location: string;
        files?: string[];
    }

    // Add debounce function
    function debounce<T extends (...args: any[]) => any>(
        func: T,
        wait: number
    ): (...args: Parameters<T>) => void {
        let timeout: ReturnType<typeof setTimeout> | null = null;
        return (...args: Parameters<T>) => {
            if (timeout) clearTimeout(timeout);
            timeout = setTimeout(() => func(...args), wait);
        };
    }

    // Create debounced version of renderEvents
    const debouncedRenderEvents = debounce(async () => {
        try {
            await renderEvents();
        } catch (error) {
            console.error("Failed to render events:", error);
        }
    }, 300);

    // Function to show content and hide skeleton
    function showEventCheckIn() {
        const eventCheckInSkeleton = document.getElementById(
            "eventCheckInSkeleton"
        );
        const eventCheckInContent = document.getElementById(
            "eventCheckInContent"
        );
        if (eventCheckInSkeleton && eventCheckInContent) {
            eventCheckInSkeleton.classList.add("hidden");
            eventCheckInContent.classList.remove("hidden");
        }
    }

    // Function to format date
    function formatDate(dateStr: string): string {
        const date = new Date(dateStr);
        return date.toLocaleString();
    }

    // Function to check if event is upcoming
    function isUpcoming(startDate: string): boolean {
        const now = new Date();
        const start = new Date(startDate);
        return start > now;
    }

    // Function to check if event is current
    function isCurrent(startDate: string, endDate: string): boolean {
        const now = new Date();
        const start = new Date(startDate);
        const end = new Date(endDate);
        return start <= now && now <= end;
    }

    // Function to get event status
    function getEventStatus(
        event: any,
        isAttended: boolean
    ): { status: string; badge: string } {
        if (isAttended) {
            return {
                status: "Attended",
                badge: "badge-success",
            };
        }

        if (isCurrent(event.start_date, event.end_date)) {
            return {
                status: "Current",
                badge: "badge-warning",
            };
        }

        if (isUpcoming(event.start_date)) {
            return {
                status: "Upcoming",
                badge: "badge-info",
            };
        }

        return {
            status: "Past",
            badge: "badge-ghost",
        };
    }

    // Function to get status icon
    function getStatusIcon(status: string): string {
        const checkIcon = `<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
        </svg>`;

        const clockIcon = `<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z" clip-rule="evenodd" />
        </svg>`;

        const exclamationIcon = `<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
        </svg>`;

        switch (status) {
            case "Attended":
                return checkIcon;
            case "Current":
                return exclamationIcon;
            case "Upcoming":
                return clockIcon;
            default:
                return "";
        }
    }

    // Function to render event card
    function renderEventCard(event: Event, attendedEvents: string[]): string {
        const isAttended =
            Array.isArray(attendedEvents) &&
            attendedEvents.includes(event.event_id);
        const hasFiles =
            event.files && Array.isArray(event.files) && event.files.length > 0;
        const isPastEvent = new Date(event.end_date) < new Date();
        const { status, badge } = getEventStatus(event, isAttended);

        // Only show files button for past events
        const filesButton =
            hasFiles && isPastEvent
                ? `
            <button 
                class="btn btn-ghost btn-xs gap-2" 
                onclick="window.showEventFiles('${event.id}')"
            >
                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clip-rule="evenodd" />
                </svg>
                ${event.files?.length || 0} File${(event.files?.length || 0) > 1 ? "s" : ""}
            </button>
        `
                : "";

        return `
            <div class="card bg-base-100 shadow-sm hover:shadow-md transition-shadow">
                <div class="card-body p-4">
                    <div class="flex justify-between items-start gap-4">
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center gap-2 mb-2">
                                <h3 class="font-medium text-lg truncate">${event.event_name}</h3>
                                <div class="badge ${badge} gap-1">
                                    ${getStatusIcon(status)}
                                    ${status}
                                </div>
                            </div>
                            <div class="text-sm opacity-70 space-y-1">
                                <p>Starts: ${formatDate(event.start_date)}</p>
                                <p>Ends: ${formatDate(event.end_date)}</p>
                                ${
                                    event.location
                                        ? `<p class="flex items-center gap-1">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                                        <path fill-rule="evenodd" d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z" clip-rule="evenodd" />
                                    </svg>
                                    ${event.location}
                                </p>`
                                        : ""
                                }
                            </div>
                            ${hasFiles && isPastEvent ? `<div class="mt-3">${filesButton}</div>` : ""}
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // Function to render events with request cancellation handling
    async function renderEvents() {
        const eventsList = document.getElementById("eventsList");
        const pastEventsList = document.getElementById("pastEventsList");
        if (!eventsList || !pastEventsList) return;

        // If we're already fetching, wait for the current fetch to complete
        if (isFetchingEvents && lastFetchPromise) {
            try {
                await lastFetchPromise;
                return;
            } catch (err) {
                console.warn("Previous fetch failed:", err);
            }
        }

        // Set up new fetch
        isFetchingEvents = true;
        const fetchPromise = (async () => {
            try {
                // Get current user's attended events with safe parsing
                const user = auth.getCurrentUser();
                let attendedEvents: string[] = [];

                if (user?.events_attended) {
                    try {
                        attendedEvents =
                            typeof user.events_attended === "string"
                                ? JSON.parse(user.events_attended)
                                : Array.isArray(user.events_attended)
                                  ? user.events_attended
                                  : [];
                        console.log("Attended events:", attendedEvents);
                    } catch (e) {
                        console.warn("Failed to parse events_attended:", e);
                        attendedEvents = [];
                    }
                }

                // Fetch all events
                console.log("Fetching all events");
                const events = await get.getAll<Event>(
                    "events",
                    undefined,
                    "-start_date"
                );
                console.log("Fetched events:", events);

                if (!Array.isArray(events)) {
                    throw new Error(
                        "Failed to fetch events: Invalid response format"
                    );
                }

                // Clear loading skeletons
                eventsList.innerHTML = "";
                pastEventsList.innerHTML = "";

                // Categorize events
                const now = new Date();
                const currentEvents: Event[] = [];
                const upcomingEvents: Event[] = [];
                const pastEvents: Event[] = [];

                events.forEach((event) => {
                    if (!event.start_date || !event.end_date) {
                        console.warn("Event missing dates:", event);
                        return;
                    }

                    const startDate = new Date(event.start_date);
                    const endDate = new Date(event.end_date);

                    if (startDate > now) {
                        upcomingEvents.push(event);
                    } else if (endDate >= now && startDate <= now) {
                        currentEvents.push(event);
                    } else {
                        pastEvents.push(event);
                    }
                });

                // Sort upcoming events by start date
                const sortedUpcomingEvents = upcomingEvents.sort(
                    (a, b) =>
                        new Date(a.start_date).getTime() -
                        new Date(b.start_date).getTime()
                );

                // Sort past events by date descending (most recent first)
                const sortedPastEvents = pastEvents.sort(
                    (a, b) =>
                        new Date(b.end_date).getTime() -
                        new Date(a.end_date).getTime()
                );

                // Update past events count
                const pastEventsCountElement =
                    document.getElementById("pastEventsCount");
                if (pastEventsCountElement) {
                    pastEventsCountElement.textContent =
                        sortedPastEvents.length.toString();
                }

                // Function to render section
                function renderSection(events: Event[]): string {
                    if (events.length === 0) {
                        return `
                        <div class="text-center py-8 opacity-70">
                            <p>No events found</p>
                        </div>
                    `;
                    }
                    return events
                        .map((event) => renderEventCard(event, attendedEvents))
                        .join("");
                }

                // Update main events list (current & upcoming)
                eventsList.innerHTML = renderSection([
                    ...currentEvents,
                    ...sortedUpcomingEvents,
                ]);

                // Update past events list
                pastEventsList.innerHTML = renderSection(sortedPastEvents);
            } catch (err) {
                console.error("Failed to render events:", err);
                await logger.send(
                    "error",
                    "render events",
                    `Failed to render events: ${err instanceof Error ? err.message : "Unknown error"}`
                );
                const errorMessage = `
                    <div class="text-center py-8 text-error">
                        <p>Failed to load events. Please try again later.</p>
                        <p class="text-sm mt-2 opacity-70">${err instanceof Error ? err.message : "Unknown error"}</p>
                    </div>
                `;
                eventsList.innerHTML = errorMessage;
                pastEventsList.innerHTML = errorMessage;
                throw err; // Re-throw to handle in the outer catch
            } finally {
                isFetchingEvents = false;
            }
        })();

        lastFetchPromise = fetchPromise;

        try {
            await fetchPromise;
        } catch (err) {
            // Error already handled above
            console.debug("Fetch completed with error");
        }
    }

    // Initialize event check-in
    document.addEventListener("DOMContentLoaded", () => {
        showEventCheckIn();
        // Only render events once at startup
        renderEvents().catch(console.error);
    });

    // Show content when auth state changes
    let lastAuthState = auth.isAuthenticated();
    auth.onAuthStateChange((isValid) => {
        showEventCheckIn();
        // Only re-render if auth state actually changed
        if (lastAuthState !== isValid) {
            lastAuthState = isValid;
            renderEvents().catch(console.error);
        }
    });

    // Update the showEventFiles function to use custom events
    window.showEventFiles = async (eventId: string) => {
        try {
            // Fetch the event data
            const event = await get.getOne("events", eventId);

            if (
                !event.files ||
                !Array.isArray(event.files) ||
                event.files.length === 0
            ) {
                console.warn("No files available for event:", eventId);
                return;
            }

            // Convert files to the format expected by FileViewerModal
            const files = event.files.map((file: string) => {
                const fileName = file.split("/").pop() || "File";
                const fileUrl = fileManager.getFileUrl(
                    "events",
                    event.id,
                    file
                );
                const fileType = getFileType(fileName);
                return {
                    url: fileUrl,
                    type: fileType,
                    name: fileName,
                };
            });

            // Dispatch custom event to show files
            const showFileViewerEvent = new CustomEvent("showFileViewer", {
                detail: { files },
            });
            window.dispatchEvent(showFileViewerEvent);
        } catch (err) {
            console.error("Failed to load event files:", err);
            await logger.send(
                "error",
                "show event files",
                `Failed to load event files: ${err instanceof Error ? err.message : "Unknown error"}`
            );
        }
    };

    // Helper function to determine file type
    function getFileType(fileName: string): string {
        const extension = fileName.split(".").pop()?.toLowerCase() || "";
        const mimeTypes: Record<string, string> = {
            pdf: "application/pdf",
            jpg: "image/jpeg",
            jpeg: "image/jpeg",
            png: "image/png",
            gif: "image/gif",
            mp4: "video/mp4",
            webm: "video/webm",
            mp3: "audio/mpeg",
            wav: "audio/wav",
            txt: "text/plain",
            json: "application/json",
            doc: "application/msword",
            docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        };

        return mimeTypes[extension] || "application/octet-stream";
    }
</script>
