{% extends 'base.html' %}
{% block content %}
<div class="page-toolbar">
  <div>
    <h1 class="h3 mb-1">Clientes</h1>
    <p class="text-muted mb-0">Bienvenido, {{ patient.nombre_completo }}. Desde aquí podés administrar tus turnos y documentación clínica.</p>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <a class="btn btn-outline-primary" href="{{ url_for('booking') }}">Solicitar turno</a>
    <a class="btn btn-outline-secondary" href="{{ url_for('change_password') }}">Cambiar contraseña</a>
  </div>
</div>

<ul class="nav nav-tabs mb-4">
  <li class="nav-item"><a class="nav-link {% if active_tab=='appointments' %}active{% endif %}" href="{{ url_for('client_portal', tab='appointments') }}">Mis turnos</a></li>
  <li class="nav-item"><a class="nav-link {% if active_tab=='clinical' %}active{% endif %}" href="{{ url_for('client_portal', tab='clinical') }}">Historia clínica</a></li>
  <li class="nav-item"><a class="nav-link {% if active_tab=='prescriptions' %}active{% endif %}" href="{{ url_for('client_portal', tab='prescriptions') }}">Recetas</a></li>
  <li class="nav-item"><a class="nav-link {% if active_tab=='profile' %}active{% endif %}" href="{{ url_for('client_portal', tab='profile') }}">Mis datos</a></li>
</ul>

{% if active_tab == 'clinical' %}
<div class="card table-panel"><div class="card-header"><strong>Mi historia clínica</strong></div>
  <div class="table-responsive wide-table"><table class="table align-middle mb-0"><thead><tr><th>Fecha</th><th>Profesional</th><th>Diagnóstico</th><th>Resumen</th></tr></thead><tbody>
    {% for item in clinical_entries %}
    <tr>
      <td>{{ item.entry_datetime.strftime('%d/%m/%Y %H:%M') if item.entry_datetime else '' }}<br><span class="small text-muted">Folio {{ item.folio_number }}</span></td>
      <td>{{ item.professional.display_name if item.professional else '—' }}<br><span class="small text-muted">{{ item.specialty_name or '—' }}</span></td>
      <td>{{ item.diagnosis_text or '—' }}<br><span class="small text-muted">{{ item.cie10_code or '—' }}{% if item.snomed_term %} · {{ item.snomed_term }}{% endif %}</span></td>
      <td><div><strong>Plan:</strong> {{ item.plan or '—' }}</div><div><strong>Tratamiento:</strong> {{ item.treatment or '—' }}</div>{% if item.patient_visible_attachments %}<div class="mt-2"><strong>Adjuntos:</strong><div class="d-flex flex-wrap gap-2 mt-1">{% for att in item.patient_visible_attachments %}<a class="btn btn-sm btn-outline-secondary" href="{{ url_for('static', filename=att.file_path) }}" target="_blank">{{ att.filename }}</a>{% endfor %}</div></div>{% endif %}</td>
    </tr>
    {% else %}
    <tr><td colspan="4" class="text-center text-muted py-4">Todavía no hay evoluciones visibles en tu historia clínica.</td></tr>
    {% endfor %}
  </tbody></table></div>
</div>
{% elif active_tab == 'prescriptions' %}
<div class="card table-panel"><div class="card-header"><strong>Mis recetas</strong></div>
  <div class="table-responsive wide-table"><table class="table align-middle mb-0"><thead><tr><th>Fecha</th><th>Número</th><th>Profesional</th><th>Medicamento / indicación</th><th>Estado</th><th class="text-end">Acciones</th></tr></thead><tbody>
    {% for item in prescriptions %}
    <tr>
      <td>{{ item.prescription_date.strftime('%d/%m/%Y') if item.prescription_date else '' }}</td>
      <td>{{ item.legal_number }}<br><span class="small text-muted">{{ item.cuir }}</span></td>
      <td>{{ item.professional_display_name }}</td>
      <td>{{ item.medication_generic_name }}<br><span class="small text-muted">{{ item.dosage_instructions }}</span></td>
      <td><span class="badge {% if item.computed_status == 'Activa' %}text-bg-success{% else %}text-bg-secondary{% endif %}">{{ item.computed_status }}</span></td>
      <td class="text-end"><div class="d-flex justify-content-end gap-2"><a class="btn btn-sm btn-outline-primary" href="{{ url_for('client_recipe_pdf', recipe_id=item.id) }}" target="_blank">PDF</a><a class="btn btn-sm btn-outline-secondary" href="{{ url_for('public_verify_recipe', q=item.cuir) }}" target="_blank">Verificar</a></div></td>
    </tr>
    {% else %}
    <tr><td colspan="6" class="text-center text-muted py-4">No tenés recetas cargadas.</td></tr>
    {% endfor %}
  </tbody></table></div>
</div>
{% elif active_tab == 'profile' %}
<div class="card table-panel"><div class="card-header"><strong>Mis datos personales</strong></div><div class="card-body">
  <form method="post" class="row g-3 geo-form">
    <input type="hidden" name="action" value="update_profile">
    <input type="hidden" name="return_tab" value="profile">
    <div class="col-md-4"><label class="form-label">Apellido y nombre</label><input class="form-control" value="{{ patient.nombre_completo }}" disabled></div>
    <div class="col-md-4"><label class="form-label">DNI</label><input class="form-control" value="{{ patient.documento }}" disabled></div>
    <div class="col-md-4"><label class="form-label">Fecha nacimiento</label><input class="form-control" value="{{ patient.fecha_nacimiento or '' }}" disabled></div>
    <div class="col-md-6"><label class="form-label">Email</label><input class="form-control" name="email" type="email" value="{{ patient.email or '' }}" required placeholder="correo@dominio.com"></div>
    <div class="col-md-6"><label class="form-label">Teléfono</label><input class="form-control" name="telefono" value="{{ patient.telefono or '' }}" placeholder="Teléfono de contacto"></div>
    <div class="col-md-4"><label class="form-label">CP</label><input class="form-control" name="cp" value="{{ patient.cp or '' }}" placeholder="Código postal"></div>
    <div class="col-md-8"><label class="form-label">Calle</label><input class="form-control" name="calle" value="{{ patient.calle or '' }}" placeholder="Calle y avenida"></div>
    <div class="col-md-3"><label class="form-label">Número</label><input class="form-control" name="numero" value="{{ patient.numero or '' }}" placeholder="Altura"></div>
    <div class="col-md-3"><label class="form-label">Piso</label><input class="form-control" name="piso" value="{{ patient.piso or '' }}" placeholder="Piso / depto"></div>
    <div class="col-md-6"><label class="form-label">Provincia</label>
      <input class="form-control geo-native-input geo-province-input" list="clientProvinceList" value="{{ patient.provincia or '' }}" autocomplete="off">
      <datalist id="clientProvinceList" class="geo-province-list"></datalist>
      <input type="hidden" name="province_name" class="geo-province-name" value="{{ patient.provincia or '' }}">
      <input type="hidden" name="provincia" class="geo-province-id">
    </div>
    <div class="col-md-6"><label class="form-label">Municipio</label>
      <input class="form-control geo-native-input geo-municipality-input" list="clientMunicipalityList" value="{{ patient.municipio or '' }}" autocomplete="off">
      <datalist id="clientMunicipalityList" class="geo-municipality-list"></datalist>
      <input type="hidden" name="municipality_name" class="geo-municipality-name" value="{{ patient.municipio or '' }}">
      <input type="hidden" name="municipio" class="geo-municipality-id">
    </div>
    <div class="col-md-6"><label class="form-label">Localidad</label>
      <input class="form-control geo-native-input geo-city-input" list="clientCityList" value="{{ patient.localidad or '' }}" autocomplete="off">
      <datalist id="clientCityList" class="geo-city-list"></datalist>
      <input type="hidden" name="city_name" class="geo-city-name" value="{{ patient.localidad or '' }}">
      <input type="hidden" name="localidad" class="geo-city-id">
    </div>
    <div class="col-md-6"><label class="form-label">Contacto de emergencia</label><input class="form-control" name="nombre_contacto" value="{{ patient.nombre_contacto or '' }}" placeholder="Nombre de referencia"></div>
    <div class="col-md-6"><label class="form-label">Tel. contacto</label><input class="form-control" name="telefono_contacto" value="{{ patient.telefono_contacto or '' }}" placeholder="Teléfono del contacto"></div>
    <div class="col-12"><label class="form-label">Observaciones</label><textarea class="form-control" name="observaciones" rows="4" placeholder="Indicaciones o datos útiles para el equipo asistencial">{{ patient.observaciones or '' }}</textarea></div>
    <div class="col-12 d-grid"><button class="btn btn-primary" data-confirm="¿Deseás guardar los cambios de tus datos personales?" data-confirm-title="Guardar perfil del cliente">Guardar mis datos</button></div>
  </form>
</div></div>
{% else %}
<div class="card table-panel"><div class="card-header d-flex justify-content-between align-items-center"><strong>Mis turnos</strong><a class="btn btn-sm btn-primary" href="{{ url_for('booking') }}">Solicitar nuevo turno</a></div>
  <div class="table-responsive wide-table"><table class="table align-middle mb-0"><thead><tr><th>Fecha</th><th>Profesional</th><th>Servicio</th><th>Estado</th><th class="text-end">Acciones</th></tr></thead><tbody>
    {% for item in appointments %}
    <tr>
      <td>{{ item.appointment_date.strftime('%d/%m/%Y') if item.appointment_date else '' }} {{ item.start_time.strftime('%H:%M') if item.start_time else '' }}</td>
      <td>{{ item.professional.display_name if item.professional else '—' }}</td>
      <td>{{ item.service.name if item.service else '—' }}</td>
      <td><span class="badge {% if item.status in ['confirmed','completed'] %}text-bg-success{% elif item.status=='pending' %}text-bg-warning{% else %}text-bg-secondary{% endif %}">{{ item.status }}</span></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('manage_booking', token=item.public_token) }}" target="_blank">Gestionar</a>{% if item.status in ['pending','confirmed'] %}<form method="post" action="{{ url_for('client_cancel_appointment', appointment_id=item.id) }}" data-confirm="¿Deseás cancelar este turno?" data-confirm-title="Cancelar turno"><button class="btn btn-sm btn-outline-danger">Cancelar</button></form>{% endif %}</div></td>
    </tr>
    {% else %}
    <tr><td colspan="5" class="text-center text-muted py-4">Todavía no tenés turnos cargados.</td></tr>
    {% endfor %}
  </tbody></table></div>
</div>
{% endif %}
{% endblock %}
