---
import EventAttendanceChart from "./SponsorAnalyticsSection/EventAttendanceChart";
import EventTypeDistribution from "./SponsorAnalyticsSection/EventTypeDistribution";
import MajorDistribution from "./SponsorAnalyticsSection/MajorDistribution";
import EventEngagementMetrics from "./SponsorAnalyticsSection/EventEngagementMetrics";
import EventTimeline from "./SponsorAnalyticsSection/EventTimeline";
---

<div class="space-y-6">
    <div
        class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4"
    >
        <div>
            <h2 class="text-2xl font-bold">Event Analytics</h2>
            <p class="text-base-content/70">
                Insights and analytics about IEEE UCSD events and student
                engagement
            </p>
        </div>
        <div class="flex items-center gap-2">
            <div class="dropdown dropdown-end">
                <div tabindex="0" role="button" class="btn btn-sm">
                    <span>Time Range</span>
                    <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="16"
                        height="16"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        class="lucide lucide-chevron-down"
                    >
                        <path d="m6 9 6 6 6-6"></path>
                    </svg>
                </div>
                <ul
                    tabindex="0"
                    class="dropdown-content z-[1] menu p-2 shadow bg-base-100 rounded-box w-52"
                >
                    <li><a data-time-range="30">Last 30 Days</a></li>
                    <li><a data-time-range="90">Last 90 Days</a></li>
                    <li><a data-time-range="180">Last 6 Months</a></li>
                    <li><a data-time-range="365">Last Year</a></li>
                    <li><a data-time-range="all">All Time</a></li>
                </ul>
            </div>
            <button id="refreshAnalyticsBtn" class="btn btn-sm btn-outline">
                <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    class="lucide lucide-refresh-cw"
                >
                    <path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"
                    ></path>
                    <path d="M21 3v5h-5"></path>
                    <path
                        d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"
                    ></path>
                    <path d="M3 21v-5h5"></path>
                </svg>
                <span>Refresh</span>
            </button>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <div class="card bg-base-100 shadow-md">
            <div class="card-body p-4">
                <h3 class="text-sm font-medium text-base-content/70">
                    Total Events
                </h3>
                <p class="text-3xl font-bold" id="totalEventsCount">--</p>
                <div class="text-xs text-base-content/50 mt-1">
                    <span id="eventsTrend" class="font-medium"></span> vs previous
                    period
                </div>
            </div>
        </div>

        <div class="card bg-base-100 shadow-md">
            <div class="card-body p-4">
                <h3 class="text-sm font-medium text-base-content/70">
                    Total Attendees
                </h3>
                <p class="text-3xl font-bold" id="totalAttendeesCount">--</p>
                <div class="text-xs text-base-content/50 mt-1">
                    <span id="attendeesTrend" class="font-medium"></span> vs previous
                    period
                </div>
            </div>
        </div>

        <div class="card bg-base-100 shadow-md">
            <div class="card-body p-4">
                <h3 class="text-sm font-medium text-base-content/70">
                    Unique Students
                </h3>
                <p class="text-3xl font-bold" id="uniqueStudentsCount">--</p>
                <div class="text-xs text-base-content/50 mt-1">
                    <span id="uniqueStudentsTrend" class="font-medium"></span> vs
                    previous period
                </div>
            </div>
        </div>

        <div class="card bg-base-100 shadow-md">
            <div class="card-body p-4">
                <h3 class="text-sm font-medium text-base-content/70">
                    Avg. Attendance
                </h3>
                <p class="text-3xl font-bold" id="avgAttendanceCount">--</p>
                <div class="text-xs text-base-content/50 mt-1">
                    <span id="avgAttendanceTrend" class="font-medium"></span> vs
                    previous period
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row 1 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div class="card bg-base-100 shadow-md">
            <div class="card-body">
                <h3 class="card-title text-lg">Event Attendance Over Time</h3>
                <div class="h-80">
                    <EventAttendanceChart client:load />
                </div>
            </div>
        </div>

        <div class="card bg-base-100 shadow-md">
            <div class="card-body">
                <h3 class="card-title text-lg">Major Distribution</h3>
                <div class="h-80">
                    <MajorDistribution client:load />
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row 2 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div class="card bg-base-100 shadow-md">
            <div class="card-body">
                <h3 class="card-title text-lg">Event Type Distribution</h3>
                <div class="h-80">
                    <EventTypeDistribution client:load />
                </div>
            </div>
        </div>

        <div class="card bg-base-100 shadow-md">
            <div class="card-body">
                <h3 class="card-title text-lg">Engagement Metrics</h3>
                <div class="h-80">
                    <EventEngagementMetrics client:load />
                </div>
            </div>
        </div>
    </div>

    <!-- Event Timeline -->
    <div class="card bg-base-100 shadow-md">
        <div class="card-body">
            <h3 class="card-title text-lg">Event Timeline</h3>
            <div class="overflow-x-auto">
                <EventTimeline client:load />
            </div>
        </div>
    </div>
</div>

<script>
    import { Authentication } from "../../scripts/pocketbase/Authentication";
    import { Get } from "../../scripts/pocketbase/Get";
    import { Realtime } from "../../scripts/pocketbase/Realtime";
    import { Collections } from "../../schemas/pocketbase/schema";

    // Initialize services
    const auth = Authentication.getInstance();
    const get = Get.getInstance();
    const realtime = Realtime.getInstance();

    // Default time range (30 days)
    let currentTimeRange = 30;

    // Initialize the analytics dashboard
    async function initAnalytics() {
        if (!auth.isAuthenticated()) {
            console.error("User not authenticated");
            return;
        }

        try {
            await loadSummaryData(currentTimeRange);

            // Set up event listeners
            document
                .querySelectorAll("[data-time-range]")
                .forEach((element) => {
                    element.addEventListener("click", (e) => {
                        const range =
                            parseInt(
                                e.currentTarget.getAttribute("data-time-range")
                            ) || 30;
                        currentTimeRange = isNaN(range) ? "all" : range;
                        loadSummaryData(currentTimeRange);
                    });
                });

            // Refresh button
            document
                .getElementById("refreshAnalyticsBtn")
                ?.addEventListener("click", () => {
                    loadSummaryData(currentTimeRange);
                });

            // Set up realtime updates
            setupRealtimeUpdates();
        } catch (error) {
            console.error("Error initializing analytics:", error);
        }
    }

    // Load summary data
    async function loadSummaryData(timeRange) {
        try {
            // Calculate date range
            const endDate = new Date();
            let startDate;

            if (timeRange === "all") {
                startDate = new Date(0); // Beginning of time
            } else {
                startDate = new Date();
                startDate.setDate(startDate.getDate() - timeRange);
            }

            // Format dates for filter
            const startDateStr = startDate.toISOString();
            const endDateStr = endDate.toISOString();

            // Build filter
            const filter =
                timeRange === "all"
                    ? "published = true"
                    : `published = true && start_date >= "${startDateStr}" && start_date <= "${endDateStr}"`;

            // Get events
            const events = await get.getAll(Collections.EVENTS, filter);

            // Get event attendees
            const attendeesFilter =
                timeRange === "all"
                    ? ""
                    : `time_checked_in >= "${startDateStr}" && time_checked_in <= "${endDateStr}"`;

            const attendees = await get.getAll(
                Collections.EVENT_ATTENDEES,
                attendeesFilter
            );

            // Calculate metrics
            const totalEvents = events.length;
            const totalAttendees = attendees.length;

            // Calculate unique students
            const uniqueStudentIds = new Set(attendees.map((a) => a.user));
            const uniqueStudents = uniqueStudentIds.size;

            // Calculate average attendance
            const avgAttendance =
                totalEvents > 0 ? Math.round(totalAttendees / totalEvents) : 0;

            // Update UI
            document.getElementById("totalEventsCount").textContent =
                totalEvents;
            document.getElementById("totalAttendeesCount").textContent =
                totalAttendees;
            document.getElementById("uniqueStudentsCount").textContent =
                uniqueStudents;
            document.getElementById("avgAttendanceCount").textContent =
                avgAttendance;

            // Calculate trends (simplified - would need previous period data for real implementation)
            document.getElementById("eventsTrend").textContent = "+5%";
            document.getElementById("attendeesTrend").textContent = "+12%";
            document.getElementById("uniqueStudentsTrend").textContent = "+8%";
            document.getElementById("avgAttendanceTrend").textContent = "+3%";

            // Dispatch custom event to notify charts to update
            window.dispatchEvent(
                new CustomEvent("analyticsDataUpdated", {
                    detail: {
                        events,
                        attendees,
                        timeRange,
                    },
                })
            );
        } catch (error) {
            console.error("Error loading summary data:", error);
        }
    }

    // Set up realtime updates
    function setupRealtimeUpdates() {
        // Subscribe to events collection
        realtime.subscribeToCollection(Collections.EVENTS, (data) => {
            console.log("Event data updated:", data);
            loadSummaryData(currentTimeRange);
        });

        // Subscribe to event attendees collection
        realtime.subscribeToCollection(Collections.EVENT_ATTENDEES, (data) => {
            console.log("Attendee data updated:", data);
            loadSummaryData(currentTimeRange);
        });
    }

    // Initialize when document is ready
    document.addEventListener("DOMContentLoaded", initAnalytics);
</script>
