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

{% block title %}{% if form.instance.pk %}Edit Department{% else %}Add New Department{% endif %} | TaskFlow{% endblock %}

{% block content %}
<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-lg-10">
            <div class="card shadow-sm border-0 rounded-lg">
                <div class="card-header bg-primary text-white py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <h2 class="h4 mb-0">
                            <i class="fas {% if form.instance.pk %}fa-building-edit{% else %}fa-plus-circle{% endif %} me-2"></i>
                            {% if form.instance.pk %}Update Department{% else %}Create New Department{% endif %}
                        </h2>
                        <nav aria-label="breadcrumb" class="mb-0">
                            <ol class="breadcrumb bg-transparent p-0 mb-0">
                                <li class="breadcrumb-item"><a href="{% url 'departments:department_list' %}" class="text-white">
                                    <i class="fas fa-sitemap me-1"></i>Departments
                                </a></li>
                                <li class="breadcrumb-item active text-white-50" aria-current="page">
                                    {% if form.instance.pk %}Edit{% else %}New{% endif %}
                                </li>
                            </ol>
                        </nav>
                    </div>
                </div>

                <div class="card-body p-4">
                    <form method="post" class="needs-validation" novalidate>
                        {% csrf_token %}
                        
                        {% if form.non_field_errors %}
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            {% for error in form.non_field_errors %}
                                {{ error }}
                            {% endfor %}
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        {% endif %}

                        <!-- Department Name -->
                        <div class="mb-4">
                            <label for="{{ form.name.id_for_label }}" class="form-label fw-bold">
                                <i class="fas fa-tag me-2 text-primary"></i>
                                {{ form.name.label }}
                                {% if form.name.field.required %}<span class="text-danger">*</span>{% endif %}
                            </label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-building"></i></span>
                                {{ form.name }}
                            </div>
                            {% if form.name.help_text %}
                                <small class="form-text text-muted mt-1">
                                    <i class="fas fa-info-circle me-1"></i>{{ form.name.help_text }}
                                </small>
                            {% endif %}
                            {% if form.name.errors %}
                                <div class="invalid-feedback d-block">
                                    <i class="fas fa-exclamation-circle me-1"></i>
                                    {{ form.name.errors|join:", " }}
                                </div>
                            {% endif %}
                        </div>

                        <div class="row g-4 mb-4">
                            <!-- Parent Department -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="{{ form.parent.id_for_label }}" class="form-label fw-bold">
                                        <i class="fas fa-sitemap me-2 text-primary"></i>
                                        {{ form.parent.label }}
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-level-up-alt"></i></span>
                                        {{ form.parent }}
                                    </div>
                                    {% if form.parent.help_text %}
                                        <small class="form-text text-muted mt-1">
                                            <i class="fas fa-info-circle me-1"></i>{{ form.parent.help_text }}
                                        </small>
                                    {% endif %}
                                    {% if form.parent.errors %}
                                        <div class="invalid-feedback d-block">
                                            <i class="fas fa-exclamation-circle me-1"></i>
                                            {{ form.parent.errors|join:", " }}
                                        </div>
                                    {% endif %}
                                </div>
                            </div>
                            
                            <!-- Department Manager -->
                            {% if form.manager %}
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="{{ form.manager.id_for_label }}" class="form-label fw-bold">
                                        <i class="fas fa-user-tie me-2 text-primary"></i>
                                        {{ form.manager.label }}
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-user"></i></span>
                                        {{ form.manager }}
                                    </div>
                                    {% if form.manager.help_text %}
                                        <small class="form-text text-muted mt-1">
                                            <i class="fas fa-info-circle me-1"></i>{{ form.manager.help_text }}
                                        </small>
                                    {% endif %}
                                    {% if form.manager.errors %}
                                        <div class="invalid-feedback d-block">
                                            <i class="fas fa-exclamation-circle me-1"></i>
                                            {{ form.manager.errors|join:", " }}
                                        </div>
                                    {% endif %}
                                </div>
                            </div>
                            {% endif %}
                        </div>

                        <!-- Description -->
                        <div class="mb-4">
                            <label for="{{ form.description.id_for_label }}" class="form-label fw-bold">
                                <i class="fas fa-align-left me-2 text-primary"></i>
                                {{ form.description.label }}
                            </label>
                            <div class="form-floating">
                                {{ form.description }}
                                <label for="{{ form.description.id_for_label }}">Enter department description...</label>
                            </div>
                            {% if form.description.help_text %}
                                <small class="form-text text-muted mt-2 d-block">
                                    <i class="fas fa-info-circle me-1"></i>{{ form.description.help_text }}
                                </small>
                            {% endif %}
                            {% if form.description.errors %}
                                <div class="invalid-feedback d-block">
                                    <i class="fas fa-exclamation-circle me-1"></i>
                                    {{ form.description.errors|join:", " }}
                                </div>
                            {% endif %}
                        </div>

                        <!-- Form Actions -->
                        <div class="d-flex justify-content-between align-items-center mt-5 pt-3 border-top">
                            <a href="{% if form.instance.pk %}{% url 'departments:department_detail' form.instance.pk %}{% else %}{% url 'departments:department_list' %}{% endif %}" 
                               class="btn btn-outline-secondary px-4">
                                <i class="fas fa-arrow-left me-2"></i>Cancel
                            </a>
                            
                            <div class="d-flex">
                                {% if form.instance.pk and perms.users.delete_department %}
                                <a href="{% url 'departments:department_delete' form.instance.pk %}" 
                                   class="btn btn-outline-danger me-2"
                                   onclick="return confirm('Are you sure you want to delete this department? This action cannot be undone.')">
                                    <i class="fas fa-trash-alt me-2"></i>Delete Department
                                </a>
                                {% endif %}
                                
                                <button type="submit" class="btn btn-primary px-4">
                                    <i class="fas {% if form.instance.pk %}fa-save{% else %}fa-plus-circle{% endif %} me-2"></i>
                                    {% if form.instance.pk %}Update{% else %}Create{% endif %} Department
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <!-- Help Card -->
            <div class="card shadow-sm border-0 rounded-3 mb-4">
                <div class="card-header bg-light bg-gradient py-3">
                    <h5 class="mb-0 text-primary">
                        <i class="fas fa-question-circle me-2"></i>Quick Help
                    </h5>
                </div>
                <div class="card-body p-0">
                    <div class="list-group list-group-flush">
                        <div class="list-group-item border-0 py-3">
                            <div class="d-flex align-items-start">
                                <div class="me-3 text-primary">
                                    <i class="fas fa-tag fa-lg"></i>
                                </div>
                                <div>
                                    <h6 class="mb-1 fw-bold">Naming Guidelines</h6>
                                    <p class="small text-muted mb-0">
                                        Use clear, descriptive names that reflect the department's function or location.
                                        <br><strong>Examples:</strong> "Marketing", "Sales - North Region", "IT - Infrastructure"
                                    </p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="list-group-item border-0 py-3">
                            <div class="d-flex align-items-start">
                                <div class="me-3 text-primary">
                                    <i class="fas fa-sitemap fa-lg"></i>
                                </div>
                                <div>
                                    <h6 class="mb-1 fw-bold">Organizational Structure</h6>
                                    <p class="small text-muted mb-0">
                                        Select a parent department to create a hierarchical structure. This helps in organizing
                                        departments into logical groups and sub-groups.
                                    </p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="list-group-item border-0 py-3">
                            <div class="d-flex align-items-start">
                                <div class="me-3 text-primary">
                                    <i class="fas fa-info-circle fa-lg"></i>
                                </div>
                                <div>
                                    <h6 class="mb-1 fw-bold">Description Tips</h6>
                                    <ul class="small text-muted mb-0 ps-3">
                                        <li>Briefly describe the department's primary purpose</li>
                                        <li>List key responsibilities and functions</li>
                                        <li>Include any special notes or considerations</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Additional Help Card -->
            <div class="card shadow-sm border-0 rounded-3">
                <div class="card-body text-center py-4">
                    <div class="bg-primary bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 60px; height: 60px;">
                        <i class="fas fa-headset fa-2x text-primary"></i>
                    </div>
                    <h5 class="h6 mb-2">Need Help?</h5>
                    <p class="small text-muted mb-3">
                        Contact the system administrator if you need assistance with department setup.
                    </p>
                    <a href="mailto:support@taskflow.com" class="btn btn-sm btn-outline-primary">
                        <i class="fas fa-envelope me-1"></i> Contact Support
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

        </button>
    </div>
</form>
{% endblock %}

{% block extra_js %}
<script>
// Enhanced form validation and interactivity
document.addEventListener('DOMContentLoaded', function() {
    // Enable Bootstrap form validation
    const form = document.querySelector('.needs-validation');
    const submitBtn = form ? form.querySelector('button[type="submit"]') : null;
    
    if (form) {
        // Real-time validation on input
        const validateField = (field) => {
            if (field.checkValidity()) {
                field.classList.remove('is-invalid');
                field.classList.add('is-valid');
                
                // Add checkmark feedback for valid fields
                const feedback = field.nextElementSibling;
                if (feedback && feedback.classList.contains('valid-feedback')) {
                    feedback.style.display = 'block';
                }
            } else if (field.value) { // Only show invalid if the field has been touched
                field.classList.remove('is-valid');
                field.classList.add('is-invalid');
            }
            
            // Toggle submit button state
            if (submitBtn) {
                submitBtn.disabled = !form.checkValidity();
            }
        };
        
        // Add input event listeners to all form controls
        const formControls = form.querySelectorAll('input, select, textarea');
        formControls.forEach(control => {
            control.addEventListener('input', () => validateField(control));
            
            // Add focus/blur effects
            control.addEventListener('focus', function() {
                this.parentNode.classList.add('focused');
            });
            
            control.addEventListener('blur', function() {
                validateField(this);
                if (!this.value) {
                    this.parentNode.classList.remove('focused');
                }
            });
            
            // Initialize validation state
            if (control.value) {
                validateField(control);
            }
        });
        
        // Form submission handler
        form.addEventListener('submit', function(event) {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
                
                // Focus on first invalid field
                const firstInvalid = form.querySelector(':invalid');
                if (firstInvalid) {
                    firstInvalid.scrollIntoView({
                        behavior: 'smooth',
                        block: 'center'
                    });
                    firstInvalid.focus();
                }
            }
            
            form.classList.add('was-validated');
        }, false);
        
        // Initialize tooltips
        const tooltipTriggerList = [].slice.call(form.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function(tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl, {
                trigger: 'hover focus',
                placement: 'top'
            });
        });
        
        // Enable custom file input styling
        const fileInputs = form.querySelectorAll('.custom-file-input');
        fileInputs.forEach(input => {
            input.addEventListener('change', function() {
                const fileName = this.files[0] ? this.files[0].name : 'Choose file';
                const label = this.nextElementSibling;
                if (label) {
                    label.textContent = fileName;
                }
            });
        });
    }
    
    // Auto-resize textarea
    const textarea = document.querySelector('textarea.form-control');
    if (textarea) {
        const adjustHeight = () => {
            textarea.style.height = 'auto';
            textarea.style.height = (textarea.scrollHeight) + 'px';
        };
        
        textarea.addEventListener('input', adjustHeight);
        // Initial adjustment
        setTimeout(adjustHeight, 100);
    }
});
</script>

<style>
/* Custom form styling */
.form-control:focus, .form-select:focus {
    border-color: #86b7fe;
    box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.15);
}

/* Validation states */
.was-validated .form-control:valid,
.was-validated .form-control.is-valid,
.form-control.is-valid {
    border-color: #198754;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23198754' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right calc(0.375em + 0.1875rem) center;
    background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}

.was-validated .form-control:invalid,
.was-validated .form-control.is-invalid,
.form-control.is-invalid {
    border-color: #dc3545;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right calc(0.375em + 0.1875rem) center;
    background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}

/* Floating label animation */
.form-floating > label {
    transition: all 0.2s ease-in-out;
    color: #6c757d;
}

.form-floating > .form-control:focus ~ label,
.form-floating > .form-control:not(:placeholder-shown) ~ label,
.form-floating > .form-select ~ label {
    color: #0d6efd;
    background: #fff;
    padding: 0 0.5rem;
    transform: scale(0.85) translateY(-0.5rem) translateX(0.15rem);
}

/* Custom file input */
.custom-file-upload {
    cursor: pointer;
    display: inline-block;
    padding: 0.375rem 0.75rem;
    border: 1px solid #dee2e6;
    border-radius: 0.25rem;
    background-color: #f8f9fa;
}

/* Input group focus state */
.input-group:focus-within .input-group-text {
    border-color: #86b7fe;
    z-index: 3;
}

/* Disabled state styling */
:disabled, .form-control:disabled, .form-select:disabled {
    background-color: #e9ecef;
    opacity: 0.8;
}
</style>
{% endblock %}
