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

{% block title %}{% trans "Patients" %} - 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;
    }
    .stat-card {
        background: white;
        border-radius: 1rem;
        border: 2px solid #e2e8f0;
        padding: 1.5rem;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        transition: all 0.3s ease;
    }
    .stat-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        border-color: #005696;
    }
    .filter-card {
        background: white;
        border-radius: 1rem;
        border: 2px solid #e2e8f0;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        overflow: hidden;
        margin-bottom: 1.5rem;
        transition: all 0.3s ease;
    }
    .filter-card:hover {
        border-color: #005696;
    }
    .table-row-hover {
        transition: all 0.2s ease;
        border-left: 3px solid transparent;
    }
    .table-row-hover:hover {
        background: #f8fafc;
        border-left-color: #007bbd;
    }
    .status-badge {
        display: inline-flex;
        align-items: center;
        padding: 0.375rem 0.75rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }
    .field-label {
        font-size: 10px;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #64748b;
    }
    .tab-link {
        padding: 0.5rem 1rem;
        border-radius: 0.5rem;
        font-size: 0.75rem;
        font-weight: 600;
        transition: all 0.2s;
    }
    .tab-link.active {
        background: #005696;
        color: white;
    }
    .tab-link:not(.active) {
        color: #64748b;
    }
    .tab-link:not(.active):hover {
        background: #e2e8f0;
        color: #005696;
    }
    .his-filter-pill {
        padding: 0.25rem 0.75rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 600;
        border: 1.5px solid #e2e8f0;
        background: white;
        color: #64748b;
        cursor: pointer;
        transition: all 0.2s;
    }
    .his-filter-pill:hover {
        border-color: #005696;
        color: #005696;
    }
    .his-filter-pill.active {
        background: #005696;
        color: white;
        border-color: #005696;
    }
</style>
{% endblock %}

{% block content %}
{% csrf_token %}
<div class="p-6">
    <div class="page-header-gradient">
        <div class="flex justify-between items-center">
            <div>
                <h1 class="text-2xl font-bold mb-1">{% trans "Patients" %}</h1>
                <p class="text-blue-100 text-sm">{% trans "Manage patient records and information" %}</p>
            </div>
            <div class="flex items-center gap-3">
                <button onclick="openHisSearchModal()" 
                   class="inline-flex items-center px-4 py-2.5 bg-white/10 text-white font-medium rounded-xl hover:bg-white/20 transition border border-white/20">
                    <i data-lucide="search" class="w-4 h-4 me-2"></i>{% trans "Search HIS" %}
                </button>
                <a href="?export=csv{% for key, value in filters.items %}{% if key != 'export' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" 
                   class="inline-flex items-center px-4 py-2.5 bg-white/10 text-white font-medium rounded-xl hover:bg-white/20 transition border border-white/20">
                    <i data-lucide="download" class="w-4 h-4 me-2"></i>{% trans "Export CSV" %}
                </a>
                {% if request.user.is_px_admin or request.user.is_hospital_admin %}
                <a href="{% url 'organizations:patient_create' %}" 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="plus" class="w-4 h-4 me-2"></i>{% trans "Add Patient" %}
                </a>
                {% endif %}
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="stat-card">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-12 h-12 bg-navy/10 rounded-xl flex items-center justify-center">
                        <i data-lucide="users" class="w-6 h-6 text-navy"></i>
                    </div>
                </div>
                <div class="ml-3">
                    <h6 class="text-slate-500 text-xs font-medium mb-1">{% trans "Total Patients" %}</h6>
                    <h2 class="text-2xl font-bold text-gray-800">{{ stats.total|default:0 }}</h2>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-12 h-12 bg-green-500/10 rounded-xl flex items-center justify-center">
                        <i data-lucide="user-check" class="w-6 h-6 text-green-600"></i>
                    </div>
                </div>
                <div class="ml-3">
                    <h6 class="text-slate-500 text-xs font-medium mb-1">{% trans "Active" %}</h6>
                    <h2 class="text-2xl font-bold text-gray-800">{{ stats.active|default:0 }}</h2>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-12 h-12 bg-blue-500/10 rounded-xl flex items-center justify-center">
                        <i data-lucide="building-2" class="w-6 h-6 text-blue"></i>
                    </div>
                </div>
                <div class="ml-3">
                    <h6 class="text-slate-500 text-xs font-medium mb-1">{% trans "Hospitals" %}</h6>
                    <h2 class="text-2xl font-bold text-gray-800">{{ stats.hospitals|default:0 }}</h2>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-12 h-12 bg-purple-500/10 rounded-xl flex items-center justify-center">
                        <i data-lucide="activity" class="w-6 h-6 text-purple-600"></i>
                    </div>
                </div>
                <div class="ml-3">
                    <h6 class="text-slate-500 text-xs font-medium mb-1">{% trans "Encounters" %}</h6>
                    <h2 class="text-2xl font-bold text-gray-800">{{ stats.visits|default:0 }}</h2>
                </div>
            </div>
        </div>
    </div>

    <div class="filter-card">
        <div class="p-5">
            <form method="get" class="grid grid-cols-1 md:grid-cols-5 gap-4" hx-boost="true" hx-target="body">
                <div>
                    <label class="field-label">{% trans "Search" %}</label>
                    <div class="relative">
                        <i data-lucide="search" class="w-4 h-4 text-slate absolute left-3 top-1/2 -translate-y-1/2"></i>
                        <input type="text" name="search" value="{{ filters.search|default:'' }}" 
                               class="w-full pl-10 pr-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition" 
                               placeholder="{% trans 'Name, MRN, SSN, Phone...' %}">
                    </div>
                </div>
                <div>
                    <label class="field-label">{% trans "Status" %}</label>
                    <select name="status" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition">
                        <option value="">{% trans "All Statuses" %}</option>
                        <option value="active" {% if filters.status == 'active' %}selected{% endif %}>{% trans "Active" %}</option>
                        <option value="inactive" {% if filters.status == 'inactive' %}selected{% endif %}>{% trans "Inactive" %}</option>
                    </select>
                </div>
                <div>
                    <label class="field-label">{% trans "Gender" %}</label>
                    <select name="gender" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition">
                        <option value="">{% trans "All" %}</option>
                        <option value="male" {% if filters.gender == 'male' %}selected{% endif %}>{% trans "Male" %}</option>
                        <option value="female" {% if filters.gender == 'female' %}selected{% endif %}>{% trans "Female" %}</option>
                    </select>
                </div>
                <div>
                    <label class="field-label">{% trans "Nationality" %}</label>
                    <select name="nationality" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition">
                        <option value="">{% trans "All" %}</option>
                        {% for n in nationalities %}
                        <option value="{{ n }}" {% if filters.nationality == n %}selected{% endif %}>{{ n }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="flex items-end gap-2">
                    <button type="submit" class="flex-1 px-4 py-2.5 border border-slate-200 text-slate rounded-xl font-semibold hover:bg-slate-50 hover:border-slate-300 transition flex items-center justify-center gap-2">
                        <i data-lucide="filter" class="w-4 h-4"></i>
                        {% trans "Filter" %}
                    </button>
                    <a href="{% url 'organizations:patient_list' %}" class="px-3 py-2.5 border border-slate-200 text-slate rounded-xl hover:bg-red-50 hover:border-red-200 hover:text-red-600 transition flex items-center justify-center" title="{% trans 'Clear filters' %}">
                        <i data-lucide="x" class="w-4 h-4"></i>
                    </a>
                </div>
            </form>
        </div>
    </div>

    <div class="section-card">
        <div class="section-header">
            <div class="section-icon bg-navy/10">
                <i data-lucide="users" class="w-5 h-5 text-navy"></i>
            </div>
            <h5 class="text-lg font-semibold text-gray-800">{% trans "Patient List" %}</h5>
            <span class="ml-auto text-xs font-bold text-navy bg-navy/10 px-2.5 py-1 rounded-lg">{{ page_obj.paginator.count }}</span>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-slate-50 border-b border-slate-200">
                    <tr>
                        <th class="px-5 py-4 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">{% trans "Patient" %}</th>
                        <th class="px-4 py-4 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">{% trans "MRN" %}</th>
                        <th class="px-4 py-4 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">{% trans "National ID" %}</th>
                        <th class="px-4 py-4 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">{% trans "Contact" %}</th>
                        <th class="px-4 py-4 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">{% trans "Nationality" %}</th>
                        <th class="px-4 py-4 text-center text-xs font-bold text-gray-500 uppercase tracking-wider">{% trans "Status" %}</th>
                        <th class="px-4 py-4 text-center text-xs font-bold text-gray-500 uppercase tracking-wider">{% trans "Actions" %}</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    {% for patient in patients %}
                    <tr class="table-row-hover">
                        <td class="px-5 py-4">
                            <a href="{% url 'organizations:patient_detail' patient.pk %}" class="flex items-center gap-3 group">
                                <div class="w-10 h-10 rounded-lg bg-blue/10 flex items-center justify-center group-hover:bg-blue group-hover:text-white transition flex-shrink-0">
                                    <span class="text-blue font-bold text-sm group-hover:text-white transition">{{ patient.first_name|first }}{{ patient.last_name|first }}</span>
                                </div>
                                <div>
                                    <p class="font-bold text-gray-800 group-hover:text-blue transition">{{ patient.get_full_name }}</p>
                                    {% if patient.first_name_ar or patient.last_name_ar %}
                                    <p class="text-xs text-slate" dir="rtl">{{ patient.first_name_ar }} {{ patient.last_name_ar }}</p>
                                    {% endif %}
                                </div>
                            </a>
                        </td>
                        <td class="px-4 py-4">
                            <span class="font-mono text-sm font-medium text-navy bg-slate-50 px-2 py-1 rounded">{{ patient.mrn }}</span>
                        </td>
                        <td class="px-4 py-4">
                            {% if patient.national_id %}
                            <span class="font-mono text-sm text-navy">{{ patient.national_id }}</span>
                            {% else %}
                            <span class="font-mono text-sm text-slate">-</span>
                            {% endif %}
                        </td>
                        <td class="px-4 py-4">
                            {% if patient.phone %}
                            <div class="flex items-center gap-2 text-sm mb-1">
                                <i data-lucide="phone" class="w-3.5 h-3.5 text-slate"></i>
                                <span class="text-slate">{{ patient.phone }}</span>
                            </div>
                            {% endif %}
                            {% if patient.email %}
                            <div class="flex items-center gap-2 text-sm">
                                <i data-lucide="mail" class="w-3.5 h-3.5 text-slate"></i>
                                <span class="text-slate truncate max-w-[150px]">{{ patient.email }}</span>
                            </div>
                            {% endif %}
                        </td>
                        <td class="px-4 py-4">
                            <span class="text-sm text-slate">{{ patient.nationality|default:"-" }}</span>
                        </td>
                        <td class="px-4 py-4 text-center">
                            <span class="status-badge {% if patient.status == 'active' %}bg-green-100 text-green-700{% else %}bg-slate-100 text-slate-700{% endif %}">
                                {{ patient.get_status_display }}
                            </span>
                        </td>
                        <td class="px-4 py-4">
                            <div class="flex items-center justify-center gap-1">
                                <a href="{% url 'organizations:patient_detail' patient.pk %}" 
                                   class="w-8 h-8 flex items-center justify-center rounded-lg bg-blue/10 text-blue hover:bg-blue hover:text-white transition" 
                                   title="{% trans 'View' %}" onclick="event.stopPropagation()">
                                    <i data-lucide="eye" class="w-4 h-4"></i>
                                </a>
                                {% if request.user.is_px_admin or request.user.is_hospital_admin %}
                                <a href="{% url 'organizations:patient_update' patient.pk %}" 
                                   class="w-8 h-8 flex items-center justify-center rounded-lg bg-slate-100 text-slate hover:bg-navy hover:text-white transition" 
                                   title="{% trans 'Edit' %}" onclick="event.stopPropagation()">
                                    <i data-lucide="edit" class="w-4 h-4"></i>
                                </a>
                                {% endif %}
                            </div>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="8" class="px-6 py-12 text-center">
                            <div class="flex flex-col items-center justify-center">
                                <div class="w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mb-4">
                                    <i data-lucide="users" class="w-8 h-8 text-slate-300"></i>
                                </div>
                                <p class="text-slate font-medium mb-2">{% trans "No patients found" %}</p>
                                <p class="text-slate text-sm mb-4">{% trans "Try adjusting your filters or add a new patient" %}</p>
                                {% if request.user.is_px_admin or request.user.is_hospital_admin %}
                                <a href="{% url 'organizations:patient_create' %}" 
                                   class="inline-flex items-center px-4 py-2 bg-navy text-white font-medium rounded-lg hover:bg-blue transition">
                                    <i data-lucide="plus" class="w-4 h-4 me-2"></i>{% trans "Add First Patient" %}
                                </a>
                                {% endif %}
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        
        {% if page_obj.has_other_pages %}
        <div class="bg-slate-50 px-6 py-4 flex items-center justify-between border-t border-slate-100">
            <div class="flex items-center gap-4">
                <span class="text-xs text-slate font-medium">
                    {% trans "Showing" %} <span class="font-bold text-navy">{{ page_obj.start_index }}-{{ page_obj.end_index }}</span> {% trans "of" %} <span class="font-bold text-navy">{{ page_obj.paginator.count }}</span>
                </span>
                <form method="get" class="flex items-center gap-2" id="pageSizeForm">
                    {% for key, value in request.GET.items %}
                        {% if key != 'page_size' and key != 'page' %}
                        <input type="hidden" name="{{ key }}" value="{{ value }}">
                        {% endif %}
                    {% endfor %}
                    <label class="text-xs text-slate font-semibold uppercase">{% trans "Show" %}</label>
                    <select name="page_size" onchange="document.getElementById('pageSizeForm').submit()" class="px-2 py-1 bg-white border border-slate-200 rounded-lg text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-navy">
                        <option value="10" {% if page_obj.paginator.per_page == 10 %}selected{% endif %}>10</option>
                        <option value="25" {% if page_obj.paginator.per_page == 25 %}selected{% endif %}>25</option>
                        <option value="50" {% if page_obj.paginator.per_page == 50 %}selected{% endif %}>50</option>
                        <option value="100" {% if page_obj.paginator.per_page == 100 %}selected{% endif %}>100</option>
                    </select>
                </form>
            </div>
            <div class="flex gap-2">
                {% if page_obj.has_previous %}
                <a href="?page={{ page_obj.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" 
                   class="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 bg-white hover:bg-slate-50 transition">
                    <i data-lucide="chevron-left" class="w-4 h-4 text-slate"></i>
                </a>
                {% else %}
                <span class="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 bg-slate-100 text-slate-300 cursor-not-allowed">
                    <i data-lucide="chevron-left" class="w-4 h-4"></i>
                </span>
                {% endif %}
                
                {% for num in page_obj.paginator.page_range %}
                    {% if num == page_obj.number %}
                    <span class="w-8 h-8 flex items-center justify-center rounded-lg bg-navy text-white text-xs font-bold">{{ num }}</span>
                    {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                    <a href="?page={{ num }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" 
                       class="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 bg-white hover:bg-slate-50 text-xs font-bold text-slate transition">
                        {{ num }}
                    </a>
                    {% elif num == 1 or num == page_obj.paginator.num_pages %}
                    <a href="?page={{ num }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" 
                       class="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 bg-white hover:bg-slate-50 text-xs font-bold text-slate transition">
                        {{ num }}
                    </a>
                    {% elif num == page_obj.number|add:'-3' or num == page_obj.number|add:'3' %}
                    <span class="w-8 h-8 flex items-center justify-center text-xs text-slate">...</span>
                    {% endif %}
                {% endfor %}
                
                {% if page_obj.has_next %}
                <a href="?page={{ page_obj.next_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" 
                   class="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 bg-white hover:bg-slate-50 transition">
                    <i data-lucide="chevron-right" class="w-4 h-4 text-slate"></i>
                </a>
                {% else %}
                <span class="w-8 h-8 flex items-center justify-center rounded-lg border border-slate-200 bg-slate-100 text-slate-300 cursor-not-allowed">
                    <i data-lucide="chevron-right" class="w-4 h-4"></i>
                </span>
                {% endif %}
            </div>
        </div>
        {% endif %}
    </div>
</div>

<!-- HIS Search Modal -->
<div id="hisSearchModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closeHisSearchModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4 pointer-events-none">
        <div class="bg-white rounded-2xl shadow-2xl w-full max-w-5xl max-h-[85vh] flex flex-col pointer-events-auto">
            <!-- Modal Header -->
            <div class="flex items-center justify-between p-6 border-b border-slate-200">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-navy/10 rounded-xl flex items-center justify-center">
                        <i data-lucide="search" class="w-5 h-5 text-navy"></i>
                    </div>
                    <div>
                        <h2 class="text-lg font-bold text-gray-800">{% trans "Search HIS" %}</h2>
                        <p class="text-xs text-slate">{% trans "Search for patients in the Hospital Information System" %}</p>
                    </div>
                </div>
                <button onclick="closeHisSearchModal()" class="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-slate-100 transition">
                    <i data-lucide="x" class="w-5 h-5 text-slate"></i>
                </button>
            </div>

            <!-- Search Form -->
            <div class="p-6 border-b border-slate-100">
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="field-label">{% trans "National ID (SSN)" %}</label>
                        <input type="text" id="hisSearchSSN" placeholder="e.g. 1220796831" 
                               class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition font-mono">
                    </div>
                    <div>
                        <label class="field-label">{% trans "Mobile Number" %}</label>
                        <input type="text" id="hisSearchMobile" placeholder="e.g. 0530112229"
                               class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition font-mono">
                    </div>
                </div>
                <div class="flex justify-between items-center mt-4">
                    <p class="text-xs text-slate">{% trans "Enter SSN or mobile number to search" %}</p>
                    <button onclick="searchHIS()" id="hisSearchBtn"
                            class="px-6 py-2.5 bg-navy text-white font-medium rounded-xl hover:bg-blue transition flex items-center gap-2 text-sm">
                        <i data-lucide="search" class="w-4 h-4"></i>
                        {% trans "Search" %}
                    </button>
                </div>
            </div>

            <!-- Error/Info Messages -->
            <div id="hisSearchError" class="hidden px-6 pt-4">
                <div class="bg-red-50 border border-red-200 rounded-xl p-4 text-sm text-red-700"></div>
            </div>
            <div id="hisSearchInfo" class="hidden px-6 pt-4">
                <div class="bg-blue-50 border border-blue-200 rounded-xl p-4 text-sm text-blue-700"></div>
            </div>

            <!-- Results -->
            <div class="flex-1 overflow-y-auto p-6">
                <div id="hisSearchLoading" class="hidden flex flex-col items-center py-10">
                    <div class="w-10 h-10 border-4 border-navy/20 border-t-navy rounded-full animate-spin mb-4"></div>
                    <p class="text-sm text-slate">{% trans "Searching HIS..." %}</p>
                </div>

                <div id="hisSearchResults" class="hidden">
                    <div class="flex items-center justify-between mb-4">
                        <div class="flex items-center gap-3">
                            <h3 class="text-sm font-bold text-gray-800">{% trans "Results" %}</h3>
                            <div id="hisTypeFilter" class="hidden flex items-center gap-1.5">
                                <button onclick="filterHisResults('all')" class="his-filter-pill active" data-filter="all">{% trans "All" %}</button>
                                <button onclick="filterHisResults('ED')" class="his-filter-pill" data-filter="ED">ED</button>
                                <button onclick="filterHisResults('IP')" class="his-filter-pill" data-filter="IP">IP</button>
                                <button onclick="filterHisResults('OP')" class="his-filter-pill" data-filter="OP">OP</button>
                            </div>
                        </div>
                        <span id="hisSearchCount" class="text-xs font-bold text-navy bg-navy/10 px-2.5 py-1 rounded-lg"></span>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead class="bg-slate-50 border-b border-slate-200">
                                <tr>
                                    <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase">{% trans "Patient" %}</th>
                                    <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase">{% trans "SSN" %}</th>
                                    <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase">{% trans "Mobile" %}</th>
                                    <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase">{% trans "Nationality" %}</th>
                                    <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase">{% trans "Hospital" %}</th>
                                    <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase">{% trans "Type" %}</th>
                                    <th class="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase">{% trans "Date" %}</th>
                                    <th class="px-4 py-3 text-center text-xs font-bold text-gray-500 uppercase">{% trans "Action" %}</th>
                                </tr>
                            </thead>
                            <tbody id="hisSearchTableBody" class="divide-y divide-gray-100">
                            </tbody>
                        </table>
                    </div>
                </div>

                <div id="hisSearchEmpty" class="hidden flex flex-col items-center py-10">
                    <div class="w-12 h-12 bg-slate-100 rounded-full flex items-center justify-center mb-3">
                        <i data-lucide="user-x" class="w-6 h-6 text-slate-300"></i>
                    </div>
                    <p class="text-slate font-medium mb-1">{% trans "No patients found" %}</p>
                    <p class="text-slate text-sm">{% trans "Try a different SSN or mobile number" %}</p>
                </div>

                <!-- Initial State -->
                <div id="hisSearchInitial" class="flex flex-col items-center py-10">
                    <div class="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mb-4">
                        <i data-lucide="database" class="w-8 h-8 text-slate-300"></i>
                    </div>
                    <p class="text-slate font-medium">{% trans "Enter a National ID or Mobile number to search" %}</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Toast Notification -->
<div id="hisToast" class="fixed bottom-6 right-6 z-50 hidden transform transition-all duration-300 translate-y-4 opacity-0">
    <div id="hisToastContent" class="px-5 py-3 rounded-xl shadow-lg text-sm font-medium flex items-center gap-2"></div>
</div>

{% endblock %}

{% block extra_js %}
<script>
    lucide.createIcons();

    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    function openHisSearchModal() {
        document.getElementById('hisSearchModal').classList.remove('hidden');
        document.getElementById('hisSearchSSN').value = '';
        document.getElementById('hisSearchMobile').value = '';
        resetHisSearchUI();
        document.getElementById('hisSearchSSN').focus();
        document.body.style.overflow = 'hidden';
    lucide.createIcons();

    let hisSearchData = [];
    }

    function closeHisSearchModal() {
        document.getElementById('hisSearchModal').classList.add('hidden');
        document.body.style.overflow = '';
    }

    function resetHisSearchUI() {
        document.getElementById('hisSearchLoading').classList.add('hidden');
        document.getElementById('hisSearchResults').classList.add('hidden');
        document.getElementById('hisSearchEmpty').classList.add('hidden');
        document.getElementById('hisSearchError').classList.add('hidden');
        document.getElementById('hisSearchInfo').classList.add('hidden');
        document.getElementById('hisSearchInitial').classList.remove('hidden');
        document.getElementById('hisSearchBtn').disabled = false;
        document.getElementById('hisSearchTableBody').innerHTML = '';
        document.getElementById('hisTypeFilter').classList.add('hidden');
        hisSearchData = [];
    }

    function showHisError(msg) {
        const el = document.getElementById('hisSearchError');
        el.querySelector('div').textContent = msg;
        el.classList.remove('hidden');
    }

    function showHisInfo(msg) {
        const el = document.getElementById('hisSearchInfo');
        el.querySelector('div').textContent = msg;
        el.classList.remove('hidden');
    }

    function showToast(message, type) {
        const toast = document.getElementById('hisToast');
        const content = document.getElementById('hisToastContent');
        const colors = {
            success: 'bg-green-600 text-white',
            error: 'bg-red-600 text-white',
        };
        content.className = 'px-5 py-3 rounded-xl shadow-lg text-sm font-medium flex items-center gap-2 ' + (colors[type] || colors.success);
        content.textContent = message;
        toast.classList.remove('hidden');
        setTimeout(() => { toast.classList.remove('translate-y-4', 'opacity-0'); }, 10);
        setTimeout(() => {
            toast.classList.add('translate-y-4', 'opacity-0');
            setTimeout(() => { toast.classList.add('hidden'); }, 300);
        }, 3000);
    }

    async function searchHIS() {
        const ssn = document.getElementById('hisSearchSSN').value.trim();
        const mobile = document.getElementById('hisSearchMobile').value.trim();

        if (!ssn && !mobile) {
            showHisError('Please enter a National ID or Mobile number');
            return;
        }

        document.getElementById('hisSearchLoading').classList.remove('hidden');
        document.getElementById('hisSearchInitial').classList.add('hidden');
        document.getElementById('hisSearchResults').classList.add('hidden');
        document.getElementById('hisSearchEmpty').classList.add('hidden');
        document.getElementById('hisSearchError').classList.add('hidden');
        document.getElementById('hisSearchInfo').classList.add('hidden');
        document.getElementById('hisSearchBtn').disabled = true;

        try {
            const response = await fetch('{% url "organizations:search_his_patient" %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken'),
                },
                body: JSON.stringify({ ssn: ssn || null, mobile_no: mobile || null }),
            });

            const data = await response.json();

            document.getElementById('hisSearchLoading').classList.add('hidden');
            document.getElementById('hisSearchBtn').disabled = false;

            if (!response.ok) {
                showHisError(data.error || 'Search failed');
                return;
            }

            if (data.total === 0) {
                document.getElementById('hisSearchEmpty').classList.remove('hidden');
                return;
            }

            document.getElementById('hisSearchCount').textContent = data.total;
            hisSearchData = data.patients;

            const types = [...new Set(data.patients.map(p => p.patient_type).filter(Boolean))];
            const filterEl = document.getElementById('hisTypeFilter');
            if (types.length > 1) {
                filterEl.classList.remove('hidden');
            } else {
                filterEl.classList.add('hidden');
            }
            filterEl.querySelectorAll('.his-filter-pill').forEach(b => b.classList.toggle('active', b.dataset.filter === 'all'));

            renderHisResults(data.patients);

            document.getElementById('hisSearchResults').classList.remove('hidden');

        } catch (err) {
            document.getElementById('hisSearchLoading').classList.add('hidden');
            document.getElementById('hisSearchBtn').disabled = false;
            showHisError('Network error. Please try again.');
        }
    }

    function renderHisResults(patients) {
        const tbody = document.getElementById('hisSearchTableBody');
        tbody.innerHTML = '';

        patients.forEach((p) => {
            const typeClass = p.patient_type ? p.patient_type.toLowerCase() : '';
            const typeBadge = p.patient_type
                ? '<span class="type-badge ' + typeClass + '">' + p.patient_type + '</span>'
                : '-';
            const row = document.createElement('tr');
            row.className = 'border-l-3 border-transparent hover:bg-slate-50 transition';
            row.dataset.type = p.patient_type || '';
            row.innerHTML = `
                <td class="px-4 py-3">
                    <p class="font-semibold text-sm text-gray-800">${p.name || '-'}</p>
                </td>
                <td class="px-4 py-3"><span class="font-mono text-sm text-slate">${p.ssn || '-'}</span></td>
                <td class="px-4 py-3"><span class="font-mono text-sm text-slate">${p.mobile_no || '-'}</span></td>
                <td class="px-4 py-3"><span class="text-sm text-slate">${p.nationality || '-'}</span></td>
                <td class="px-4 py-3"><span class="text-sm text-slate">${p.hospital_name || '-'}</span></td>
                <td class="px-4 py-3">${typeBadge}</td>
                <td class="px-4 py-3 text-sm text-slate">${p.admit_date ? '<span class="block">' + p.admit_date + '</span>' : ''}${p.discharge_date ? '<span class="block text-xs text-slate-400">' + p.discharge_date + '</span>' : (p.dob ? '<span class="block">' + p.dob + '</span>' : (p.admit_date ? '' : '-'))}</td>
                <td class="px-4 py-3 text-center">
                    <button onclick='saveHisPatient(${JSON.stringify(p.raw).replace(/'/g, "&#39;")}, this)'
                            class="px-3 py-1.5 bg-navy text-white text-xs font-bold rounded-lg hover:bg-blue transition">
                        Save
                    </button>
                </td>
            `;
            tbody.appendChild(row);
        });

        document.getElementById('hisSearchCount').textContent = patients.length;
        lucide.createIcons();
    }

    function filterHisResults(type) {
        document.querySelectorAll('#hisTypeFilter .his-filter-pill').forEach(b => {
            b.classList.toggle('active', b.dataset.filter === type);
        });

        const filtered = type === 'all'
            ? hisSearchData
            : hisSearchData.filter(p => p.patient_type === type);

        renderHisResults(filtered);
    }

    async function saveHisPatient(patientData, btn) {
        btn.disabled = true;
        btn.textContent = 'Saving...';

        try {
            const response = await fetch('{% url "organizations:save_his_patient" %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken'),
                },
                body: JSON.stringify({ patient_data: patientData }),
            });

            const data = await response.json();

            if (!response.ok) {
                showToast('Error: ' + (data.error || 'Save failed'), 'error');
                btn.disabled = false;
                btn.textContent = 'Save';
                return;
            }

            showToast('Patient saved: ' + data.patient_name, 'success');
            btn.textContent = 'Saved';
            btn.className = 'px-3 py-1.5 bg-green-600 text-white text-xs font-bold rounded-lg cursor-default';

        } catch (err) {
            showToast('Network error. Please try again.', 'error');
            btn.disabled = false;
            btn.textContent = 'Save';
        }
    }

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') closeHisSearchModal();
    });
</script>
{% endblock %}
