{% extends 'base.html' %}

{% block content %}
<div class="card table-panel">
  <div class="card-body">
    <div class="page-toolbar">
      <div>
        <h2 class="h4 mb-1">Profesionales</h2>
        <p class="text-muted mb-0">
          Gestioná perfiles del equipo, agenda, bloqueos y datos para prescripción.
        </p>
      </div>

      <div class="d-flex gap-2 align-items-center flex-wrap">
        <span class="badge {% if sisa_enabled %}text-bg-success{% else %}text-bg-secondary{% endif %}">
          SISA {% if sisa_enabled %}activo{% else %}desactivado{% endif %}
        </span>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#professionalModal">
          <i class="bi bi-plus-circle"></i> Nuevo profesional
        </button>
      </div>
    </div>

    <div class="table-responsive wide-table">
      <table class="table align-middle mb-0">
        <thead>
          <tr>
            <th>Profesional</th>
            <th>Profesión / Especialidad</th>
            <th>Institución</th><th>Ubicación</th>
            <th>Fuente</th>
            <th>Estado</th>
            <th class="text-end">Acciones</th>
          </tr>
        </thead>
        <tbody>
          {% for prof in profiles %}
          <tr>
            <td>
              {{ prof.display_name }}<br>
              <span class="small text-muted">{{ prof.matricula or 'Sin matrícula' }}</span>
            </td>
            <td>
              {{ prof.profession_name or '—' }}<br>
              <span class="small text-muted">{{ prof.specialty }}</span>
            </td>
            <td>{{ prof.institution.name if prof.institution else '—' }}</td>
            <td class="text-wrap">
              {{ prof.location or '—' }}<br>
              <span class="small text-muted">{{ prof.full_address or 'Sin dirección' }}</span>
            </td>
            <td>
              <span class="badge text-bg-light">{{ prof.source_mode|upper }}</span>
            </td>
            <td>{{ 'Reservable' if prof.is_bookable else 'Oculto' }}</td>
            <td class="text-end">
              <div class="d-flex justify-content-end gap-2 flex-wrap">
                <a class="btn btn-sm btn-outline-primary" href="{{ url_for('admin_professionals', edit=prof.id) }}">Editar</a>
                <a class="btn btn-sm btn-outline-secondary" href="{{ url_for('admin_professional_schedule', professional_id=prof.id) }}">Agenda</a>
                <a class="btn btn-sm btn-outline-warning" href="{{ url_for('admin_professional_leaves', professional_id=prof.id) }}">Bloqueos</a>
                <form method="post" action="{{ url_for('admin_professional_delete', professional_id=prof.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">No hay profesionales cargados.</td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade modal-professional" id="professionalModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <div>
          <h5 class="modal-title">
            {{ 'Editar profesional' if edit_profile else 'Nuevo profesional' }}
          </h5>
          <div class="small text-light opacity-75">
            {% if sisa_enabled %}
              Modo SISA activo: buscá el profesional y luego completá los datos faltantes.
            {% else %}
              Modo manual con especialidades locales y jurisdicción seleccionable.
            {% endif %}
          </div>
        </div>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>

      <form method="post" class="geo-form" id="professionalForm">
        <div class="modal-body">
          {% if sisa_enabled %}
          <div class="section-card mb-4">
            <div class="section-title">Buscar en SISA</div>

            <div class="row g-3 align-items-end" id="sisaSearchBox">
              <div class="col-md-4">
                <label class="form-label">DNI</label>
                <input class="form-control field-placeholder" id="sisaDni" placeholder="30111222">
              </div>
              <div class="col-md-4">
                <label class="form-label">Nombre / Apellido</label>
                <input class="form-control field-placeholder" id="sisaQuery" placeholder="Laura Gómez">
              </div>
              <div class="col-md-4">
                <label class="form-label">Matrícula</label>
                <input class="form-control field-placeholder" id="sisaMatricula" placeholder="MN 123456">
              </div>
              <div class="col-12 d-grid">
                <button class="btn btn-outline-primary" type="button" id="sisaSearchBtn">Buscar en SISA</button>
              </div>
            </div>

            <div id="sisaSearchStatus" class="small text-muted mt-2"></div>
            <div id="sisaSearchResults" class="mt-3 d-flex flex-column gap-2"></div>
          </div>
          {% endif %}

          {% if edit_profile %}
          <input type="hidden" name="professional_id" value="{{ edit_profile.id }}">
          {% endif %}
          {% if current_user.role == 'admin' %}
          <div class="section-card mb-4"><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_profile and edit_profile.institution_id == inst.id %}selected{% endif %}>{{ inst.name }}</option>{% endfor %}</select></div>
          {% endif %}

          <div class="d-flex flex-column gap-4">
            <div class="section-card">
              <div class="section-title">Identificación y operación</div>

              <div class="row g-3">
                <div class="col-md-6">
                  <label class="form-label">Usuario vinculado</label>
                  <select class="form-select searchable-select" name="user_id" data-placeholder="Sin vincular">
                    <option value="">Sin vincular</option>
                    {% for user in users %}
                    <option value="{{ user.id }}" {% if edit_profile and edit_profile.user_id == user.id %}selected{% endif %}>
                      {{ user.full_name }} · {{ user.email }}
                    </option>
                    {% endfor %}
                  </select>
                </div>

                <div class="col-md-3">
                  <label class="form-label">Nombre visible</label>
                  <input class="form-control field-placeholder" id="professional_display_name" name="display_name" value="{{ edit_profile.display_name if edit_profile else '' }}" placeholder="Nombre que verá el paciente" required>
                </div>

                <div class="col-md-3">
                  <label class="form-label">Matrícula</label>
                  <input class="form-control field-placeholder" id="professional_matricula" name="matricula" value="{{ edit_profile.matricula if edit_profile else '' }}" placeholder="MN 123456">
                </div>

                <div class="col-md-3">
                  <label class="form-label">Profesión</label>
                  <input class="form-control field-placeholder" id="professional_profession_name" name="profession_name" value="{{ edit_profile.profession_name if edit_profile else '' }}" placeholder="Profesión">
                </div>

                {% if sisa_enabled %}
                <div class="col-md-3">
                  <label class="form-label">Especialidad</label>
                  <input class="form-control field-placeholder" id="professional_specialty" name="specialty" value="{{ edit_profile.specialty if edit_profile else '' }}" placeholder="Especialidad">
                </div>

                <div class="col-md-3">
                  <label class="form-label">Jurisdicción</label>
                  <input class="form-control field-placeholder" id="professional_jurisdiction_name" name="jurisdiction_name" value="{{ edit_profile.jurisdiction_name if edit_profile else '' }}" placeholder="Jurisdicción">
                </div>
                {% else %}
                <div class="col-md-3">
                  <label class="form-label">Especialidad</label>
                  <select class="form-select searchable-select" name="specialty_id" data-placeholder="Seleccionar especialidad">
                    <option value="">Seleccionar</option>
                    {% for item in specialties %}
                    <option value="{{ item.id }}" {% if edit_profile and edit_profile.specialty_id == item.id %}selected{% endif %}>{{ item.name }}</option>
                    {% endfor %}
                  </select>
                </div>

                <div class="col-md-3">
                  <label class="form-label">Jurisdicción</label>
                  <select class="form-select searchable-select" name="jurisdiction_name" data-placeholder="Seleccionar jurisdicción">
                    <option value="">Seleccionar</option>
                    {% for item in jurisdiction_options %}
                    <option value="{{ item.name }}" {% if edit_profile and edit_profile.jurisdiction_name == item.name %}selected{% endif %}>
                      {{ item.name }}
                    </option>
                    {% endfor %}
                  </select>
                </div>
                {% endif %}

                <div class="col-md-3">
                  <label class="form-label">Estado</label>
                  <input class="form-control field-placeholder" id="professional_state_name" name="state_name" value="{{ edit_profile.state_name if edit_profile else '' }}" placeholder="Activo, vigente, etc.">
                </div>

                <div class="col-md-3 d-flex align-items-end">
                  <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="is_bookable" {% if not edit_profile or edit_profile.is_bookable %}checked{% endif %}>
                    <label class="form-check-label">Permitir reservas</label>
                  </div>
                </div>
              </div>
            </div>

            <div class="row g-4">
              <div class="col-lg-6">
                <div class="section-card h-100">
                  <div class="section-title">Ubicación profesional</div>

                  <div class="row g-3">
                    <div class="col-md-6">
                      <label class="form-label">Ubicación / Sede</label>
                      <input class="form-control field-placeholder" name="location" value="{{ edit_profile.location if edit_profile else '' }}" placeholder="Consultorio, sede o servicio">
                    </div>

                    <div class="col-md-6">
                      <label class="form-label">Color</label>
                      <input class="form-control form-control-color" type="color" name="color" value="{{ edit_profile.color if edit_profile else '#0d6efd' }}">
                    </div>

                    <div class="col-md-6">
                      <label class="form-label">Provincia</label>
                      <input class="form-control geo-native-input geo-province-input" list="professionalProvinceList" value="{{ edit_profile.province if edit_profile else '' }}" placeholder="Escribí y seleccioná provincia" autocomplete="off">
                      <datalist id="professionalProvinceList" class="geo-province-list"></datalist>
                      <input type="hidden" name="province_name" class="geo-province-name" value="{{ edit_profile.province if edit_profile else '' }}">
                      <input type="hidden" name="province" 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="professionalMunicipalityList" value="{{ edit_profile.municipality if edit_profile else '' }}" placeholder="Escribí y seleccioná partido / municipio" autocomplete="off">
                      <datalist id="professionalMunicipalityList" class="geo-municipality-list"></datalist>
                      <input type="hidden" name="municipality_name" class="geo-municipality-name" value="{{ edit_profile.municipality if edit_profile else '' }}">
                      <input type="hidden" name="municipality" 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="professionalCityList" value="{{ edit_profile.city if edit_profile else '' }}" placeholder="Escribí y seleccioná ciudad / localidad" autocomplete="off">
                      <datalist id="professionalCityList" class="geo-city-list"></datalist>
                      <input type="hidden" name="city_name" class="geo-city-name" value="{{ edit_profile.city if edit_profile else '' }}">
                      <input type="hidden" name="city" class="geo-city-id">
                    </div>

                    <div class="col-md-6">
                      <label class="form-label">Dirección</label>
                      <input class="form-control field-placeholder" name="address" value="{{ edit_profile.address if edit_profile else '' }}" placeholder="Calle o avenida">
                    </div>

                    <div class="col-md-6">
                      <label class="form-label">Número</label>
                      <input class="form-control field-placeholder" name="address_number" value="{{ edit_profile.address_number if edit_profile else '' }}" placeholder="123">
                    </div>
                  </div>
                </div>
              </div>

              <div class="col-lg-6">
                <div class="section-card h-100">
                  <div class="section-title">Contacto profesional</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="phone" value="{{ edit_profile.phone if edit_profile else '' }}" placeholder="11 5555-5555">
                    </div>

                    <div class="col-md-6">
                      <label class="form-label">Email de contacto</label>
                      <input class="form-control field-placeholder" name="contact_email" value="{{ edit_profile.contact_email if edit_profile else '' }}" placeholder="profesional@correo.com">
                    </div>

                    <div class="col-12">
                      <label class="form-label">Bio</label>
                      <textarea class="form-control field-placeholder" name="bio" rows="4" placeholder="Resumen profesional, observaciones o notas internas">{{ edit_profile.bio if edit_profile else '' }}</textarea>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-primary">Guardar profesional</button>
        </div>
      </form>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
  {{ super() }}
  {% if edit_profile %}
  <script>
    document.addEventListener('DOMContentLoaded', function () {
      new bootstrap.Modal(document.getElementById('professionalModal')).show();
    });
  </script>
  {% endif %}
{% endblock %}