<!--
  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">
      @if (currentStep > 1) {
        <ion-button (click)="goBack()">
          <ion-icon name="arrow-back-outline" slot="icon-only"></ion-icon>
        </ion-button>
      }
      @if (currentStep === 1) {
        <ion-back-button></ion-back-button>
      }
    </ion-buttons>
    <ion-title>Nuova Richiesta</ion-title>
  </ion-toolbar>
  <!-- Step indicator -->
  <ion-toolbar>
    <div class="step-indicator">
      <div class="step" [class.active]="currentStep >= 1" [class.done]="currentStep > 1">1</div>
      <div class="step-line" [class.active]="currentStep >= 2"></div>
      <div class="step" [class.active]="currentStep >= 2" [class.done]="currentStep > 2">2</div>
      <div class="step-line" [class.active]="currentStep >= 3"></div>
      <div class="step" [class.active]="currentStep >= 3">3</div>
    </div>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">

  <!-- ========== STEP 1: Seleziona Servizi (multi) ========== -->
  @if (currentStep === 1) {
    <div>
      <h5 style="margin-bottom: 4px; font-weight: 600">Seleziona i servizi</h5>
      <p style="font-size: 13px; color: var(--ion-color-medium); margin-bottom: 12px;">Puoi scegliere più servizi: la durata verrà sommata.</p>
      @for (group of groupedServiceTypes; track group) {
        <div>
          @if (groupedServiceTypes.length > 1) {
            <div style="padding: 8px 4px 4px; font-size: 14px; font-weight: 600;">
              {{ group.category_name }}
            </div>
          }
          @for (st of group.services; track st) {
            <ion-card
              button
              (click)="toggleServiceType(st)"
              [class.service-card-selected]="isServiceTypeSelected(st)"
              >
              <ion-card-content>
                <div style="display: flex; align-items: center; gap: 12px">
                  <div
                    style="width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; flex-shrink: 0"
                    [style.background-color]="st.st_color || '#6366F1'"
                    >
                    <ion-icon name="calendar-outline" style="color: white; font-size: 20px"></ion-icon>
                  </div>
                  <div style="flex: 1">
                    <strong>{{ st.st_name }}</strong>
                    @if (st.st_description) {
                      <p style="margin: 2px 0 0; font-size: 13px; color: var(--ion-color-medium)">{{ st.st_description }}</p>
                    }
                    <div style="display: flex; gap: 8px; margin-top: 4px">
                      <ion-badge color="light" style="font-size: 11px">{{ st.st_duration_minutes }} min</ion-badge>
                      @if (st.st_requires_attachments) {
                        <ion-badge color="warning" style="font-size: 11px">Foto richieste</ion-badge>
                      }
                    </div>
                  </div>
                  <ion-icon
                    [name]="isServiceTypeSelected(st) ? 'checkmark-circle' : 'ellipse-outline'"
                    [color]="isServiceTypeSelected(st) ? 'primary' : 'light'"
                    style="font-size: 24px; flex-shrink: 0"
                  ></ion-icon>
                </div>
              </ion-card-content>
            </ion-card>
          }
        </div>
      }
      @if (serviceTypes.length === 0) {
        <div class="ion-text-center" style="margin-top: 40px; color: var(--ion-color-medium)">
          <ion-icon name="pricetags-outline" style="font-size: 48px"></ion-icon>
          <p>Nessun tipo di servizio disponibile</p>
        </div>
      }
    </div>
  }

  <!-- ========== STEP 2: Prenotazione ========== -->
  @if (currentStep === 2 && primaryServiceType) {
    <div>
      <!-- Riepilogo servizi selezionati -->
      <div style="margin-bottom: 16px; background: var(--ion-color-light); border-radius: 10px; padding: 10px 14px;">
        @if (companyName) {
          <strong style="font-size: 15px; display: block; margin-bottom: 2px;">{{ companyName }}</strong>
        }
        @for (st of selectedServiceTypes; track st) {
          <div style="font-size: 13px; color: var(--ion-color-medium);">
            · {{ st.st_name }} ({{ st.st_duration_minutes }} min)
          </div>
        }
        <div style="margin-top: 4px; font-size: 13px; font-weight: 600; color: var(--ion-color-primary)">
          Totale: {{ totalDurationMinutes }} min
        </div>
      </div>
      <!-- SLOT_FISSO -->
      @if (primaryServiceType.st_mode === 'SLOT_FISSO') {
        <div>
          @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: 40px; 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) {
            <div>
              <!-- 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) {
                  <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) {
                <div>
                  <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" #timeChipsScroll (scroll)="onTimeScroll()">
                    @if (selectedDateGroup.morningSlots.length > 0) {
                      <div #morningAnchor></div>
                      @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) {
                      <div #afternoonAnchor></div>
                      @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>
                </div>
              }
              <ion-button expand="block" style="margin-top: 20px;" [disabled]="!selectedSlot" (click)="confirmSlotSelection()">
                Continua
              </ion-button>
            </div>
          }
        </div>
      }
      <!-- SU_RICHIESTA -->
      @if (primaryServiceType.st_mode === 'SU_RICHIESTA') {
        <div>
          <h5 style="margin-bottom: 12px; font-weight: 600">Indica le tue preferenze</h5>
          <ion-list>
            <ion-item>
              <ion-label position="stacked">Data preferita *</ion-label>
              <ion-datetime [(ngModel)]="preferredDate" presentation="date" [preferWheel]="false" [min]="minDate"></ion-datetime>
            </ion-item>
            <ion-item>
              <ion-label position="stacked">Ora preferita *</ion-label>
              <ion-datetime [(ngModel)]="preferredTime" presentation="time" hourCycle="h23" [preferWheel]="true"></ion-datetime>
            </ion-item>
            <ion-item>
              <ion-textarea
                label="Descrizione del problema"
                labelPlacement="stacked"
                [(ngModel)]="problemDescription"
                placeholder="Descrivi il motivo della richiesta..."
                [autoGrow]="true"
                rows="3"
              ></ion-textarea>
            </ion-item>
          </ion-list>
          <!-- Allegati -->
          <div style="margin-top: 12px">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px">
              <span style="font-size: 14px; font-weight: 500">
                Allegati
                @if (anyRequiresAttachments) {
                  <span style="color: var(--ion-color-danger)">*</span>
                }
              </span>
              <div style="display: flex; gap: 4px">
                <ion-button size="small" fill="outline" (click)="addPhoto()">
                  <ion-icon name="camera-outline" slot="start"></ion-icon>
                  Foto
                </ion-button>
                <ion-button size="small" fill="outline" (click)="pickFile()">
                  <ion-icon name="document-outline" slot="start"></ion-icon>
                  File
                </ion-button>
              </div>
            </div>
            @for (file of pendingFiles; track file; let i = $index) {
              <ion-chip (click)="removePendingFile(i)">
                <ion-icon name="document-outline"></ion-icon>
                <ion-label>{{ file.name }}</ion-label>
                <ion-icon name="close-circle"></ion-icon>
              </ion-chip>
            }
            @if (anyRequiresAttachments && pendingFiles.length === 0) {
              <p style="font-size: 12px; color: var(--ion-color-danger)">
                Almeno un allegato è obbligatorio
              </p>
            }
          </div>
          <ion-button expand="block" style="margin-top: 16px" (click)="proceedToStep3()" [disabled]="!canProceedStep2()"> Continua </ion-button>
        </div>
      }
      <!-- SU_PREVENTIVO -->
      @if (primaryServiceType.st_mode === 'SU_PREVENTIVO') {
        <div>
          <h5 style="margin-bottom: 12px; font-weight: 600">Descrivi la richiesta di preventivo</h5>
          <ion-list>
            <ion-item>
              <ion-textarea
                label="Descrizione dell'intervento *"
                labelPlacement="stacked"
                [(ngModel)]="problemDescription"
                placeholder="Descrivi l'intervento. Puoi indicare anche servizi non presenti nel listino..."
                [autoGrow]="true"
                rows="4"
              ></ion-textarea>
            </ion-item>
          </ion-list>
          <!-- Allegati -->
          <div style="margin-top: 12px">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px">
              <span style="font-size: 14px; font-weight: 500">
                Allegati
                @if (anyRequiresAttachments) {
                  <span style="color: var(--ion-color-danger)">*</span>
                }
              </span>
              <div style="display: flex; gap: 4px">
                <ion-button size="small" fill="outline" (click)="addPhoto()">
                  <ion-icon name="camera-outline" slot="start"></ion-icon>
                  Foto
                </ion-button>
                <ion-button size="small" fill="outline" (click)="pickFile()">
                  <ion-icon name="document-outline" slot="start"></ion-icon>
                  File
                </ion-button>
              </div>
            </div>
            @for (file of pendingFiles; track file; let i = $index) {
              <ion-chip (click)="removePendingFile(i)">
                <ion-icon name="document-outline"></ion-icon>
                <ion-label>{{ file.name }}</ion-label>
                <ion-icon name="close-circle"></ion-icon>
              </ion-chip>
            }
            @if (anyRequiresAttachments && pendingFiles.length === 0) {
              <p style="font-size: 12px; color: var(--ion-color-danger)">
                Almeno un allegato è obbligatorio
              </p>
            }
          </div>
          <ion-button expand="block" style="margin-top: 16px" (click)="proceedToStep3()" [disabled]="!canProceedStep2()"> Continua </ion-button>
        </div>
      }
    </div>
  }

  <!-- ========== STEP 3: Riepilogo ========== -->
  @if (currentStep === 3 && primaryServiceType) {
    <div>
      <h5 style="margin-bottom: 12px; font-weight: 600">Riepilogo</h5>
      <ion-card>
        <ion-card-content>
          <ion-list lines="none">
            <ion-item>
              <ion-icon name="pricetags-outline" slot="start" color="primary"></ion-icon>
              <ion-label>
                <p>Servizi richiesti</p>
                @for (st of selectedServiceTypes; track st) {
                  <h3>{{ st.st_name }} <small style="color: var(--ion-color-medium)">({{ st.st_duration_minutes }} min)</small></h3>
                }
              </ion-label>
            </ion-item>
            <ion-item>
              <ion-icon name="hourglass-outline" slot="start" color="primary"></ion-icon>
              <ion-label>
                <p>Durata totale</p>
                <h3>{{ totalDurationMinutes }} minuti</h3>
              </ion-label>
            </ion-item>
            @if (primaryServiceType.st_mode !== 'SU_PREVENTIVO') {
              <ion-item>
                <ion-icon name="calendar-outline" slot="start" color="primary"></ion-icon>
                <ion-label>
                  <p>Data</p>
                  <h3>{{ getSummaryDate() }}</h3>
                </ion-label>
              </ion-item>
              <ion-item>
                <ion-icon name="time-outline" slot="start" color="primary"></ion-icon>
                <ion-label>
                  <p>Ora</p>
                  <h3>{{ getSummaryTime() }}</h3>
                </ion-label>
              </ion-item>
            }
            @if (primaryServiceType.st_mode === 'SU_PREVENTIVO') {
              <ion-item>
                <ion-icon name="document-text-outline" slot="start" color="primary"></ion-icon>
                <ion-label class="ion-text-wrap">
                  <p>Tipo richiesta</p>
                  <h3>Preventivo — il professionista ti invierà un'offerta</h3>
                </ion-label>
              </ion-item>
            }
          </ion-list>
        </ion-card-content>
      </ion-card>
      <ion-list>
        <ion-item>
          <ion-textarea
            label="Note aggiuntive"
            labelPlacement="stacked"
            [(ngModel)]="additionalNotes"
            placeholder="Note opzionali..."
            [autoGrow]="true"
            rows="2"
          ></ion-textarea>
        </ion-item>
      </ion-list>
      @if (pendingFiles.length > 0) {
        <div style="margin: 8px 0">
          <p style="font-size: 13px; color: var(--ion-color-medium)">{{ pendingFiles.length }} allegat{{ pendingFiles.length === 1 ? 'o' : 'i' }}</p>
        </div>
      }
      <ion-button expand="block" color="success" (click)="submitRequest()" [disabled]="submitting" style="margin-top: 16px">
        <ion-icon name="send-outline" slot="start"></ion-icon>
        Invia Richiesta
      </ion-button>
    </div>
  }
</ion-content>

<!-- Footer sticky Step 1: mostra solo quando ci sono servizi selezionati -->
@if (currentStep === 1 && selectedServiceTypes.length > 0) {
  <ion-footer class="selection-footer">
    <div class="selection-footer-inner">
      <div class="selection-footer-info">
        <span class="selection-count">{{ selectedServiceTypes.length }} serviz{{ selectedServiceTypes.length === 1 ? 'io' : 'i' }}</span>
        <span class="selection-duration">{{ totalDurationMinutes }} min totali</span>
      </div>
      <ion-button class="selection-cta" (click)="proceedFromStep1()">
        Scegli orario
        <ion-icon name="arrow-forward-outline" slot="end"></ion-icon>
      </ion-button>
    </div>
  </ion-footer>
}
