{% extends 'base.html' %}
{% load static %}

{% block title %}Planning Board | AI ML Operations{% endblock %}

{% block content %}
<style>
    /* Custom Kanban styles to match the cyber aesthetic */
    .kanban-board {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 2rem;
        padding: 2rem 0;
        align-items: start;
    }

    .kanban-column {
        background: rgba(26, 26, 26, 0.6);
        border: 1px solid rgba(255, 255, 255, 0.05);
        border-radius: 12px;
        padding: 1.5rem;
        min-height: 500px;
        transition: border-color 0.3s;
    }

    .kanban-column h3 {
        margin-bottom: 1rem;
        color: var(--primary-color);
        text-transform: uppercase;
        font-size: 1.25rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .kanban-items {
        min-height: 400px;
        /* For drop zone */
    }

    .kanban-item {
        background: var(--surface-color);
        border: 1px solid rgba(0, 243, 255, 0.1);
        border-radius: 8px;
        padding: 1rem;
        margin-bottom: 1rem;
        cursor: grab;
        transition: transform 0.2s, box-shadow 0.2s;
    }

    .kanban-item:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0, 243, 255, 0.2);
        border-color: var(--primary-color);
    }

    .kanban-item:active {
        cursor: grabbing;
    }

    .kanban-item-title {
        font-weight: 600;
        margin-bottom: 0.5rem;
        color: white;
    }

    .kanban-item-desc {
        font-size: 0.85rem;
        color: var(--text-muted);
    }

    /* Modal Styles */
    .modal {
        display: none;
        position: fixed;
        z-index: 2000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.8);
        backdrop-filter: blur(5px);
    }

    .modal-content {
        background-color: var(--surface-color);
        margin: 10% auto;
        padding: 2rem;
        border: 1px solid var(--primary-color);
        border-radius: 12px;
        width: 90%;
        max-width: 600px;
        color: var(--text-color);
        box-shadow: 0 0 30px rgba(0, 243, 255, 0.2);
    }

    .close {
        color: var(--text-muted);
        float: right;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
    }

    .close:hover {
        color: var(--secondary-color);
    }

    .badge {
        background: rgba(255, 255, 255, 0.1);
        padding: 0.2rem 0.5rem;
        border-radius: 12px;
        font-size: 0.8rem;
        color: white;
    }

    @media (max-width: 968px) {
        .kanban-board {
            grid-template-columns: 1fr;
        }
    }
</style>

<div class="container section">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
        <h2 class="section-title" style="margin-bottom: 0;">Planning Board</h2>
        <div>
            <a href="{% url 'planning:backlog_view' %}" class="btn"
                style="padding: 0.5rem 1rem; border-radius: 8px; margin-right: 1rem; background: var(--surface-color); color: var(--text-color); border: 1px solid var(--primary-color);">View
                Backlog</a>
            {% if is_developer %}
            <button class="btn" id="openAddModalBtn">Add Item</button>
            {% endif %}
        </div>
    </div>

    <div class="kanban-board">
        <!-- TODO Column -->
        <div class="kanban-column" id="col-TODO">
            <h3>Todo <span class="badge">{{ todo_items.count }}</span></h3>
            <div class="kanban-items" data-status="TODO">
                {% for item in todo_items %}
                <div class="kanban-item" draggable="{% if is_developer %}true{% else %}false{% endif %}"
                    data-id="{{ item.id }}">
                    <div class="kanban-item-title">{{ item.title }}</div>
                    {% if item.charge_number %}
                    <div style="margin-bottom: 0.5rem;"><span class="badge"
                            style="background: rgba(188, 19, 254, 0.2); color: var(--secondary-color); border: 1px solid var(--secondary-color);">
                            {{ item.charge_number.contract.name }} ({{ item.charge_number }})</span></div>
                    {% endif %}
                    {% if item.description %}
                    <div class="kanban-item-desc">{{ item.description|truncatechars:50 }}</div>
                    {% endif %}
                </div>
                {% endfor %}
            </div>
        </div>

        <!-- In Progress Column -->
        <div class="kanban-column" id="col-IN_PROGRESS">
            <h3>In Progress <span class="badge">{{ in_progress_items.count }}</span></h3>
            <div class="kanban-items" data-status="IN_PROGRESS">
                {% for item in in_progress_items %}
                <div class="kanban-item" draggable="{% if is_developer %}true{% else %}false{% endif %}"
                    data-id="{{ item.id }}">
                    <div class="kanban-item-title">{{ item.title }}</div>
                    {% if item.charge_number %}
                    <div style="margin-bottom: 0.5rem;"><span class="badge"
                            style="background: rgba(188, 19, 254, 0.2); color: var(--secondary-color); border: 1px solid var(--secondary-color);">
                            {{ item.charge_number.contract.name }} ({{ item.charge_number }})</span></div>
                    {% endif %}
                    {% if item.description %}
                    <div class="kanban-item-desc">{{ item.description|truncatechars:50 }}</div>
                    {% endif %}
                </div>
                {% endfor %}
            </div>
        </div>

        <!-- Done Column -->
        <div class="kanban-column" id="col-DONE">
            <h3>Done <span class="badge">{{ done_items.count }}</span></h3>
            <div class="kanban-items" data-status="DONE">
                {% for item in done_items %}
                <div class="kanban-item" draggable="{% if is_developer %}true{% else %}false{% endif %}"
                    data-id="{{ item.id }}">
                    <div class="kanban-item-title">{{ item.title }}</div>
                    {% if item.charge_number %}
                    <div style="margin-bottom: 0.5rem;"><span class="badge"
                            style="background: rgba(188, 19, 254, 0.2); color: var(--secondary-color); border: 1px solid var(--secondary-color);">
                            {{ item.charge_number.contract.name }} ({{ item.charge_number }})</span></div>
                    {% endif %}
                    {% if item.description %}
                    <div class="kanban-item-desc">{{ item.description|truncatechars:50 }}</div>
                    {% endif %}
                </div>
                {% endfor %}
            </div>
        </div>
    </div>
</div>

<!-- Add Item Modal -->
<div id="addItemModal" class="modal">
    <div class="modal-content">
        <span class="close" id="closeAddModal">&times;</span>
        <h2 style="color: var(--primary-color); margin-bottom: 1.5rem;">New Item</h2>
        <form method="post" action="{% url 'planning:create_item' %}">
            {% csrf_token %}
            <div class="form-group">
                <label style="color: var(--text-muted); margin-bottom: 0.5rem; display: block;">Title</label>
                <input type="text" name="title" class="form-control" required>
            </div>
            <div class="form-group">
                <label style="color: var(--text-muted); margin-bottom: 0.5rem; display: block;">Charge Number
                    (QBD)</label>
                <select name="charge_number" class="form-control">
                    <option value="">-- No Charge Number --</option>
                    {% for cn in qbd_charge_numbers %}
                    <option value="{{ cn.id }}">{{ cn.contract.name }} - {{ cn.slug }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="form-group">
                <label style="color: var(--text-muted); margin-bottom: 0.5rem; display: block;">Description</label>
                <textarea name="description" class="form-control" rows="4"></textarea>
            </div>
            <input type="hidden" name="next" value="{{ request.path }}">
            <button type="submit" class="btn"
              data-tianji-event="planning_create_item">Create</button>
        </form>
    </div>
</div>

<!-- Item Details Modal -->
<div id="itemDetailModal" class="modal">
    <div class="modal-content">
        <span class="close" id="closeDetailModal">&times;</span>
        <div id="itemDetailContent">
            <!-- Loaded via AJAX -->
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        // Modal logic
        const addModal = document.getElementById('addItemModal');
        const openAddBtn = document.getElementById('openAddModalBtn');
        const closeAddBtn = document.getElementById('closeAddModal');

        if (openAddBtn) {
            openAddBtn.onclick = () => addModal.style.display = "block";
        }
        if (closeAddBtn) {
            closeAddBtn.onclick = () => addModal.style.display = "none";
        }

        const detailModal = document.getElementById('itemDetailModal');
        const closeDetailBtn = document.getElementById('closeDetailModal');
        const detailContent = document.getElementById('itemDetailContent');

        closeDetailBtn.onclick = () => detailModal.style.display = "none";

        window.onclick = (event) => {
            if (event.target == addModal) addModal.style.display = "none";
            if (event.target == detailModal) detailModal.style.display = "none";
        }

        // Drag and Drop Logic
        const items = document.querySelectorAll('.kanban-item');
        const dropzones = document.querySelectorAll('.kanban-items');

        items.forEach(item => {
            item.addEventListener('dragstart', (e) => {
                e.dataTransfer.setData('text/plain', e.target.closest('.kanban-item').dataset.id);
                setTimeout(() => e.target.closest('.kanban-item').style.opacity = '0.5', 0);
            });

            item.addEventListener('dragend', (e) => {
                e.target.closest('.kanban-item').style.opacity = '1';
            });

            item.addEventListener('click', (e) => {
                const itemId = item.dataset.id;
                fetch(`/planning/item/${itemId}/`)
                    .then(res => res.text())
                    .then(html => {
                        detailContent.innerHTML = html;
                        detailModal.style.display = "block";
                    });
            });
        });

        dropzones.forEach(zone => {
            zone.addEventListener('dragover', (e) => {
                e.preventDefault(); // Necessary to allow dropping
                zone.parentElement.style.borderColor = 'var(--primary-color)';
            });

            zone.addEventListener('dragleave', (e) => {
                zone.parentElement.style.borderColor = 'rgba(255, 255, 255, 0.05)';
            });

            zone.addEventListener('drop', (e) => {
                e.preventDefault();
                zone.parentElement.style.borderColor = 'rgba(255, 255, 255, 0.05)';
                const id = e.dataTransfer.getData('text/plain');
                if (!id) return;
                const draggable = document.querySelector(`.kanban-item[data-id='${id}']`);
                if (!draggable) return;

                zone.appendChild(draggable);

                const newStatus = zone.dataset.status;

                // Send AJAX update
                fetch(`/planning/item/${id}/update/`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': '{{ csrf_token }}'
                    },
                    body: JSON.stringify({
                        status: newStatus,
                        order: Array.from(zone.children).indexOf(draggable)
                    })
                }).then(res => res.json())
                    .then(data => {
                        if (data.status !== 'success') {
                            alert('Failed to update status');
                        } else if (window.aimlTrack) {
                            window.aimlTrack('planning_item_status_change', {
                                status: newStatus,
                                item_id: id
                            });
                        }
                    });
            });
        });
    });
</script>
{% endblock %}