import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Slot } from '@calendar/core';
import { SlotTimePipe } from '../pipes/slot-time.pipe';

@Component({
  selector: 'calendar-slot-picker',
  standalone: true,
  imports: [SlotTimePipe],
  template: `
    @if (loading) {
      <p class="status">Loading available times…</p>
    } @else if (!slots.length) {
      <div class="empty">
        <p>No times available for this date.</p>
        <p class="hint">Try selecting a different day.</p>
      </div>
    } @else {
      <div class="slots">
        @for (slot of slots; track slot.startTime) {
          <button
            type="button"
            class="slot"
            [class.selected]="slot.startTime === selectedStartTime"
            (click)="slotSelect.emit(slot)"
          >
            <span class="slot-time">{{ slot.startTime | slotTime: timezone }}</span>
            <span class="slot-end">– {{ slot.endTime | slotTime: timezone }}</span>
          </button>
        }
      </div>
    }
  `,
  styles: [
    `
      .slots {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 0.5rem;
      }
      .slot {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 0.1rem;
        padding: 0.65rem 0.5rem;
        border: 1px solid var(--cal-border, #e2e8f0);
        border-radius: 10px;
        background: var(--cal-surface, #fff);
        font-size: 0.875rem;
        font-weight: 500;
        font-family: inherit;
        cursor: pointer;
        transition: border-color 0.15s, background 0.15s, color 0.15s;
      }
      .slot-time {
        font-weight: 600;
      }
      .slot-end {
        font-size: 0.75rem;
        font-weight: 400;
        opacity: 0.85;
      }
      .slot.selected .slot-end {
        opacity: 0.9;
      }
      .slot:hover {
        border-color: var(--cal-brand, #4f46e5);
        background: var(--cal-brand-soft, #eef2ff);
        color: var(--cal-brand, #4f46e5);
      }
      .slot.selected {
        border-color: var(--cal-brand, #4f46e5);
        background: var(--cal-brand, #4f46e5);
        color: #fff;
        font-weight: 600;
      }
      .status {
        text-align: center;
        color: var(--cal-text-muted, #64748b);
        padding: 2rem 0;
      }
      .empty {
        text-align: center;
        padding: 2rem 1rem;
        color: var(--cal-text-muted, #64748b);
      }
      .empty p {
        margin: 0;
      }
      .hint {
        margin-top: 0.35rem !important;
        font-size: 0.85rem;
      }
    `,
  ],
})
export class SlotPickerComponent {
  @Input() slots: Slot[] = [];
  @Input() loading = false;
  @Input() selectedStartTime: string | null = null;
  /** Guest IANA timezone — slots are converted from UTC start/end for display. */
  @Input() timezone: string | null = null;
  @Output() slotSelect = new EventEmitter<Slot>();
}
