<!--
  Questo file fa parte di MyTown.
  MyTown è software libero: puoi ridistribuirlo e/o modificarlo secondo
  i termini della GNU Affero General Public License come pubblicata dalla
  Free Software Foundation, versione 3.
  Distribuito senza ALCUNA GARANZIA; vedi la GNU AGPL v3 per i dettagli.
  Copyright (C) Kondor Consulting & Services S.r.l.
  SPDX-License-Identifier: AGPL-3.0-or-later
-->
<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button defaultHref="../../list"></ion-back-button>
    </ion-buttons>
    <ion-title>Dettaglio</ion-title>
  </ion-toolbar>
</ion-header>

@if (appointment) {
  <ion-content>
    <!-- ===== HERO ===== -->
    <div class="detail-hero">
      <div class="hero-wash" [style.background-color]="appointment.service_type_color || getStatusColor(appointment.apt_status)"></div>
      <div class="hero-body">
        <div class="hero-service-row">
          <div class="hero-service-dot" [style.background-color]="appointment.service_type_color || '#6366F1'"></div>
          <h2 class="hero-service-name">{{ appointment.service_type_name }}</h2>
        </div>
        <span class="hero-status-badge" [style.background-color]="getStatusColor(appointment.apt_status)">
          {{ getStatusLabel(appointment.apt_status) }}
        </span>
        <div class="hero-apt-id">#{{ appointment.apt_id }}</div>
      </div>
    </div>
    <!-- ===== BODY ===== -->
    <div class="detail-body">
      <!-- Date section -->
      <div class="detail-section">
        @if (appointment.apt_confirmed_date) {
          <div class="info-row accent-confirmed">
            <div class="ir-icon-wrap">
              <ion-icon name="checkmark-circle-outline"></ion-icon>
            </div>
            <div class="ir-content">
              <span class="ir-label">Data Confermata</span>
              <span class="ir-value">{{ formatDate(appointment.apt_confirmed_date) }} alle {{ formatTime(appointment.apt_confirmed_time) }}</span>
            </div>
          </div>
        }
        @if (appointment.apt_proposed_date) {
          <div class="info-row accent-proposed">
            <div class="ir-icon-wrap">
              <ion-icon name="send-outline"></ion-icon>
            </div>
            <div class="ir-content">
              <span class="ir-label">Data Proposta</span>
              <span class="ir-value">{{ formatDate(appointment.apt_proposed_date) }} alle {{ formatTime(appointment.apt_proposed_time) }}</span>
            </div>
          </div>
        }
        @if (appointment.apt_requested_date) {
          <div class="info-row">
            <div class="ir-icon-wrap">
              <ion-icon name="calendar-outline"></ion-icon>
            </div>
            <div class="ir-content">
              <span class="ir-label">Data Richiesta</span>
              <span class="ir-value">{{ formatDate(appointment.apt_requested_date) }} alle {{ formatTime(appointment.apt_requested_time) }}</span>
            </div>
          </div>
        }
        <div class="info-row">
          <div class="ir-icon-wrap">
            <ion-icon name="hourglass-outline"></ion-icon>
          </div>
          <div class="ir-content">
            <span class="ir-label">Durata</span>
            <span class="ir-value">{{ appointment.apt_duration_minutes }} minuti</span>
          </div>
        </div>
      </div>
      <!-- People section (gestore) -->
      @if (isGestore) {
        <div class="detail-section">
          <h6 class="section-title">Persone</h6>
          <div class="info-row">
            <div class="ir-icon-wrap">
              <ion-icon name="person-outline"></ion-icon>
            </div>
            <div class="ir-content">
              <span class="ir-label">Cliente</span>
              <span class="ir-value">{{ appointment.client_firstname }} {{ appointment.client_lastname }}</span>
              @if (appointment.client_email) {
                <span class="ir-sub">
                  <ion-icon name="mail-outline"></ion-icon>{{ appointment.client_email }}
                </span>
              }
              @if (appointment.client_phone) {
                <span class="ir-sub">
                  <ion-icon name="call-outline"></ion-icon>{{ appointment.client_phone }}
                </span>
              }
            </div>
          </div>
          @if (appointment.operator_firstname) {
            <div class="info-row">
              <div class="ir-icon-wrap">
                <ion-icon name="medkit-outline"></ion-icon>
              </div>
              <div class="ir-content">
                <span class="ir-label">Operatore</span>
                <span class="ir-value">{{ appointment.operator_firstname }} {{ appointment.operator_lastname }}</span>
              </div>
            </div>
          }
        </div>
      }
      <!-- Notes section -->
      @if (appointment.apt_client_notes || appointment.apt_operator_notes || appointment.apt_rejection_reason || appointment.apt_cancellation_reason) {
        <div class="detail-section">
          <h6 class="section-title">Note</h6>
          @if (appointment.apt_client_notes) {
            <div class="note-block">
              <span class="note-tag">Cliente</span>
              <p class="note-text">{{ appointment.apt_client_notes }}</p>
            </div>
          }
          @if (appointment.apt_operator_notes) {
            <div class="note-block">
              <span class="note-tag">Operatore</span>
              <p class="note-text">{{ appointment.apt_operator_notes }}</p>
            </div>
          }
          @if (appointment.apt_rejection_reason) {
            <div class="note-block is-danger">
              <span class="note-tag">Motivo Rifiuto</span>
              <p class="note-text">{{ appointment.apt_rejection_reason }}</p>
            </div>
          }
          @if (appointment.apt_cancellation_reason) {
            <div class="note-block is-danger">
              <span class="note-tag">Motivo Annullamento</span>
              <p class="note-text">{{ appointment.apt_cancellation_reason }}</p>
            </div>
          }
        </div>
      }
      <!-- Preventivo (modalità SU_PREVENTIVO) -->
      @if (appointment.apt_quote_amount != null) {
        <div class="detail-section">
          <h6 class="section-title">Preventivo</h6>
          <div class="info-row accent-confirmed">
            <div class="ir-icon-wrap">
              <ion-icon name="cash-outline"></ion-icon>
            </div>
            <div class="ir-content">
              <span class="ir-label">Importo</span>
              <span class="ir-value">{{ appointment.apt_quote_amount | number: '1.2-2' }} €</span>
            </div>
          </div>
          @if (appointment.apt_quote_valid_until) {
            <div class="info-row">
              <div class="ir-icon-wrap">
                <ion-icon name="time-outline"></ion-icon>
              </div>
              <div class="ir-content">
                <span class="ir-label">Valido fino al</span>
                <span class="ir-value">{{ formatDate(appointment.apt_quote_valid_until) }}</span>
              </div>
            </div>
          }
          @if (appointment.apt_quote_description) {
            <div class="note-block">
              <span class="note-tag">Dettaglio</span>
              <p class="note-text">{{ appointment.apt_quote_description }}</p>
            </div>
          }
        </div>
      }
      <!-- Eventi programmatici / scadenziario -->
      @if (appointment.apt_programmatic_due_date || canSetProgrammatic) {
        <div class="detail-section">
          <h6 class="section-title">Manutenzione ricorrente</h6>
          <!-- Info (visibile a tutti, anche al cliente) -->
          @if (appointment.apt_programmatic_due_date) {
            <div class="info-row">
              <div class="ir-icon-wrap">
                <ion-icon name="notifications-outline"></ion-icon>
              </div>
              <div class="ir-content">
                <span class="ir-label">Prossima scadenza</span>
                <span class="ir-value">{{ formatDate(appointment.apt_programmatic_due_date) }}</span>
              </div>
            </div>
          }
          <!-- Editing (gated dal permesso modulo eventi_programmatici + workflow) -->
          @if (canSetProgrammatic) {
            <ion-list>
              <ion-item>
                <ion-label position="stacked">Prossima scadenza</ion-label>
                <ion-datetime [(ngModel)]="programmaticDueDate" presentation="date" [preferWheel]="false"></ion-datetime>
              </ion-item>
              <ion-item>
                <ion-select label="Ricorrenza" labelPlacement="stacked" [(ngModel)]="programmaticRecurrenceMonths" [disabled]="!programmaticDueDate" interface="popover">
                  @for (opt of recurrenceOptions; track opt) {
                    <ion-select-option [value]="opt.value">{{ opt.label }}</ion-select-option>
                  }
                </ion-select>
              </ion-item>
              <ion-item>
                <ion-input label="Promemoria (giorni prima)" labelPlacement="stacked" type="number" min="0" [(ngModel)]="programmaticLeadDays"></ion-input>
              </ion-item>
            </ion-list>
            <div style="display: flex; gap: 8px; margin-top: 8px;">
              <ion-button size="small" color="primary" (click)="saveProgrammatic()">
                <ion-icon name="save-outline" slot="start"></ion-icon>
                Salva
              </ion-button>
              @if (appointment.apt_programmatic_due_date) {
                <ion-button size="small" color="medium" fill="outline" (click)="clearProgrammatic()">
                  Rimuovi
                </ion-button>
              }
            </div>
            <p class="att-empty">Alla scadenza cliente e azienda ricevono un promemoria. Con la ricorrenza la prossima scadenza è calcolata automaticamente.</p>
          }
        </div>
      }
      <!-- Messages card (gestore) -->
      @if (isGestore && chatEnabled) {
        <div class="messages-card" (click)="goToMessages()">
          <div class="mc-icon">
            <ion-icon name="chatbubbles-outline"></ion-icon>
          </div>
          <div class="mc-body">
            <span class="mc-title">Messaggi</span>
            @if (!appointment.unread_message_count) {
              <span class="mc-sub">Nessun messaggio non letto</span>
            }
            @if (appointment.unread_message_count) {
              <span class="mc-sub mc-unread">{{ appointment.unread_message_count }} nuovi messaggi</span>
            }
          </div>
          <div class="mc-end">
            @if (appointment.unread_message_count) {
              <span class="mc-badge">{{ appointment.unread_message_count }}</span>
            }
            <ion-icon name="chevron-forward" class="mc-arrow"></ion-icon>
          </div>
        </div>
      }
      <!-- Attachments -->
      @if (attachments.length > 0 || isGestore) {
        <div class="detail-section">
          <div class="section-header-row">
            <h6 class="section-title">Allegati</h6>
            <button class="section-add-btn" (click)="addAttachment()">
              <ion-icon name="add-outline"></ion-icon>
              Aggiungi
            </button>
          </div>
          @if (attachments.length === 0) {
            <div class="att-empty">Nessun allegato</div>
          }
          @if (attachments.length > 0) {
            <ion-list lines="none" class="att-list">
              @for (att of attachments; track att) {
                <ion-item-sliding>
                  <ion-item (click)="downloadAttachment(att)" button class="att-item">
                    <div class="att-icon" slot="start">
                      <ion-icon name="document-outline"></ion-icon>
                    </div>
                    <ion-label>
                      <h3>{{ att.att_filename }}</h3>
                      <p>{{ formatFileSize(att.att_size_bytes) }}</p>
                    </ion-label>
                  </ion-item>
                  <ion-item-options side="end">
                    <ion-item-option color="danger" (click)="deleteAttachment(att)">
                      <ion-icon name="trash-outline" slot="icon-only"></ion-icon>
                    </ion-item-option>
                  </ion-item-options>
                </ion-item-sliding>
              }
            </ion-list>
          }
        </div>
      }
      <!-- Status history timeline -->
      @if (appointment.status_history && appointment.status_history.length > 0) {
        <div class="detail-section">
          <h6 class="section-title">Storico</h6>
          <div class="timeline">
            @for (change of appointment.status_history; track change; let last = $last) {
              <div class="tl-item">
                <div class="tl-left">
                  <div class="tl-dot" [style.background-color]="getStatusColor(change.asc_new_status)"></div>
                  @if (!last) {
                    <div class="tl-line"></div>
                  }
                </div>
                <div class="tl-content">
                  <span class="tl-status">{{ getStatusLabel(change.asc_new_status) }}</span>
                  <span class="tl-meta">
                    {{ change.changed_by_firstname }} {{ change.changed_by_lastname }}
                    <span class="tl-dot-sep">·</span>
                    {{ formatDateTime(change.asc_changed_at) }}
                  </span>
                  @if (change.asc_notes) {
                    <span class="tl-notes">{{ change.asc_notes }}</span>
                  }
                </div>
              </div>
            }
          </div>
        </div>
      }
      <!-- Recensione (cliente, appuntamento COMPLETATO): componente condiviso -->
      @if (appointment.apt_status === 'COMPLETATO' && !isGestore && currentUserId === appointment.apt_client_usr_id) {
        <app-review-cta source="APPUNTAMENTO" [sourceId]="appointment.apt_id" prompt="Hai completato questo appuntamento: lascia una recensione verificata all'impresa."></app-review-cta>
      }
      <!-- Spacer for action bar -->
      @if (canProposeDate() || canConfirmDirect() || canAcceptProposal() || canSendQuote() || canAcceptQuote() || canReject() || canRejectQuote() || canCancel()) {
        <div style="height: 100px;"></div>
      }
      <div style="height: 24px;"></div>
    </div>
  </ion-content>
}

<!-- ===== ACTION BAR (sticky bottom) ===== -->
@if (appointment && (canProposeDate() || canConfirmDirect() || canAcceptProposal() || canSendQuote() || canAcceptQuote() || canReject() || canRejectQuote() || canCancel())) {
  <div class="action-bar">
    <div class="action-bar-inner">
      <div class="action-primary">
        @if (canSendQuote()) {
          <ion-button expand="block" color="primary" (click)="openQuoteModal()" class="action-btn">
            <ion-icon name="document-text-outline" slot="start"></ion-icon>
            Invia Preventivo
          </ion-button>
        }
        @if (canAcceptQuote()) {
          <ion-button expand="block" color="success" (click)="acceptQuote()" class="action-btn">
            <ion-icon name="checkmark-circle-outline" slot="start"></ion-icon>
            Accetta Preventivo
          </ion-button>
        }
        @if (canProposeDate()) {
          <ion-button expand="block" color="warning" (click)="openProposeModal()" class="action-btn">
            <ion-icon name="calendar-outline" slot="start"></ion-icon>
            Proponi Data/Ora
          </ion-button>
        }
        @if (canConfirmDirect()) {
          <ion-button expand="block" color="success" (click)="confirmDirect()" class="action-btn">
            <ion-icon name="checkmark-circle-outline" slot="start"></ion-icon>
            Conferma
          </ion-button>
        }
        @if (canAcceptProposal()) {
          <ion-button expand="block" color="success" (click)="acceptProposal()" class="action-btn">
            <ion-icon name="checkmark-circle-outline" slot="start"></ion-icon>
            Accetta Proposta
          </ion-button>
        }
      </div>
      <div class="action-secondary">
        @if (canRejectQuote()) {
          <ion-button expand="block" color="danger" fill="outline" (click)="openRejectQuoteModal()" class="action-btn-sm">
            Rifiuta Preventivo
          </ion-button>
        }
        @if (canReject()) {
          <ion-button expand="block" color="danger" fill="outline" (click)="openRejectModal()" class="action-btn-sm">
            Rifiuta
          </ion-button>
        }
        @if (canCancel()) {
          <ion-button expand="block" color="danger" fill="outline" (click)="openCancelModal()" class="action-btn-sm">
            Annulla
          </ion-button>
        }
      </div>
    </div>
  </div>
}

<!-- ===== MODAL: Proponi Data (slot picker) ===== -->
<ion-modal [isOpen]="showProposeModal" [breakpoints]="[0, 1]" [initialBreakpoint]="1">
  <ng-template>
    <ion-header>
      <ion-toolbar>
        <ion-title>Proponi Data/Ora</ion-title>
        <ion-buttons slot="end">
          <ion-button (click)="showProposeModal = false">Chiudi</ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>
    <ion-content class="ion-padding">
      <!-- Filtro operatore -->
      <ion-list>
        <ion-item>
          <ion-select label="Operatore" labelPlacement="stacked" [(ngModel)]="proposeOperatorEmId" (ionChange)="onProposeOperatorChange()" placeholder="Tutti gli operatori" interface="action-sheet">
            <ion-select-option [value]="null">Tutti gli operatori</ion-select-option>
            @for (op of operators; track op.em_id) {
              <ion-select-option [value]="op.em_id">{{ op.em_lastname }} {{ op.em_firstname }}</ion-select-option>
            }
          </ion-select>
        </ion-item>
      </ion-list>

      <!-- Selettore slot -->
      @if (slotsLoading) {
        <div class="ion-text-center ion-padding">
          <ion-spinner name="bubbles"></ion-spinner>
          <p style="color: var(--ion-color-medium)">Caricamento slot...</p>
        </div>
      }

      @if (!slotsLoading && slotGroups.length === 0) {
        <div class="ion-text-center" style="margin-top: 32px; color: var(--ion-color-medium)">
          <ion-icon name="sad-outline" style="font-size: 48px"></ion-icon>
          <p>Nessuno slot disponibile nelle prossime 2 settimane</p>
        </div>
      }

      @if (!slotsLoading && slotGroups.length > 0) {
        <!-- Giorni -->
        <p style="font-size: 14px; font-weight: 600; margin-bottom: 8px;">Giorno</p>
        <div class="day-chips-scroll">
          @for (group of slotGroups; track group.date) {
            <div
              class="day-chip"
              [class.selected]="selectedDateGroup?.date === group.date"
              (click)="selectDateGroup(group)">
              <span class="day-chip-label">{{ getDayName(group) }}</span>
              <span class="day-chip-date">{{ getDayDate(group) }}</span>
            </div>
          }
        </div>

        <!-- Orari -->
        @if (selectedDateGroup) {
          <p style="font-size: 14px; font-weight: 600; margin: 16px 0 8px;">Ora</p>
          @if (selectedDateGroup.morningSlots.length > 0 && selectedDateGroup.afternoonSlots.length > 0) {
            <div class="period-toggle-row">
              <div class="period-btn" [class.active]="selectedPeriod === 'morning'" (click)="selectPeriod('morning')">
                <ion-icon name="sunny-outline"></ion-icon>
                Mattina
              </div>
              <div class="period-btn" [class.active]="selectedPeriod === 'afternoon'" (click)="selectPeriod('afternoon')">
                <ion-icon name="moon-outline"></ion-icon>
                Pomeriggio
              </div>
            </div>
          }
          <div class="time-chips-scroll">
            @if (selectedDateGroup.morningSlots.length > 0) {
              @for (slot of selectedDateGroup.morningSlots; track slot) {
                <div
                  class="time-chip"
                  [class.selected]="selectedSlot === slot"
                  (click)="selectSlot(slot)">
                  {{ slot.start_time.substring(0, 5) }}
                </div>
              }
            }
            @if (selectedDateGroup.morningSlots.length > 0 && selectedDateGroup.afternoonSlots.length > 0) {
              <div class="time-separator"></div>
            }
            @if (selectedDateGroup.afternoonSlots.length > 0) {
              @for (slot of selectedDateGroup.afternoonSlots; track slot) {
                <div
                  class="time-chip"
                  [class.selected]="selectedSlot === slot"
                  (click)="selectSlot(slot)">
                  {{ slot.start_time.substring(0, 5) }}
                </div>
              }
            }
          </div>
        }
      }

      <!-- Note -->
      <ion-list>
        <ion-item>
          <ion-textarea label="Note" labelPlacement="stacked" [(ngModel)]="proposeNotes" placeholder="Note opzionali..." [autoGrow]="true"></ion-textarea>
        </ion-item>
      </ion-list>
      <ion-button expand="block" color="warning" (click)="submitProposal()" [disabled]="!selectedSlot" style="margin-top: 16px">
        <ion-icon name="send-outline" slot="start"></ion-icon>
        Invia Proposta
      </ion-button>
    </ion-content>
  </ng-template>
</ion-modal>

<!-- ===== MODAL: Rifiuta/Annulla ===== -->
<ion-modal [isOpen]="showRejectModal" [breakpoints]="[0, 1]" [initialBreakpoint]="1">
  <ng-template>
    <ion-header>
      <ion-toolbar>
        <ion-title>{{ rejectAction === 'ANNULLATO' ? 'Annulla Appuntamento' : (rejectAction === 'PREVENTIVO_RIFIUTATO' ? 'Rifiuta Preventivo' : 'Rifiuta Appuntamento') }}</ion-title>
        <ion-buttons slot="end">
          <ion-button (click)="showRejectModal = false">Chiudi</ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>
    <ion-content class="ion-padding">
      <ion-list>
        <ion-item>
          <ion-textarea
            label="Motivo"
            labelPlacement="stacked"
            [(ngModel)]="rejectReason"
            placeholder="Inserisci il motivo..."
            [autoGrow]="true"
            rows="4">
          </ion-textarea>
        </ion-item>
      </ion-list>
      <ion-button expand="block" color="danger" (click)="submitReject()" style="margin-top: 16px">
        <ion-icon [name]="rejectAction === 'ANNULLATO' ? 'ban-outline' : 'close-circle-outline'" slot="start"></ion-icon>
        {{ rejectAction === 'ANNULLATO' ? 'Annulla' : 'Rifiuta' }}
      </ion-button>
    </ion-content>
  </ng-template>
</ion-modal>

<!-- ===== MODAL: Invia Preventivo ===== -->
<ion-modal [isOpen]="showQuoteModal" [breakpoints]="[0, 1]" [initialBreakpoint]="1">
  <ng-template>
    <ion-header>
      <ion-toolbar>
        <ion-title>Invia Preventivo</ion-title>
        <ion-buttons slot="end">
          <ion-button (click)="showQuoteModal = false">Chiudi</ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>
    <ion-content class="ion-padding">
      <ion-list>
        <ion-item>
          <ion-input label="Importo (€)" labelPlacement="stacked" type="number" inputmode="decimal" [(ngModel)]="quoteAmount" placeholder="0.00"></ion-input>
        </ion-item>
        <ion-item>
          <ion-textarea label="Descrizione" labelPlacement="stacked" [(ngModel)]="quoteDescription" placeholder="Dettaglio del preventivo..." [autoGrow]="true" rows="3"></ion-textarea>
        </ion-item>
        <ion-item>
          <ion-label position="stacked">Valido fino al</ion-label>
          <ion-datetime [(ngModel)]="quoteValidUntil" presentation="date" [preferWheel]="false"></ion-datetime>
        </ion-item>
      </ion-list>
      <ion-button expand="block" color="primary" (click)="submitQuote()" [disabled]="!quoteAmount" style="margin-top: 16px">
        <ion-icon name="send-outline" slot="start"></ion-icon>
        Invia Preventivo
      </ion-button>
    </ion-content>
  </ng-template>
</ion-modal>
