{% extends 'base.html' %}
{% block content %}
<div class="card table-panel">
  <div class="card-body">
    <div class="page-toolbar">
      <div><h2 class="h4 mb-1">Pacientes / Clientes</h2><p class="text-muted mb-0">Filtrá arriba y gestioná altas o ediciones desde un modal profesional.</p></div>
      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#patientModal"><i class="bi bi-plus-circle"></i> Nuevo paciente</button>
    </div>
    <form method="get" class="row g-3 align-items-end mb-3 filter-toolbar">
      <div class="col-lg-6"><label class="form-label">Buscar</label><input class="form-control" name="q" placeholder="Nombre, DNI, email u obra social" value="{{ request.args.get('q','') }}"></div>
      <div class="col-lg-3"><label class="form-label">Estado</label><select class="form-select searchable-select" name="estado" data-placeholder="Todos"><option value="">Todos</option><option value="Activo" {% if request.args.get('estado')=='Activo' %}selected{% endif %}>Activo</option><option value="Suspendido" {% if request.args.get('estado')=='Suspendido' %}selected{% endif %}>Suspendido</option></select></div>
      <div class="col-lg-3 d-flex gap-2"><button class="btn btn-outline-primary flex-fill">Filtrar</button><a class="btn btn-outline-secondary" href="{{ url_for('admin_patients') }}">Limpiar</a></div>
    </form>
    <div class="table-responsive wide-table">
      <table class="table align-middle mb-0">
        <thead><tr><th>Paciente</th><th>Institución</th><th>Contacto</th><th>Domicilio</th><th>Obra social</th><th>Estado</th><th class="text-end">Acciones</th></tr></thead>
        <tbody>
        {% for item in patients %}
        <tr>
          <td>{{ item.nombre_completo }}<br><span class="small text-muted">{{ item.tipo_documento }} {{ item.documento }}</span><br><span class="small text-muted">{{ item.fecha_nacimiento or 'Sin fecha nac.' }}</span></td>
          <td>{{ item.institution.name if item.institution else '—' }}</td>
          <td>{{ item.telefono or '—' }}<br><span class="small text-muted">{{ item.email or 'Sin email' }}</span></td>
          <td class="text-wrap" style="min-width:220px">{{ item.domicilio_completo or 'Sin domicilio' }}</td>
          <td>{{ item.obra_social.denominacion if item.obra_social else 'Sin cobertura' }}<br><span class="small text-muted">{{ item.afiliado_nro or 'Sin afiliado' }}</span></td>
          <td><span class="badge {% if item.estado=='Activo' %}text-bg-success{% elif item.estado=='Suspendido' %}text-bg-warning{% else %}text-bg-secondary{% endif %}">{{ item.estado }}</span></td>
          <td class="text-end"><div class="d-flex gap-2 justify-content-end flex-wrap"><a class="btn btn-sm btn-outline-primary" href="{{ url_for('admin_patients', edit=item.id) }}">Editar</a><form method="post" action="{{ url_for('admin_patient_toggle', patient_id=item.id) }}"><button class="btn btn-sm btn-outline-warning">{{ 'Suspender' if item.estado=='Activo' else 'Reactivar' }}</button></form><form method="post" action="{{ url_for('admin_patient_delete', patient_id=item.id) }}" onsubmit="return confirm('¿Eliminar?')"><button class="btn btn-sm btn-outline-danger">Eliminar</button></form></div></td>
        </tr>
        {% else %}<tr><td colspan="6" class="text-center text-muted py-4">Sin resultados.</td></tr>{% endfor %}
        </tbody>
      </table>
    </div>
    {% if pagination.pages > 1 %}
    <div class="pt-3 border-top mt-3"><nav><ul class="pagination mb-0 justify-content-end"><li class="page-item {% if not pagination.has_prev %}disabled{% endif %}"><a class="page-link" href="{{ url_for('admin_patients', page=pagination.prev_num, q=request.args.get('q',''), estado=request.args.get('estado','')) }}">Anterior</a></li>{% for page_num in pagination.iter_pages() %}{% if page_num %}<li class="page-item {% if page_num == pagination.page %}active{% endif %}"><a class="page-link" href="{{ url_for('admin_patients', page=page_num, q=request.args.get('q',''), estado=request.args.get('estado','')) }}">{{ page_num }}</a></li>{% else %}<li class="page-item disabled"><span class="page-link">…</span></li>{% endif %}{% endfor %}<li class="page-item {% if not pagination.has_next %}disabled{% endif %}"><a class="page-link" href="{{ url_for('admin_patients', page=pagination.next_num, q=request.args.get('q',''), estado=request.args.get('estado','')) }}">Siguiente</a></li></ul></nav></div>
    {% endif %}
  </div>
</div>

<div class="modal fade" id="patientModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">{{ 'Editar paciente' if edit_patient else 'Nuevo paciente / cliente' }}</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <form method="post" class="geo-form">
        <div class="modal-body"><div class="row g-4 modal-form-grid">
          {% if edit_patient %}<input type="hidden" name="patient_id" value="{{ edit_patient.id }}">{% endif %}
          {% if current_user.role == 'admin' %}<div class="col-12"><div class="section-card"><div class="section-title">Institución</div><select class="form-select searchable-select" name="institution_id"><option value="">Seleccionar institución</option>{% for inst in institutions %}<option value="{{ inst.id }}" {% if edit_patient and edit_patient.institution_id == inst.id %}selected{% endif %}>{{ inst.name }}</option>{% endfor %}</select></div></div>{% endif %}
          <div class="col-12"><div class="section-card"><div class="section-title">Identificación</div><div class="row g-3"><div class="col-md-4"><label class="form-label">Nombre</label><input class="form-control field-placeholder" name="nombre" value="{{ edit_patient.nombre if edit_patient else '' }}" placeholder="Nombre" required></div><div class="col-md-4"><label class="form-label">Apellido</label><input class="form-control field-placeholder" name="apellido" value="{{ edit_patient.apellido if edit_patient else '' }}" placeholder="Apellido" required></div><div class="col-md-4"><label class="form-label">Tipo doc.</label><input class="form-control field-placeholder" name="tipo_documento" value="{{ edit_patient.tipo_documento if edit_patient else 'DNI' }}" placeholder="DNI"></div><div class="col-md-4"><label class="form-label">Documento</label><input class="form-control field-placeholder" name="documento" value="{{ edit_patient.documento if edit_patient else '' }}" placeholder="30111222" required></div><div class="col-md-4"><label class="form-label">Fecha nac.</label><input class="form-control" type="date" name="fecha_nacimiento" value="{{ edit_patient.fecha_nacimiento if edit_patient else '' }}"></div><div class="col-md-4"><label class="form-label">Género</label><input class="form-control field-placeholder" name="genero" value="{{ edit_patient.genero if edit_patient else '' }}" placeholder="F, M, X, etc."></div></div></div></div>
          <div class="col-lg-6"><div class="section-card h-100"><div class="section-title">Contacto y cobertura</div><div class="row g-3"><div class="col-md-6"><label class="form-label">Teléfono</label><input class="form-control field-placeholder" name="telefono" value="{{ edit_patient.telefono if edit_patient else '' }}" placeholder="11 5555-5555"></div><div class="col-md-6"><label class="form-label">Email</label><input class="form-control field-placeholder" name="email" value="{{ edit_patient.email if edit_patient else '' }}" placeholder="paciente@correo.com" required><div class="form-text">Este email se usa para crear el acceso del cliente. Contraseña provisoria: DNI.</div></div><div class="col-md-8"><label class="form-label">Obra social</label><select class="form-select searchable-select obra-social-select" data-placeholder="Buscar obra social"><option value="">Seleccionar</option>{% for os in obras_sociales %}<option value="{{ os.id }}" data-subtext="RNAS {{ os.rnas }}" {% if edit_patient and edit_patient.obra_social_id == os.id %}selected{% endif %}>{{ os.denominacion }}</option>{% endfor %}</select><input type="hidden" name="obra_social_id" class="obra-social-id" value="{{ edit_patient.obra_social_id if edit_patient else '' }}"></div><div class="col-md-4"><label class="form-label">N° afiliado</label><input class="form-control field-placeholder" name="afiliado_nro" value="{{ edit_patient.afiliado_nro if edit_patient else '' }}" placeholder="N° afiliado"></div><div class="col-md-6"><label class="form-label">Contacto de emergencia</label><input class="form-control field-placeholder" name="nombre_contacto" value="{{ edit_patient.nombre_contacto if edit_patient else '' }}" placeholder="Nombre del contacto"></div><div class="col-md-6"><label class="form-label">Tel. contacto</label><input class="form-control field-placeholder" name="telefono_contacto" value="{{ edit_patient.telefono_contacto if edit_patient else '' }}" placeholder="11 4444-4444"></div><div class="col-md-4"><label class="form-label">Estado</label><select class="form-select searchable-select" name="estado"><option {% if not edit_patient or edit_patient.estado=='Activo' %}selected{% endif %}>Activo</option><option {% if edit_patient and edit_patient.estado=='Suspendido' %}selected{% endif %}>Suspendido</option></select></div></div></div></div>
          <div class="col-lg-6"><div class="section-card h-100"><div class="section-title">Domicilio</div><div class="row g-3"><div class="col-md-4"><label class="form-label">CP</label><input class="form-control field-placeholder" name="cp" value="{{ edit_patient.cp if edit_patient else '' }}" placeholder="1884"></div><div class="col-md-8"><label class="form-label">Calle</label><input class="form-control field-placeholder" name="calle" value="{{ edit_patient.calle if edit_patient else '' }}" placeholder="Calle o avenida"></div><div class="col-md-3"><label class="form-label">Número</label><input class="form-control field-placeholder" name="numero" value="{{ edit_patient.numero if edit_patient else '' }}" placeholder="123"></div><div class="col-md-3"><label class="form-label">Piso</label><input class="form-control field-placeholder" name="piso" value="{{ edit_patient.piso if edit_patient else '' }}" placeholder="2 B"></div><div class="col-md-6"><label class="form-label">Provincia</label><input class="form-control geo-native-input geo-province-input" list="patientProvinceList" value="{{ edit_patient.provincia if edit_patient else '' }}" placeholder="Escribí y seleccioná provincia" autocomplete="off"><datalist id="patientProvinceList" class="geo-province-list"></datalist><input type="hidden" name="province_name" class="geo-province-name" value="{{ edit_patient.provincia if edit_patient else '' }}"><input type="hidden" name="provincia" class="geo-province-id"></div><div class="col-md-6"><label class="form-label">Partido / Municipio</label><input class="form-control geo-native-input geo-municipality-input" list="patientMunicipalityList" value="{{ edit_patient.municipio if edit_patient else '' }}" placeholder="Escribí y seleccioná partido / municipio" autocomplete="off"><datalist id="patientMunicipalityList" class="geo-municipality-list"></datalist><input type="hidden" name="municipality_name" class="geo-municipality-name" value="{{ edit_patient.municipio if edit_patient else '' }}"><input type="hidden" name="municipio" class="geo-municipality-id"></div><div class="col-md-6"><label class="form-label">Ciudad / Localidad</label><input class="form-control geo-native-input geo-city-input" list="patientCityList" value="{{ edit_patient.localidad if edit_patient else '' }}" placeholder="Escribí y seleccioná ciudad / localidad" autocomplete="off"><datalist id="patientCityList" class="geo-city-list"></datalist><input type="hidden" name="city_name" class="geo-city-name" value="{{ edit_patient.localidad if edit_patient else '' }}"><input type="hidden" name="localidad" class="geo-city-id"></div></div></div></div>
          <div class="col-12"><div class="section-card"><div class="section-title">Observaciones</div><textarea class="form-control field-placeholder" name="observaciones" rows="3" placeholder="Notas relevantes del paciente">{{ edit_patient.observaciones if edit_patient else '' }}</textarea></div></div>
        </div>
        <div class="modal-footer"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancelar</button><button class="btn btn-primary">Guardar paciente</button></div>
      </form>
    </div>
  </div>
</div>
{% endblock %}
{% block scripts %}{{ super() }}{% if edit_patient %}<script>document.addEventListener('DOMContentLoaded',function(){ new bootstrap.Modal(document.getElementById('patientModal')).show(); });</script>{% endif %}{% endblock %}
