{% extends "base.html" %}

{% block title %}Meetings - {{ lab_name }}{% endblock %}

{% block content %}
<div class="card">
    <div
        style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; flex-wrap: wrap; gap: 1rem;">
        <h1 style="color: var(--primary);">Lab Meetings</h1>
        <a href="{{ url_for('create_meeting_route') }}" class="btn btn-primary">Schedule Meeting</a>
    </div>

    <!-- This Week Section -->
    {% if this_week %}
    <div style="margin-bottom: 2rem;">
        <h2 style="color: var(--primary); margin-bottom: 1rem;">This Week</h2>
        <div class="grid grid-2">
            {% for meeting in this_week %}
            <div
                style="background-color: var(--bg-light); padding: 1rem; border-radius: 8px; border-left: 4px solid var(--primary);">
                <a href="{{ url_for('meeting_detail', meeting_id=meeting.id) }}"
                    style="text-decoration: none; color: inherit;">
                    <h3 style="color: var(--primary); margin-bottom: 0.5rem;">{{ meeting.title }}</h3>
                    <p style="color: var(--text-light); margin: 0.25rem 0;">
                        <strong>📅 {{ meeting.meeting_time }}</strong>
                    </p>
                    <p style="color: var(--text-light); margin: 0.25rem 0;">
                        👤 {{ meeting.created_by_name }}
                    </p>
                    {% if meeting.group_name %}
                    <span class="badge badge-user" style="margin-top: 0.5rem;">{{ meeting.group_name }}</span>
                    {% endif %}
                </a>
            </div>
            {% endfor %}
        </div>
    </div>
    {% endif %}

    <!-- Calendar Section -->
    <div style="margin-bottom: 2rem;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
            <h2 style="color: var(--primary);">Calendar</h2>
            <div style="display: flex; gap: 1rem; align-items: center;">
                <button onclick="changeMonth(-1)" class="btn btn-secondary">← Previous</button>
                <span id="currentMonth" style="font-weight: bold; min-width: 150px; text-align: center;"></span>
                <button onclick="changeMonth(1)" class="btn btn-secondary">Next →</button>
            </div>
        </div>
        <div id="calendar" style="background-color: var(--bg-light); padding: 1rem; border-radius: 8px;">
            <!-- Calendar will be generated by JavaScript -->
        </div>
    </div>

    <!-- Filter by Tags -->
    <div style="margin-bottom: 1rem;">
        <label style="font-weight: bold; margin-right: 1rem;">Filter by Tag:</label>
        <select onchange="filterByTag(this.value)" class="form-control"
            style="display: inline-block; width: auto; min-width: 200px;">
            <option value="">All Meetings</option>
            {% for tag in available_tags %}
            <option value="{{ tag }}" {% if request.args.get('tag')==tag %}selected{% endif %}>{{ tag }}</option>
            {% endfor %}
        </select>
    </div>

    <!-- All Meetings List -->
    <table class="table">
        <thead>
            <tr>
                <th>Title</th>
                <th>Date & Time</th>
                <th>Group</th>
                <th>Tags</th>
                <th>Organized By</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            {% for meeting in meetings %}
            <tr>
                <td><strong>{{ meeting.title }}</strong></td>
                <td>{{ meeting.meeting_time }}</td>
                <td>
                    {% if meeting.group_name %}
                    <span class="badge badge-user">{{ meeting.group_name }}</span>
                    {% else %}
                    <span style="color: var(--text-light);">All Lab</span>
                    {% endif %}
                </td>
                <td>
                    {% if meeting.tags %}
                    {% for tag in meeting.tags.split(',') %}
                    <span class="badge" style="background-color: var(--accent); color: white; margin-right: 0.25rem;">{{
                        tag }}</span>
                    {% endfor %}
                    {% else %}
                    -
                    {% endif %}
                </td>
                <td>{{ meeting.created_by_name }}</td>
                <td>
                    <a href="{{ url_for('meeting_detail', meeting_id=meeting.id) }}" class="btn btn-secondary"
                        style="padding: 0.5rem 1rem;">View Details</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>

    {% if not meetings %}
    <p style="text-align: center; color: var(--text-light); padding: 2rem;">No meetings found.</p>
    {% endif %}
</div>

<script>
    let currentDate = new Date();

    function filterByTag(tag) {
        if (tag) {
            window.location.href = '{{ url_for("meetings") }}?tag=' + encodeURIComponent(tag);
        } else {
            window.location.href = '{{ url_for("meetings") }}';
        }
    }

    function changeMonth(delta) {
        currentDate.setMonth(currentDate.getMonth() + delta);
        renderCalendar();
    }

    async function renderCalendar() {
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1;

        // Update month display
        const monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'];
        document.getElementById('currentMonth').textContent = monthNames[month - 1] + ' ' + year;

        // Fetch meetings for this month
        const response = await fetch(`/meetings/calendar/${year}/${month}`);
        const data = await response.json();
        const meetings = data.meetings;

        // Create calendar grid
        const firstDay = new Date(year, month - 1, 1).getDay();
        const daysInMonth = new Date(year, month, 0).getDate();

        let html = '<div style="display: grid; grid-template-columns: repeat(7, 1fr); gap: 0.5rem;">';

        // Day headers
        const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
        days.forEach(day => {
            html += `<div style="text-align: center; font-weight: bold; padding: 0.5rem; background-color: var(--accent); color: white; border-radius: 4px;">${day}</div>`;
        });

        // Empty cells before first day
        for (let i = 0; i < firstDay; i++) {
            html += '<div style="background-color: white; min-height: 80px; border-radius: 4px;"></div>';
        }

        // Days of month
        for (let day = 1; day <= daysInMonth; day++) {
            const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
            const dayMeetings = meetings.filter(m => m.meeting_time.startsWith(dateStr));

            let cellClass = 'background-color: white; min-height: 80px; border-radius: 4px; padding: 0.5rem; position: relative;';
            if (dayMeetings.length > 0) {
                cellClass = 'background-color: #FFF8DC; min-height: 80px; border-radius: 4px; padding: 0.5rem; position: relative; border: 2px solid var(--primary); cursor: pointer;';
            }

            html += `<div style="${cellClass}" ${dayMeetings.length > 0 ? `onclick="showDayMeetings('${dateStr}')"` : ''}>`;
            html += `<div style="font-weight: bold; color: var(--primary);">${day}</div>`;

            if (dayMeetings.length > 0) {
                html += `<div style="font-size: 0.75rem; color: var(--text-light); margin-top: 0.25rem;">`;
                dayMeetings.slice(0, 2).forEach(m => {
                    html += `<a href="/meetings/${m.id}" style="text-decoration: none; color: inherit; display: block;" onclick="event.stopPropagation()">`;
                    html += `<div style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" title="${m.title}">• ${m.title}</div>`;
                    html += `</a>`;
                });
                if (dayMeetings.length > 2) {
                    html += `<div>+${dayMeetings.length - 2} more</div>`;
                }
                html += `</div>`;
            }

            html += '</div>';
        }

        html += '</div>';
        document.getElementById('calendar').innerHTML = html;
    }

    function showDayMeetings(dateStr) {
        // Find all meetings on this day and display them
        const rows = Array.from(document.querySelectorAll('.table tbody tr'));
        rows.forEach(row => {
            const dateCell = row.cells[1].textContent;
            if (dateCell.startsWith(dateStr)) {
                row.style.backgroundColor = '#FFF8DC';
                row.scrollIntoView({ behavior: 'smooth', block: 'center' });
            } else {
                row.style.backgroundColor = '';
            }
        });
    }

    // Initialize calendar on page load
    document.addEventListener('DOMContentLoaded', function () {
        renderCalendar();
    });
</script>
{% endblock %}