{% extends "layouts/base.html" %}
{% load i18n %}
{% load static %}

{% block title %}{{ _("New Inquiry")}} - PX360{% endblock %}

{% block extra_css %}
<style>
    .form-section {
        background: #fff;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 25px;
        margin-bottom: 20px;
    }
    .form-section-title {
        font-size: 1.1rem;
        font-weight: 600;
        color: #495057;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 2px solid #17a2b8;
    }
    .required-field::after {
        content: " *";
        color: #dc3545;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- Page Header -->
    <div class="mb-4">
        <a href="{% url 'complaints:inquiry_list' %}" class="btn btn-outline-secondary btn-sm mb-3">
            <i class="bi bi-arrow-left me-1"></i> {{ _("Back to Inquiries")}}
        </a>
        <h2 class="mb-1">
            <i class="bi bi-plus-circle text-info me-2"></i>
            {{ _("Create New Inquiry")}}
        </h2>
        <p class="text-muted mb-0">{{ _("Create a new patient inquiry or request")}}</p>
    </div>

    <form method="post" action="{% url 'complaints:inquiry_create' %}" id="inquiryForm">
        {% csrf_token %}
        
        <div class="row">
            <div class="col-lg-8">
                <!-- Organization Information -->
                <div class="form-section">
                    <h5 class="form-section-title">
                        <i class="bi bi-hospital me-2"></i>{{ _("Organization") }}
                    </h5>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label required-field">{% trans "Hospital" %}</label>
                            <select name="hospital_id" class="form-select" id="hospital-select" required>
                                <option value="">{{ _("Select hospital")}}</option>
                                {% for hospital in hospitals %}
                                <option value="{{ hospital.id }}">{{ hospital.name_en }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">{% trans "Department" %}</label>
                            <select name="department_id" class="form-select" id="department-select">
                                <option value="">{{ _("Select department")}}</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Contact/Patient Information -->
                <div class="form-section">
                    <h5 class="form-section-title">
                        <i class="bi bi-person-fill me-2"></i>{{ _("Contact Information")}}
                    </h5>
                    
                    <!-- Patient Search -->
                    <div class="mb-3">
                        <label class="form-label">{% trans "Patient" %} ({% trans "Optional" %})</label>
                        <input type="text" class="form-control" id="patient-search" 
                               placeholder="{% trans 'Search by MRN or name...' %}">
                        <input type="hidden" name="patient_id" id="patient-id">
                        <div id="patient-results" class="list-group mt-2" style="display: none;"></div>
                        <div id="selected-patient" class="alert alert-info mt-2" style="display: none;"></div>
                    </div>

                    <div class="text-muted mb-3">
                        <small>{{ _("OR") }}</small>
                    </div>

                    <!-- Contact Information (if no patient) -->
                    <div class="mb-3">
                        <label class="form-label">{% trans "Contact Name" %}</label>
                        <input type="text" name="contact_name" class="form-control"
                               placeholder="{% trans 'Name of contact person' %}">
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">{% trans "Contact Phone" %}</label>
                            <input type="tel" name="contact_phone" class="form-control"
                                   placeholder="{% trans 'Phone number' %}">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">{% trans "Contact Email" %}</label>
                            <input type="email" name="contact_email" class="form-control"
                                   placeholder="{% trans 'Email address' %}">
                        </div>
                    </div>
                </div>

                <!-- Inquiry Details -->
                <div class="form-section">
                    <h5 class="form-section-title">
                        <i class="bi bi-file-text me-2"></i>{{ _("Inquiry Details")}}
                    </h5>
                    
                    <div class="mb-3">
                        <label class="form-label required-field">{% trans "Category" %}</label>
                        <select name="category" class="form-select" required>
                            <option value="">{{ _("Select category")}}</option>
                            <option value="appointment">{{ _("Appointment")}}</option>
                            <option value="billing">{{ _("Billing")}}</option>
                            <option value="medical_records">{{ _("Medical Records")}}</option>
                            <option value="pharmacy">{{ _("Pharmacy")}}</option>
                            <option value="insurance">{{ _("Insurance")}}</option>
                            <option value="feedback">{{ _("Feedback")}}</option>
                            <option value="general">{{ _("General Information")}}</option>
                            <option value="other">{{ _("Other")}}</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label required-field">{% trans "Subject" %}</label>
                        <input type="text" name="subject" class="form-control" required maxlength="500"
                               placeholder="{% trans 'Brief summary of the inquiry' %}">
                    </div>

                    <div class="mb-3">
                        <label class="form-label required-field">{% trans "Message" %}</label>
                        <textarea name="message" class="form-control" rows="6" required
                                  placeholder="{% trans 'Detailed description of the inquiry...' %}"></textarea>
                    </div>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="col-lg-4">
                <!-- Classification -->
                <div class="form-section">
                    <h5 class="form-section-title">
                        <i class="bi bi-tags me-2"></i>{{ _("Classification") }}
                    </h5>
                    
                    <div class="mb-3">
                        <label class="form-label">{% trans "Priority" %}</label>
                        <select name="priority" class="form-select">
                            <option value="">{{ _("Select priority")}}</option>
                            <option value="low">{{ _("Low") }}</option>
                            <option value="medium" selected>{{ _("Medium") }}</option>
                            <option value="high">{{ _("High") }}</option>
                            <option value="urgent">{{ _("Urgent") }}</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">{% trans "Source" %}</label>
                        <select name="source" class="form-select">
                            <option value="">{{ _("Select source")}}</option>
                            <option value="patient">{{ _("Patient") }}</option>
                            <option value="family">{{ _("Family Member")}}</option>
                            <option value="staff">{{ _("Staff") }}</option>
                            <option value="phone">{{ _("Phone") }}</option>
                            <option value="email">{{ _("Email") }}</option>
                            <option value="website">{{ _("Website") }}</option>
                            <option value="walk_in">{{ _("Walk-in") }}</option>
                            <option value="social_media">{{ _("Social Media")}}</option>
                            <option value="call_center">{{ _("Call Center")}}</option>
                            <option value="other">{{ _("Other")}}</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">{% trans "Channel" %}</label>
                        <select name="channel" class="form-select">
                            <option value="">{{ _("Select channel")}}</option>
                            <option value="in_person">{{ _("In Person") }}</option>
                            <option value="phone">{{ _("Phone") }}</option>
                            <option value="email">{{ _("Email") }}</option>
                            <option value="web_form">{{ _("Web Form") }}</option>
                            <option value="mobile_app">{{ _("Mobile App") }}</option>
                            <option value="social_media">{{ _("Social Media")}}</option>
                            <option value="fax">{{ _("Fax") }}</option>
                            <option value="other">{{ _("Other")}}</option>
                        </select>
                    </div>
                </div>

                <!-- Due Date -->
                <div class="mb-3">
                    <label class="form-label">{% trans "Due Date" %}</label>
                    <input type="datetime-local" name="due_date" class="form-control"
                           placeholder="{% trans 'Optional due date' %}">
                    <small class="form-text text-muted">
                        {{ _("Leave empty for default based on priority")}}
                    </small>
                </div>

                <!-- Help Information -->
                <div class="alert alert-info">
                    <h6 class="alert-heading">
                        <i class="bi bi-info-circle me-2"></i>{{ _("Help")}}
                    </h6>
                    <p class="mb-0 small">
                        {{ _("Use this form to create a new inquiry from a patient or visitor.")}}
                    </p>
                    <hr class="my-2">
                    <p class="mb-0 small">
                        {{ _("If the inquiry is from a registered patient, search and select them. Otherwise, provide contact information.")}}
                    </p>
                    <p class="mb-0 small mt-2 text-muted">
                        {{ _("Fields marked with * are required.")}}
                    </p>
                </div>

                <!-- Action Buttons -->
                <div class="d-grid gap-2">
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="bi bi-check-circle me-2"></i>{{ _("Create Inquiry")}}
                    </button>
                    <a href="{% url 'complaints:inquiry_list' %}" class="btn btn-outline-secondary">
                        <i class="bi bi-x-circle me-2"></i>{{ _("Cancel") }}
                    </a>
                </div>
            </div>
        </div>
    </form>
</div>
{% endblock %}

{% block extra_js %}
<script>
// Department loading
document.getElementById('hospital-select')?.addEventListener('change', function() {
    const hospitalId = this.value;
    const departmentSelect = document.getElementById('department-select');
    
    if (!hospitalId) {
        departmentSelect.innerHTML = '<option value="">{{ _("Select department")}}</option>';
        return;
    }
    
    fetch(`/complaints/ajax/departments/?hospital_id=${hospitalId}`)
        .then(response => response.json())
        .then(data => {
            departmentSelect.innerHTML = '<option value="">{{ _("Select department")}}</option>';
            data.departments.forEach(dept => {
                const option = document.createElement('option');
                option.value = dept.id;
                option.textContent = dept.name_en || dept.name;
                departmentSelect.appendChild(option);
            });
        })
        .catch(error => console.error('Error loading departments:', error));
});

// Patient search with debounce
let searchTimeout;
document.getElementById('patient-search')?.addEventListener('input', function() {
    const query = this.value;
    const resultsDiv = document.getElementById('patient-results');
    
    clearTimeout(searchTimeout);
    
    if (query.length < 2) {
        resultsDiv.style.display = 'none';
        return;
    }
    
    searchTimeout = setTimeout(() => {
        fetch(`/complaints/ajax/search-patients/?q=${encodeURIComponent(query)}`)
            .then(response => response.json())
            .then(data => {
                if (data.patients.length === 0) {
                    resultsDiv.innerHTML = `<div class="list-group-item">{{ _("No patients found")}}</div>`;
                    resultsDiv.style.display = 'block';
                    return;
                }
                
                resultsDiv.innerHTML = '';
                data.patients.forEach(patient => {
                    const item = document.createElement('a');
                    item.href = '#';
                    item.className = 'list-group-item list-group-item-action';
                    item.innerHTML = `
                        <strong>${patient.name}</strong><br>
                        <small>{{ _("MRN") }}: ${patient.mrn} | ${patient.phone || ''} | ${patient.email || ''}</small>
                    `;
                    item.addEventListener('click', function(e) {
                        e.preventDefault();
                        selectPatient(patient);
                    });
                    resultsDiv.appendChild(item);
                });
                resultsDiv.style.display = 'block';
            })
            .catch(error => console.error('Error searching patients:', error));
    }, 300);
});

function selectPatient(patient) {
    document.getElementById('patient-id').value = patient.id;
    document.getElementById('patient-search').value = '';
    document.getElementById('patient-results').style.display = 'none';
    
    const selectedDiv = document.getElementById('selected-patient');
    selectedDiv.innerHTML = `
        <strong>{{ _("Selected Patient") }}:</strong> ${patient.name}<br>
        <small>{{ _("MRN") }}: ${patient.mrn}</small>
        <button type="button" class="btn btn-sm btn-link" onclick="clearPatient()">{{ _("Clear") }}</button>
    `;
    selectedDiv.style.display = 'block';
}

function clearPatient() {
    document.getElementById('patient-id').value = '';
    document.getElementById('selected-patient').style.display = 'none';
}

// Form validation
const form = document.getElementById('inquiryForm');
form?.addEventListener('submit', function(e) {
    if (!form.checkValidity()) {
        e.preventDefault();
        e.stopPropagation();
    }
    form.classList.add('was-validated');
});
</script>
{% endblock %}
