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

{% block title %}{% trans "Create Inquiry" %} - {% trans "Call Center" %} - PX360{% endblock %}

{% block extra_css %}
<style>
    .page-header-gradient {
        background: linear-gradient(135deg, #005696 0%, #0069a8 50%, #007bbd 100%);
        color: white;
        padding: 1.5rem 2rem;
        border-radius: 1rem;
        margin-bottom: 1.5rem;
        box-shadow: 0 10px 15px -3px rgba(0, 86, 150, 0.2);
    }
    .section-card {
        background: white;
        border-radius: 1rem;
        border: 2px solid #e2e8f0;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        transition: all 0.3s ease;
    }
    .section-card:hover {
        border-color: #005696;
        box-shadow: 0 10px 25px -5px rgba(0, 86, 150, 0.15);
    }
    .section-header {
        padding: 1rem 1.5rem;
        border-bottom: 2px solid #e2e8f0;
        background: linear-gradient(to right, #f8fafc, #f1f5f9);
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }
    .section-icon {
        width: 40px;
        height: 40px;
        border-radius: 0.75rem;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .patient-search-result {
        padding: 10px;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        margin-bottom: 10px;
        cursor: pointer;
        transition: all 0.2s;
    }
    .patient-search-result:hover {
        background: #f8fafc;
        border-color: #005696;
    }
    .patient-search-result.selected {
        background: #e0f2fe;
        border-color: #005696;
    }
</style>
{% endblock %}

{% block content %}
<div class="page-header-gradient">
    <div class="flex justify-between items-center">
        <div>
            <div class="flex items-center gap-2 text-blue-100 text-sm mb-2">
                <a href="{% url 'callcenter:inquiry_list' %}" class="hover:text-white transition">{% trans "Call Center" %}</a>
                <i data-lucide="chevron-right" class="w-3 h-3"></i>
                <span class="text-white">{% trans "Create Inquiry" %}</span>
            </div>
            <h1 class="text-2xl font-bold">{% trans "Create Inquiry" %}</h1>
            <p class="text-blue-100 text-sm">{% trans "Create an inquiry on behalf of a patient or caller" %}</p>
        </div>
        <a href="{% url 'callcenter:inquiry_list' %}" class="inline-flex items-center px-4 py-2.5 bg-white text-navy font-medium rounded-xl hover:bg-blue-50 transition">
            <i data-lucide="arrow-left" class="w-4 h-4 me-2"></i>{% trans "Back to List" %}
        </a>
    </div>
</div>

<form method="post" action="{% url 'callcenter:create_inquiry' %}" id="inquiryForm">
    {% csrf_token %}
    <input type="hidden" name="patient_id" id="patientId">

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div class="lg:col-span-2 space-y-6">
            <div class="section-card">
                <div class="section-header">
                    <div class="section-icon bg-blue-500/10">
                        <i data-lucide="user" class="w-5 h-5 text-blue-600"></i>
                    </div>
                    <h5 class="text-lg font-semibold text-gray-800">{% trans "Caller Information" %}</h5>
                </div>
                <div class="p-6">
                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-3 mb-5 text-sm text-blue-700">
                        <i data-lucide="info" class="w-4 h-4 inline-block me-1"></i>
                        {% trans "Search for an existing patient or enter contact details manually" %}
                    </div>

                    <div class="mb-5">
                        <label class="block text-sm font-semibold text-slate-700 mb-1.5">{% trans "Search Patient" %}</label>
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-navy" id="patientSearch"
                                   placeholder="{% trans 'Search by MRN, name, phone, or national ID...' %}">
                            <button type="button" id="searchBtn" class="px-4 py-2.5 bg-navy text-white rounded-xl text-sm font-semibold hover:bg-navy/90 transition">
                                <i data-lucide="search" class="w-4 h-4 inline-block"></i> {% trans "Search" %}
                            </button>
                        </div>
                        <div id="patientResults" class="mt-2"></div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-5">
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-1.5">{% trans "Contact Name" %} <span class="text-red-500">*</span></label>
                            <input type="text" name="contact_name" id="contactName" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-navy"
                                   placeholder="{% trans 'Full name' %}" required>
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-1.5">{% trans "Contact Phone" %} <span class="text-red-500">*</span></label>
                            <input type="tel" name="contact_phone" id="contactPhone" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-navy"
                                   placeholder="{% trans 'Phone number' %}" required>
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-1.5">{% trans "Contact Email" %}</label>
                            <input type="email" name="contact_email" id="contactEmail" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-navy"
                                   placeholder="{% trans 'Email address' %}">
                        </div>
                    </div>

                    <div class="mt-4">
                        <label class="block text-sm font-semibold text-slate-700 mb-1.5">{% trans "Relationship" %} <span class="text-red-500">*</span></label>
                        <select name="caller_relationship" class="px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-navy bg-white" required>
                            <option value="patient">{% trans "Patient" %}</option>
                            <option value="family">{% trans "Family Member" %}</option>
                            <option value="other">{% trans "Other" %}</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="section-card">
                <div class="section-header">
                    <div class="section-icon bg-cyan-500/10">
                        <i data-lucide="building-2" class="w-5 h-5 text-cyan-600"></i>
                    </div>
                    <h5 class="text-lg font-semibold text-gray-800">{% trans "Organization" %}</h5>
                </div>
                <div class="p-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-1.5">{% trans "Hospital" %}</label>
                            <input type="text" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm bg-slate-50" value="{{ current_hospital.name }}" readonly>
                            <input type="hidden" name="hospital_id" value="{{ current_hospital.id }}">
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-1.5">{% trans "Department" %}</label>
                            <select name="department_id" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-navy bg-white" id="departmentSelect">
                                <option value="">{% trans "Select department..." %}</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <div class="section-card">
                <div class="section-header">
                    <div class="section-icon bg-orange-500/10">
                        <i data-lucide="help-circle" class="w-5 h-5 text-orange-600"></i>
                    </div>
                    <h5 class="text-lg font-semibold text-gray-800">{% trans "Inquiry Details" %}</h5>
                </div>
                <div class="p-6 space-y-5">
                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-1.5">{% trans "Category" %} <span class="text-red-500">*</span></label>
                        <select name="category" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-navy bg-white" required>
                            <option value="">{% trans "Select category..." %}</option>
                            <option value="appointment">{% trans "Appointment" %}</option>
                            <option value="billing">{% trans "Billing" %}</option>
                            <option value="medical_records">{% trans "Medical Records" %}</option>
                            <option value="general">{% trans "General Information" %}</option>
                            <option value="other">{% trans "Other" %}</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-1.5">{% trans "Subject" %} <span class="text-red-500">*</span></label>
                        <input type="text" name="subject" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-navy"
                               placeholder="{% trans 'Brief summary of the inquiry' %}" required maxlength="500">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-1.5">{% trans "Message" %} <span class="text-red-500">*</span></label>
                        <textarea name="message" class="w-full px-4 py-3 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-navy resize-none" rows="6"
                                  placeholder="{% trans 'Detailed description of the inquiry. Include all relevant information provided by the caller...' %}" required></textarea>
                    </div>
                </div>
            </div>
        </div>

        <div class="space-y-6">
            <div class="section-card">
                <div class="section-header">
                    <div class="section-icon bg-blue-500/10">
                        <i data-lucide="info" class="w-5 h-5 text-blue-600"></i>
                    </div>
                    <h5 class="text-lg font-semibold text-gray-800">{% trans "Categories" %}</h5>
                </div>
                <div class="p-6 text-sm text-slate-600 space-y-2">
                    <p><strong>{% trans "Appointment:" %}</strong> {% trans "Scheduling, rescheduling, or cancellation" %}</p>
                    <p><strong>{% trans "Billing:" %}</strong> {% trans "Payment questions or invoice requests" %}</p>
                    <p><strong>{% trans "Medical Records:" %}</strong> {% trans "Record requests or updates" %}</p>
                    <p><strong>{% trans "General:" %}</strong> {% trans "Hospital information or services" %}</p>
                </div>
            </div>

            <div class="section-card">
                <div class="section-header">
                    <div class="section-icon bg-purple-500/10">
                        <i data-lucide="headphones" class="w-5 h-5 text-purple-600"></i>
                    </div>
                    <h5 class="text-lg font-semibold text-gray-800">{% trans "Call Center Note" %}</h5>
                </div>
                <div class="p-6 text-sm text-slate-600">
                    {% trans "This inquiry will be logged as received via Call Center. A call center interaction record will be automatically created for tracking purposes." %}
                </div>
            </div>

            <div class="section-card">
                <div class="section-header">
                    <div class="section-icon bg-green-500/10">
                        <i data-lucide="lightbulb" class="w-5 h-5 text-green-600"></i>
                    </div>
                    <h5 class="text-lg font-semibold text-gray-800">{% trans "Tips" %}</h5>
                </div>
                <div class="p-6 text-sm text-slate-600 space-y-1">
                    <p>{% trans "Be clear and concise in the subject line" %}</p>
                    <p>{% trans "Include all relevant details in the message" %}</p>
                    <p>{% trans "Verify contact information for follow-up" %}</p>
                    <p>{% trans "Select the most appropriate category" %}</p>
                </div>
            </div>

            <div class="flex flex-col gap-3">
                <button type="submit" class="w-full px-6 py-3 bg-navy text-white rounded-xl font-bold hover:bg-navy/90 transition text-sm inline-flex items-center justify-center gap-2">
                    <i data-lucide="check-circle" class="w-4 h-4"></i>{% trans "Create Inquiry" %}
                </button>
                <a href="{% url 'callcenter:inquiry_list' %}" class="w-full px-6 py-3 border-2 border-slate-200 rounded-xl font-semibold text-slate-600 hover:bg-slate-50 transition text-sm text-center">
                    {% trans "Cancel" %}
                </a>
            </div>
        </div>
    </div>
</form>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const departmentSelect = document.getElementById('departmentSelect');
    const patientSearch = document.getElementById('patientSearch');
    const searchBtn = document.getElementById('searchBtn');
    const patientResults = document.getElementById('patientResults');
    const patientIdInput = document.getElementById('patientId');
    const contactNameInput = document.getElementById('contactName');
    const contactPhoneInput = document.getElementById('contactPhone');
    const contactEmailInput = document.getElementById('contactEmail');

    const currentHospitalId = '{{ current_hospital.id|default:"" }}';

    if (currentHospitalId) {
        fetch(`/callcenter/ajax/departments/?hospital_id=${currentHospitalId}`)
            .then(response => response.json())
            .then(data => {
                departmentSelect.innerHTML = '<option value="">{% trans "Select department..." %}</option>';
                data.departments.forEach(dept => {
                    const option = document.createElement('option');
                    option.value = dept.id;
                    option.textContent = dept.name_ar || dept.name;
                    departmentSelect.appendChild(option);
                });
            })
            .catch(error => console.error('Error loading departments:', error));
    }

    function searchPatients() {
        const query = patientSearch.value.trim();
        const hospitalId = currentHospitalId;

        if (query.length < 2) {
            patientResults.innerHTML = '<div class="bg-amber-50 border border-amber-200 rounded-lg p-2 text-xs text-amber-700">{% trans "Please enter at least 2 characters to search" %}</div>';
            return;
        }

        patientResults.innerHTML = '<div class="text-center text-sm text-slate-500 py-2">{% trans "Searching..." %}</div>';

        let url = `/callcenter/ajax/patients/?q=${encodeURIComponent(query)}`;
        if (hospitalId) {
            url += `&hospital_id=${hospitalId}`;
        }

        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.patients.length === 0) {
                    patientResults.innerHTML = '<div class="bg-blue-50 border border-blue-200 rounded-lg p-2 text-xs text-blue-700">{% trans "No patients found. Please enter contact details manually." %}</div>';
                    return;
                }

                let html = '<div class="mb-2 text-sm font-semibold text-slate-700">{% trans "Select Patient:" %}</div>';
                data.patients.forEach(patient => {
                    html += `
                        <div class="patient-search-result" data-patient-id="${patient.id}"
                             data-patient-name="${patient.name}" data-patient-phone="${patient.phone}"
                             data-patient-email="${patient.email || ''}">
                            <div class="flex justify-between items-center">
                                <div>
                                    <strong class="text-slate-800">${patient.name}</strong><br>
                                    <small class="text-slate-500">
                                        MRN: ${patient.mrn} |
                                        Phone: ${patient.phone || 'N/A'} |
                                        ID: ${patient.national_id_masked || 'N/A'}
                                    </small>
                                </div>
                                <i data-lucide="check-circle" class="w-5 h-5 text-green-500 hidden"></i>
                            </div>
                        </div>
                    `;
                });
                patientResults.innerHTML = html;
                lucide.createIcons();

                document.querySelectorAll('.patient-search-result').forEach(result => {
                    result.addEventListener('click', function() {
                        document.querySelectorAll('.patient-search-result').forEach(r => {
                            r.classList.remove('selected');
                            const icon = r.querySelector('[data-lucide="check-circle"]');
                            if (icon) icon.classList.add('hidden');
                        });

                        this.classList.add('selected');
                        const icon = this.querySelector('[data-lucide="check-circle"]');
                        if (icon) icon.classList.remove('hidden');

                        patientIdInput.value = this.dataset.patientId;
                        contactNameInput.value = this.dataset.patientName;
                        contactPhoneInput.value = this.dataset.patientPhone;
                        contactEmailInput.value = this.dataset.patientEmail;
                    });
                });
            })
            .catch(error => {
                console.error('Error searching patients:', error);
                patientResults.innerHTML = '<div class="bg-red-50 border border-red-200 rounded-lg p-2 text-xs text-red-700">{% trans "Error searching patients. Please try again." %}</div>';
            });
    }

    searchBtn.addEventListener('click', searchPatients);
    patientSearch.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            searchPatients();
        }
    });

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