{% extends "base.html" %}
{% from "components/ui.html" import page_header %}

{% block title %}{{ _('Gantt Chart') }} - {{ app_name }}{% endblock %}

{% block content %}
{% set breadcrumbs = [
    {'text': 'Gantt Chart'}
] %}

{% set gantt_actions %}
<a href="{{ url_for('tasks.create_task', project_id=selected_project_id if selected_project_id else none, next=request.full_path) }}" class="inline-flex items-center gap-2 bg-primary text-white text-sm px-3 py-2 rounded-lg hover:bg-primary/90 transition-colors">
    <i class="fas fa-plus"></i> {{ _('Add task') }}
</a>
{% endset %}

{{ page_header(
    icon_class='fas fa-project-diagram',
    title_text='Gantt Chart',
    subtitle_text='Project timeline visualization',
    breadcrumbs=breadcrumbs,
    actions_html=gantt_actions
) }}

<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm mb-6">
    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4">
        <div>
            <label for="projectFilter" class="form-label">{{ _('Project') }}</label>
            <select id="projectFilter" class="form-input" onchange="loadGanttChart()">
                <option value="">{{ _('All Projects') }}</option>
                {% for project in projects %}
                <option value="{{ project.id }}" {% if selected_project_id == project.id %}selected{% endif %}>{{ project.name }}</option>
                {% endfor %}
            </select>
        </div>
        <div>
            <label for="startDate" class="form-label">{{ _('Start Date') }}</label>
            <input type="date" id="startDate" class="form-input user-date-input" onchange="loadGanttChart()">
        </div>
        <div>
            <label for="endDate" class="form-label">{{ _('End Date') }}</label>
            <input type="date" id="endDate" class="form-input user-date-input" onchange="loadGanttChart()">
        </div>
        <div class="flex items-end">
            <button onclick="loadGanttChart()" class="w-full bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90">
                <i class="fas fa-sync mr-2"></i>{{ _('Refresh') }}
            </button>
        </div>
    </div>
</div>

<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
    <div id="gantt-container" class="overflow-x-auto -mx-6 px-6" style="-webkit-overflow-scrolling: touch;">
        <div id="gantt-chart" style="min-height: 500px; min-width: 600px;"></div>
    </div>
</div>

<!-- Include Frappe Gantt library and app overrides -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/frappe-gantt@0.6.1/dist/frappe-gantt.css">
<link rel="stylesheet" href="{{ url_for('static', filename='css/gantt-chart.css') }}">
<script src="https://cdn.jsdelivr.net/npm/frappe-gantt@0.6.1/dist/frappe-gantt.min.js"></script>

<script>
let ganttChart = null;

// Initialize date inputs
document.addEventListener('DOMContentLoaded', function() {
    const today = new Date();
    const startDate = new Date(today);
    startDate.setMonth(startDate.getMonth() - 3);
    
    document.getElementById('startDate').value = startDate.toISOString().split('T')[0];
    document.getElementById('endDate').value = new Date(today.getTime() + 90 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
    
    loadGanttChart();
});

async function loadGanttChart() {
    const projectId = document.getElementById('projectFilter').value;
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    
    const params = new URLSearchParams();
    if (projectId) params.append('project_id', projectId);
    if (startDate) params.append('start_date', startDate);
    if (endDate) params.append('end_date', endDate);
    
    try {
        const response = await fetch(`{{ url_for('gantt.gantt_data') }}?${params}`);
        const data = await response.json();

        // Collect custom hex colors for dynamic CSS (item.color is 6-char hex without #)
        const customColors = new Set();
        const tasks = data.data.map(item => {
            const hex = (item.color && /^[0-9a-fA-F]{6}$/.test(item.color)) ? String(item.color).toLowerCase() : null;
            const customClass = hex
                ? 'gantt-fill-' + hex
                : (item.type === 'project' ? 'gantt-project' : 'gantt-task');
            if (hex) customColors.add(hex);
            return {
                id: item.id,
                name: item.name,
                start: item.start,
                end: item.end,
                progress: item.progress || 0,
                dependencies: Array.isArray(item.dependencies) ? item.dependencies.join(',') : (item.dependencies || ''),
                custom_class: customClass,
                type: item.type,
                project_id: item.project_id,
                task_id: item.task_id
            };
        });

        // Inject dynamic CSS for custom bar colors
        let styleEl = document.getElementById('gantt-dynamic-colors');
        if (styleEl) styleEl.remove();
        if (customColors.size > 0) {
            styleEl = document.createElement('style');
            styleEl.id = 'gantt-dynamic-colors';
            const rules = [];
            customColors.forEach(function(c) {
                const h = '#' + c;
                const sel = '.gantt .bar-wrapper.gantt-fill-' + c;
                rules.push(sel + ' .bar { fill: ' + h + ' !important; }');
                rules.push(sel + ' .bar-progress { fill: ' + h + ' !important; opacity: 0.4; }');
                rules.push(sel + ':hover .bar, ' + sel + '.active .bar { fill: ' + h + ' !important; }');
                rules.push(sel + ':hover .bar-progress, ' + sel + '.active .bar-progress { fill: ' + h + ' !important; opacity: 0.5; }');
            });
            styleEl.textContent = rules.join('\n');
            document.head.appendChild(styleEl);
        }
        
        // Destroy existing chart
        if (ganttChart) {
            ganttChart = null;
        }
        
        // Create new chart
        const container = document.getElementById('gantt-chart');
        container.innerHTML = ''; // Clear container
        
        ganttChart = new Gantt('#gantt-chart', tasks, {
            header_height: 50,
            column_width: 30,
            step: 24,
            view_modes: ['Quarter Day', 'Half Day', 'Day', 'Week', 'Month'],
            bar_height: 24,
            bar_corner_radius: 6,
            arrow_curve: 5,
            padding: 20,
            date_format: window.userPrefs ? window.userPrefs.dateFormat : 'YYYY-MM-DD',
            language: 'en',
            on_click: function(task) {
                // Handle task click
                if (task.type === 'project') {
                    window.location.href = `/projects/${task.project_id}`;
                } else if (task.type === 'task') {
                    window.location.href = `/tasks/${task.task_id}`;
                }
            },
            on_date_change: function(task, start, end) {
                // Handle date change (if editing enabled)
                console.log('Task dates changed:', task, start, end);
            },
            on_progress_change: function(task, progress) {
                // Handle progress change
                console.log('Task progress changed:', task, progress);
            },
            on_view_change: function(mode) {
                // Handle view mode change
                console.log('View mode changed:', mode);
            }
        });
        
    } catch (error) {
        console.error('Error loading Gantt chart:', error);
        document.getElementById('gantt-chart').innerHTML = 
            '<div class="text-center text-red-600 py-8">Error loading Gantt chart. Please try again.</div>';
    }
}
</script>

{% endblock %}

