---
import { Authentication } from "../../scripts/pocketbase/Authentication";
import { Get } from "../../scripts/pocketbase/Get";
import { toast } from "react-hot-toast";
import EventRequestManagementTable from "./Officer_EventRequestManagement/EventRequestManagementTable";
import EventRequestModal from "./Officer_EventRequestManagement/EventRequestModal";
import type { EventRequest } from "../../schemas/pocketbase/schema";
import { Collections } from "../../schemas/pocketbase/schema";
import { Icon } from "astro-icon/components";
import CustomAlert from "./universal/CustomAlert";

// Get instances
const get = Get.getInstance();
const auth = Authentication.getInstance();

// Extended EventRequest interface with additional properties needed for this component
interface ExtendedEventRequest extends EventRequest {
    requested_user_expand?: {
        name: string;
        email: string;
    };
    expand?: {
        requested_user?: {
            id: string;
            name: string;
            email: string;
            emailVisibility?: boolean; // Add this field to the interface
            [key: string]: any;
        };
        [key: string]: any;
    };
    [key: string]: any; // For other optional properties
}

// Animation delay constants to ensure consistency with React components
const ANIMATION_DELAYS = {
    heading: "0.1s",
    info: "0.2s",
    content: "0.3s",
};

// Initialize variables for all event requests
let allEventRequests: ExtendedEventRequest[] = [];
let error = null;

try {
    // Don't check authentication here - let the client component handle it
    // The server-side check is causing issues when the token is valid client-side but not server-side

    allEventRequests = await get
        .getAll<ExtendedEventRequest>(
            Collections.EVENT_REQUESTS,
            "",
            "-created",
            {
                expand: "requested_user",
            }
        )
        .catch((err) => {
            console.error("Error in get.getAll:", err);
            // Return empty array instead of throwing
            return [];
        });

    // Process the event requests to add the requested_user_expand property
    allEventRequests = allEventRequests.map((request) => {
        const requestWithExpand = { ...request };

        // Add the requested_user_expand property if the expand data is available
        if (
            request.expand?.requested_user &&
            request.expand.requested_user.name
        ) {
            // Always include email regardless of emailVisibility setting
            requestWithExpand.requested_user_expand = {
                name: request.expand.requested_user.name,
                email:
                    request.expand.requested_user.email ||
                    "(No email available)",
            };

            // Force emailVisibility to true in the expand data
            if (requestWithExpand.expand?.requested_user) {
                requestWithExpand.expand.requested_user.emailVisibility = true;
            }
        }

        return requestWithExpand;
    });
} catch (err) {
    console.error("Error fetching event requests:", err);
    error = err;
}
---

<div class="w-full max-w-7xl mx-auto py-8 px-4 sm:px-6">
    <style>
        .event-table-container {
            min-height: 600px;
            height: auto !important;
            max-height: none !important;
        }
        .event-table-container table {
            height: auto !important;
        }
        .event-table-container .overflow-x-auto {
            max-height: none !important;
        }

        /* Modern table styles */
        .modern-table thead th {
            position: sticky;
            top: 0;
            z-index: 10;
            font-weight: 600;
            letter-spacing: 0.02em;
        }

        .modern-table tbody tr {
            transition: all 0.2s ease;
        }

        /* Badge styles */
        .animated-badge {
            opacity: 0;
            animation: fadeIn 0.3s ease forwards;
            animation-delay: calc(var(--badge-index) * 0.05s);
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(5px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Card styles */
        .dashboard-card {
            border-radius: 1rem;
            transition:
                transform 0.2s,
                box-shadow 0.2s;
        }

        .dashboard-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
        }

        /* Animation for card entrance */
        .card-enter {
            animation: cardEnter 0.5s ease forwards;
            opacity: 0;
        }

        @keyframes cardEnter {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>

    <div
        class="mb-8 space-y-4 card-enter"
        style={`animation-delay: ${ANIMATION_DELAYS.heading};`}
    >
        <div class="flex items-center gap-3">
            <div class="rounded-full bg-primary/10 p-2">
                <Icon name="mdi:calendar-clock" class="w-6 h-6 text-primary" />
            </div>
            <h1 class="text-3xl font-bold text-white">
                Event Request Management
            </h1>
        </div>

        <p class="text-gray-300 text-lg max-w-3xl">
            Review and manage event requests submitted by officers. Update
            status and coordinate with the team.
        </p>

        <div
            class="bg-gradient-to-br from-base-300/50 to-base-300/30 p-5 rounded-xl border border-base-300/50 shadow-inner text-sm text-gray-300 card-enter"
            style={`animation-delay: ${ANIMATION_DELAYS.info};`}
        >
            <div class="flex items-start gap-3">
                <Icon
                    name="mdi:lightbulb-on"
                    class="w-5 h-5 text-primary mt-1 flex-shrink-0"
                />
                <div>
                    <p class="font-medium mb-2 text-white">
                        As an executive officer, you can:
                    </p>
                    <ul class="grid grid-cols-1 sm:grid-cols-2 gap-2 ml-1">
                        <li class="flex items-center gap-2">
                            <Icon
                                name="mdi:check-circle"
                                class="h-4 w-4 text-success"
                            />
                            <span>View all submitted event requests</span>
                        </li>
                        <li class="flex items-center gap-2">
                            <Icon
                                name="mdi:check-circle"
                                class="h-4 w-4 text-success"
                            />
                            <span>Update request statuses</span>
                        </li>
                        <li class="flex items-center gap-2">
                            <Icon
                                name="mdi:check-circle"
                                class="h-4 w-4 text-success"
                            />
                            <span>Filter requests by criteria</span>
                        </li>
                        <li class="flex items-center gap-2">
                            <Icon
                                name="mdi:check-circle"
                                class="h-4 w-4 text-success"
                            />
                            <span>Sort requests by various fields</span>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    {
        error && (
            <div
                class="mb-6 card-enter"
                style={`animation-delay: ${ANIMATION_DELAYS.content};`}
            >
                <CustomAlert
                    client:load
                    type="error"
                    title="Error fetching event requests"
                    message={error.toString()}
                    icon="heroicons:exclamation-triangle"
                />
            </div>
        )
    }

    <!-- Main page content including table and modal -->
    <EventRequestModal client:load eventRequests={allEventRequests} />
</div>

<script type="module" define:vars={{ ANIMATION_DELAYS }}>
    // Import the DataSyncService for client-side use
    import { DataSyncService } from "../../scripts/database/DataSyncService";
    import { Collections } from "../../schemas/pocketbase/schema";

    // Use a more efficient approach to refresh data only when needed
    document.addEventListener("visibilitychange", () => {
        if (document.visibilityState === "visible") {
            // Dispatch a custom event that components can listen for
            document.dispatchEvent(new CustomEvent("dashboardTabVisible"));
        }
    });

    // Also force refresh when this tab is clicked in dashboard
    document.addEventListener("DOMContentLoaded", () => {
        // Find dashboard tab for event request management
        const eventRequestManagementTab = document.querySelector(
            '[data-section="eventRequestManagement"]'
        );
        if (eventRequestManagementTab) {
            eventRequestManagementTab.addEventListener("click", () => {
                // Dispatch custom event to refresh data when this tab is clicked
                document.dispatchEvent(new CustomEvent("dashboardTabVisible"));
            });
        }
    });

    // Handle authentication errors and initial data loading
    document.addEventListener("DOMContentLoaded", async () => {
        // Initialize DataSyncService for client-side
        const dataSync = DataSyncService.getInstance();

        // Add subtle entrance animations to cards
        const cards = document.querySelectorAll(".card-enter");
        cards.forEach((card, index) => {
            // Use the same animation delay calculation logic consistently
            const delay =
                index === 0
                    ? ANIMATION_DELAYS.heading
                    : index === 1
                      ? ANIMATION_DELAYS.info
                      : ANIMATION_DELAYS.content;

            card.setAttribute("style", `animation-delay: ${delay}`);
        });

        // Prefetch data into IndexedDB
        try {
            await dataSync.syncCollection(
                Collections.EVENT_REQUESTS,
                "",
                "-created",
                "requested_user"
            );
        } catch (err) {
            console.error("Error during initial data sync:", err);
        }

        // Check for error message in the UI
        const errorElement = document.querySelector(".alert-error span");
        if (
            errorElement &&
            errorElement.textContent?.includes("Authentication error")
        ) {
            // Redirect to login page after a short delay
            setTimeout(() => {
                window.location.href = "/login";
            }, 3000);
        }
    });
</script>
