{% extends "base.html" %}

{% block title %}{{ _('Create Task') }} - Time Tracker{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://uicdn.toast.com/editor/latest/toastui-editor.min.css">
<link rel="stylesheet" href="https://uicdn.toast.com/editor/latest/theme/toastui-editor-dark.css">
{% endblock %}

{% block content %}
<div class="container mt-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card mobile-card">
                <div class="card-body py-4">
                    <div class="d-flex align-items-center">
                        <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 48px; height: 48px;">
                            <i class="fas fa-plus text-primary fa-lg"></i>
                        </div>
                        <div>
                            <h1 class="h2 mb-1">{{ _('Create New Task') }}</h1>
                            <p class="text-muted mb-0">{{ _('Add a new task to your project to break down work into manageable components') }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Create Task Form -->
    <div class="row">
        <div class="col-lg-8">
            <div class="card mobile-card">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-edit me-2 text-primary"></i>{{ _('Task Information') }}
                    </h6>
                </div>
                <div class="card-body">
                    <form method="POST" id="createTaskForm">
                        <!-- Task Name -->
                        <div class="mb-4">
                            <label for="name" class="form-label fw-semibold">
                                <i class="fas fa-tag me-2 text-primary"></i>{{ _('Task Name') }} <span class="text-danger">*</span>
                            </label>
                            <input type="text" class="form-control form-control-lg" id="name" name="name" 
                                   value="{{ request.form.get('name', '') }}" placeholder="{{ _('Enter a descriptive task name') }}" required>
                            <small class="form-text text-muted">{{ _('Choose a clear, descriptive name that explains what needs to be done') }}</small>
                        </div>

                        <!-- Description -->
                        <div class="mb-4">
                            <label for="description" class="form-label fw-semibold d-flex align-items-center justify-content-between">
                                <i class="fas fa-align-left me-2 text-primary"></i>{{ _('Description') }}
                                <small class="text-muted">{{ _('Supports Markdown') }}</small>
                            </label>
                            <div class="markdown-editor-wrapper">
                                <textarea class="form-control d-none" id="description" name="description" rows="12" placeholder="{{ _('Provide detailed information about the task, requirements, and any specific instructions...') }}">{{ request.form.get('description', '') }}</textarea>
                                <div id="description_editor"></div>
                            </div>
                            <small class="form-text text-muted">{{ _('Optional: Add context, requirements, or specific instructions for the task') }}</small>
                        </div>

                        <!-- Project Selection -->
                        <div class="mb-4">
                            <label for="project_id" class="form-label fw-semibold">
                                <i class="fas fa-project-diagram me-2 text-primary"></i>{{ _('Project') }} <span class="text-danger">*</span>
                            </label>
                            <select class="form-select form-select-lg" id="project_id" name="project_id" required>
                                <option value="">{{ _('Select a project') }}</option>
                                {% for project in projects %}
                                <option value="{{ project.id }}" {% if request.form.get('project_id')|int == project.id or request.args.get('project_id')|int == project.id %}selected{% endif %}>
                                    {{ project.name }} ({{ project.client }})
                                </option>
                                {% endfor %}
                            </select>
                            <small class="form-text text-muted">{{ _('Select the project this task belongs to') }}</small>
                        </div>

                        <!-- Priority and Status -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label for="priority" class="form-label fw-semibold">
                                    <i class="fas fa-flag me-2 text-warning"></i>{{ _('Priority') }}
                                </label>
                                <select class="form-select" id="priority" name="priority">
                                    <option value="low" {% if request.form.get('priority') == 'low' %}selected{% endif %}>{{ _('Low') }}</option>
                                    <option value="medium" {% if request.form.get('priority') == 'medium' or not request.form.get('priority') %}selected{% endif %}>{{ _('Medium') }}</option>
                                    <option value="high" {% if request.form.get('priority') == 'high' %}selected{% endif %}>{{ _('High') }}</option>
                                    <option value="urgent" {% if request.form.get('priority') == 'urgent' %}selected{% endif %}>{{ _('Urgent') }}</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="status" class="form-label fw-semibold">
                                    <i class="fas fa-tasks me-2 text-info"></i>{{ _('Initial Status') }}
                                </label>
                                <select class="form-select" id="status" name="status">
                                    <option value="todo" {% if request.form.get('status') == 'todo' or not request.form.get('status') %}selected{% endif %}>{{ _('To Do') }}</option>
                                    <option value="in_progress" {% if request.form.get('status') == 'in_progress' %}selected{% endif %}>{{ _('In Progress') }}</option>
                                    <option value="review" {% if request.form.get('status') == 'review' %}selected{% endif %}>{{ _('Review') }}</option>
                                    <option value="done" {% if request.form.get('status') == 'done' %}selected{% endif %}>{{ _('Done') }}</option>
                                    <option value="cancelled" {% if request.form.get('status') == 'cancelled' %}selected{% endif %}>{{ _('Cancelled') }}</option>
                                </select>
                            </div>
                        </div>

                        <!-- Due Date and Estimated Hours -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label for="due_date" class="form-label fw-semibold">
                                    <i class="fas fa-calendar me-2 text-secondary"></i>{{ _('Due Date') }}
                                </label>
                                <input type="date" class="form-control" id="due_date" name="due_date" 
                                       value="{{ request.form.get('due_date', '') }}">
                                <small class="form-text text-muted">{{ _('Optional: Set a deadline for this task') }}</small>
                            </div>
                            <div class="col-md-6">
                                <label for="estimated_hours" class="form-label fw-semibold">
                                    <i class="fas fa-clock me-2 text-warning"></i>{{ _('Estimated Hours') }}
                                </label>
                                <input type="number" class="form-control" id="estimated_hours" name="estimated_hours" 
                                       value="{{ request.form.get('estimated_hours', '') }}" step="0.5" min="0" placeholder="0.0">
                                <small class="form-text text-muted">{{ _('Optional: Estimate how long this task will take') }}</small>
                            </div>
                        </div>

                        <!-- Assignment -->
                        <div class="mb-4">
                            <label for="assigned_to" class="form-label fw-semibold">
                                <i class="fas fa-user me-2 text-info"></i>{{ _('Assign To') }}
                            </label>
                            <select class="form-select" id="assigned_to" name="assigned_to">
                                <option value="">{{ _('Unassigned') }}</option>
                                {% for user in users %}
                                <option value="{{ user.id }}" {% if request.form.get('assigned_to')|int == user.id %}selected{% endif %}>
                                    {{ user.display_name }}
                                </option>
                                {% endfor %}
                            </select>
                            <small class="form-text text-muted">{{ _('Optional: Assign this task to a team member') }}</small>
                        </div>

                        <!-- Form Actions -->
                        <div class="d-flex gap-3 pt-3 border-top">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="fas fa-save me-2"></i>{{ _('Create Task') }}
                            </button>
                            <a href="{{ url_for('tasks.list_tasks') }}" class="btn btn-outline-secondary btn-lg">
                                <i class="fas fa-times me-2"></i>{{ _('Cancel') }}
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Sidebar Help -->
        <div class="col-lg-4">
            <!-- Task Creation Tips -->
            <div class="card mobile-card mb-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-lightbulb me-2 text-warning"></i>{{ _('Task Creation Tips') }}
                    </h6>
                </div>
                <div class="card-body">
                    <div class="tip-item mb-3">
                        <div class="d-flex align-items-start">
                            <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 24px; height: 24px;">
                                <i class="fas fa-check text-primary fa-xs"></i>
                            </div>
                            <div>
                                <small class="fw-semibold d-block">{{ _('Clear Naming') }}</small>
                                <small class="text-muted">{{ _('Use action verbs and be specific about what needs to be done') }}</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="tip-item mb-3">
                        <div class="d-flex align-items-start">
                            <div class="bg-success bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 24px; height: 24px;">
                                <i class="fas fa-clock text-success fa-xs"></i>
                            </div>
                            <div>
                                <small class="fw-semibold d-block">{{ _('Realistic Estimates') }}</small>
                                <small class="text-muted">{{ _('Consider complexity and dependencies when estimating time') }}</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="tip-item mb-3">
                        <div class="d-flex align-items-start">
                            <div class="bg-info bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 24px; height: 24px;">
                                <i class="fas fa-calendar text-info fa-xs"></i>
                            </div>
                            <div>
                                <small class="fw-semibold d-block">{{ _('Set Deadlines') }}</small>
                                <small class="text-muted">{{ _('Due dates help prioritize work and track progress') }}</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="tip-item">
                        <div class="d-flex align-items-start">
                            <div class="bg-warning bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 24px; height: 24px;">
                                <i class="fas fa-flag text-warning fa-xs"></i>
                            </div>
                            <div>
                                <small class="fw-semibold d-block">{{ _('Priority Matters') }}</small>
                                <small class="text-muted">{{ _('Use priority levels to help team members focus on what\'s most important') }}</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Priority Guide -->
            <div class="card mobile-card mb-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-info-circle me-2 text-info"></i>{{ _('Priority Guide') }}
                    </h6>
                </div>
                <div class="card-body">
                    <div class="priority-guide-item mb-3">
                        <div class="d-flex align-items-center mb-2">
                            <span class="priority-badge priority-low me-2">{{ _('Low') }}</span>
                            <small class="text-muted">{{ _('Non-urgent, can be done later') }}</small>
                        </div>
                    </div>
                    
                    <div class="priority-guide-item mb-3">
                        <div class="d-flex align-items-center mb-2">
                            <span class="priority-badge priority-medium me-2">{{ _('Medium') }}</span>
                            <small class="text-muted">{{ _('Normal priority, standard timeline') }}</small>
                        </div>
                    </div>
                    
                    <div class="priority-guide-item mb-3">
                        <div class="d-flex align-items-center mb-2">
                            <span class="priority-badge priority-high me-2">{{ _('High') }}</span>
                            <small class="text-muted">{{ _('Important, needs attention soon') }}</small>
                        </div>
                    </div>
                    
                    <div class="priority-guide-item">
                        <div class="d-flex align-items-center mb-2">
                            <span class="priority-badge priority-urgent me-2">{{ _('Urgent') }}</span>
                            <small class="text-muted">{{ _('Critical, immediate attention required') }}</small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Status Guide -->
            <div class="card mobile-card">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-list me-2 text-secondary"></i>{{ _('Status Guide') }}
                    </h6>
                </div>
                <div class="card-body">
                    <div class="status-guide-item mb-3">
                        <div class="d-flex align-items-center mb-2">
                            <span class="status-badge status-todo me-2">{{ _('To Do') }}</span>
                            <small class="text-muted">{{ _('Task is planned but not started') }}</small>
                        </div>
                    </div>
                    
                    <div class="status-guide-item mb-3">
                        <div class="d-flex align-items-center mb-2">
                            <span class="status-badge status-in_progress me-2">{{ _('In Progress') }}</span>
                            <small class="text-muted">{{ _('Work has begun on the task') }}</small>
                        </div>
                    </div>
                    
                    <div class="status-guide-item mb-3">
                        <div class="d-flex align-items-center mb-2">
                            <span class="status-badge status-review me-2">{{ _('Review') }}</span>
                            <small class="text-muted">{{ _('Task is ready for review/testing') }}</small>
                        </div>
                    </div>
                    
                    <div class="status-guide-item">
                        <div class="d-flex align-items-center mb-2">
                            <span class="status-badge status-done me-2">{{ _('Done') }}</span>
                            <small class="text-muted">{{ _('Task is completed successfully') }}</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Priority Badges */
.priority-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.priority-low {
    background-color: #dcfce7;
    color: #166534;
}

.priority-medium {
    background-color: #fef3c7;
    color: #92400e;
}

.priority-high {
    background-color: #fed7aa;
    color: #c2410c;
}

.priority-urgent {
    background-color: #fee2e2;
    color: #991b1b;
}

/* Status Badges */
.status-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.status-todo {
    background-color: #e2e8f0;
    color: #475569;
}

.status-in_progress {
    background-color: #fef3c7;
    color: #92400e;
}

.status-review {
    background-color: #dbeafe;
    color: #1e40af;
}

.status-done {
    background-color: #dcfce7;
    color: #166534;
}

/* Tip Items */
.tip-item {
    padding: 0.75rem;
    border-radius: 8px;
    background-color: #f8fafc;
    transition: all 0.2s ease;
}

.tip-item:hover {
    background-color: #f1f5f9;
    transform: translateX(4px);
}

/* Priority and Status Guide Items */
.priority-guide-item,
.status-guide-item {
    padding: 0.5rem;
    border-radius: 6px;
    transition: all 0.2s ease;
}

.priority-guide-item:hover,
.status-guide-item:hover {
    background-color: #f8fafc;
}

/* Form Styling */
.form-control:focus,
.form-select:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 0.2rem rgba(59, 130, 246, 0.25);
}

.form-control-lg {
    min-height: 56px;
}

.form-select-lg {
    min-height: 56px;
}

/* Mobile Optimizations */
@media (max-width: 768px) {
    .card-header {
        padding: 1rem 1rem 0.75rem 1rem;
    }
    
    .card-body {
        padding: 0.75rem 1rem;
    }
    
    .tip-item:hover {
        transform: none;
    }
    
    .priority-guide-item:hover,
    .status-guide-item:hover {
        background-color: transparent;
    }
}

/* Hover Effects */
.btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.tip-item:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* Enhanced markdown editor styles are now centralized in base.css */
</style>

<!-- Toast UI Editor -->
<script src="https://uicdn.toast.com/editor/latest/toastui-editor-all.min.js"></script>

<script>
// Form validation and enhancement
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('createTaskForm');
    const nameInput = document.getElementById('name');
    const descriptionInput = document.getElementById('description');
    let mdEditor = null;

    // Initialize Toast UI Editor
    if (descriptionInput && window.toastui && window.toastui.Editor) {
        const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'light';
        mdEditor = new toastui.Editor({
            el: document.getElementById('description_editor'),
            height: '380px',
            initialEditType: 'wysiwyg',
            previewStyle: 'vertical',
            usageStatistics: false,
            hideModeSwitch: false,
            placeholder: 'Provide detailed information about the task, requirements, and any specific instructions...',
            theme: theme,
            toolbarItems: [
                ['heading', 'bold', 'italic', 'strike'],
                ['hr', 'quote'],
                ['ul', 'ol', 'task'],
                ['link', 'code', 'codeblock', 'table'],
                ['image'],
                ['scrollSync']
            ],
            initialValue: descriptionInput.value || ''
        });

        // Apply theme changes dynamically if supported
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.type === 'attributes' && mutation.attributeName === 'data-theme' && mdEditor) {
                    const nextTheme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'light';
                    try {
                        if (typeof mdEditor.setTheme === 'function') {
                            mdEditor.setTheme(nextTheme);
                        }
                    } catch (e) {}
                }
            });
        });
        observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });

        // Image upload hook
        mdEditor.removeHook && mdEditor.removeHook('addImageBlobHook');
        mdEditor.addHook && mdEditor.addHook('addImageBlobHook', async (blob, callback) => {
            try {
                const formData = new FormData();
                formData.append('image', blob, blob.name || 'upload.png');
                const res = await fetch('{{ url_for('api.upload_editor_image') }}', {
                    method: 'POST',
                    body: formData
                });
                const data = await res.json();
                if (data && data.url) {
                    callback(data.url, blob.name || 'image');
                } else {
                    console.warn('Upload failed', data);
                }
            } catch (e) { console.error('Image upload error', e); }
        });

        // Autosave to localStorage
        const autosaveKey = 'tt-task-create-description';
        if (!descriptionInput.value) {
            const cached = localStorage.getItem(autosaveKey);
            if (cached) { try { mdEditor.setMarkdown(cached); } catch(e) {} }
        }
        mdEditor.on && mdEditor.on('change', () => {
            try { localStorage.setItem(autosaveKey, mdEditor.getMarkdown()); } catch (e) {}
        });
    }
    
    // Form submission enhancement
    form.addEventListener('submit', function(e) {
        const name = nameInput.value.trim();
        if (!name) {
            e.preventDefault();
            nameInput.focus();
            nameInput.classList.add('is-invalid');
            return false;
        }
        // Sync markdown content back to hidden textarea
        if (mdEditor && descriptionInput) {
            try { descriptionInput.value = mdEditor.getMarkdown(); } catch (err) {}
        }
        
        // Sync markdown content back to hidden textarea
        if (mdEditor && descriptionInput) {
            try { descriptionInput.value = mdEditor.getMarkdown(); } catch (err) {}
        }
        // Show loading state
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Creating...';
        submitBtn.disabled = true;
        
        // Re-enable after a delay (in case of validation errors)
        setTimeout(() => {
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }, 5000);
    });
    
    // Real-time validation feedback
    nameInput.addEventListener('input', function() {
        if (this.value.trim()) {
            this.classList.remove('is-invalid');
            this.classList.add('is-valid');
        } else {
            this.classList.remove('is-valid');
        }
    });
});
</script>
{% endblock %}
