import { Component, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { ApiService, VisitPlanItem } from '../../core/api.service';
import { LangService } from '../../core/lang.service';
import { SelectionService } from '../../core/selection.service';
import { WizardStateService } from '../../core/wizard-state.service';

@Component({
  selector: 'app-visit',
  standalone: true,
  imports: [FormsModule, RouterLink],
  template: `
    <section class="visit">
      <div class="container narrow">
        @if (booked()) {
          <div class="card done center fade-in">
            <div class="tick">✓</div>
            <h2>{{ lang.t('visits_booked') }}</h2>
            <p class="muted">{{ lang.t('visits_booked_msg') }}</p>
            <a routerLink="/account" class="btn btn--gold">{{ lang.t('login_now') }}</a>
          </div>
        } @else {
          <div class="head">
            <h2>{{ lang.t('book_visit') }}</h2>
            <p class="muted">{{ lang.t('visit_intro') }}</p>
          </div>

          @if (loading()) {
            <div class="center muted load">{{ lang.t('loading') }}</div>
          } @else {
            @for (loc of plan(); track $index) {
              <div class="card loc fade-in">
                <div class="loc-head">
                  <h3>{{ loc.location_name || ('—') }}</h3>
                  <span class="halls muted">{{ lang.t('halls_at') }}: {{ loc.halls.join('، ') }}</span>
                  @if (loc.hours) {
                    <div class="hours muted">
                      <span>{{ lang.t('open_days') }}: {{ openDayNames(loc) }}</span>
                      <span>· {{ lang.t('open_hours') }}: {{ loc.hours.open }}–{{ loc.hours.close }}</span>
                    </div>
                  }
                </div>
                <div class="row">
                  <div class="field grow">
                    <label>{{ lang.t('pick_date') }}</label>
                    <input type="date" [min]="today" [(ngModel)]="dates[$index]" />
                    @if (dateClosed($index)) { <small class="err">{{ lang.t('closed_that_day') }}</small> }
                  </div>
                  <div class="field grow">
                    <label>{{ lang.t('pick_time') }}</label>
                    <select [(ngModel)]="times[$index]">
                      <option value="">—</option>
                      @for (s of slots(loc); track s) { <option [value]="s">{{ s }}</option> }
                    </select>
                  </div>
                </div>
              </div>
            }

            <button class="btn btn--gold btn--lg full" [disabled]="busy() || !anyValid()" (click)="confirm()">
              {{ busy() ? lang.t('processing') : lang.t('confirm_visits') }}
            </button>
          }
        }
      </div>
    </section>
  `,
  styles: [`
    .visit { padding: 46px 0 90px; min-height: calc(100vh - 72px); }
    .narrow { max-width: 720px; }
    .head { text-align: center; margin-bottom: 28px; }
    .head h2 { margin-bottom: 6px; }
    .load { padding: 60px 0; }
    .loc { padding: 24px; margin-bottom: 18px; }
    .loc-head { margin-bottom: 16px; }
    .loc-head h3 { margin: 0 0 4px; }
    .halls { font-size: .9rem; }
    .hours { font-size: .82rem; margin-top: 6px; display: flex; gap: 8px; flex-wrap: wrap; }
    .err { color: #c0392b; font-size: .8rem; margin-top: 5px; display: block; }
    .field select { width: 100%; padding: 11px 12px; border: 1px solid var(--line, #e6e0d6); border-radius: 10px;
      background: #fff; font: inherit; color: inherit; }
    .full { width: 100%; margin-top: 8px; }
    .done { padding: 56px 30px; display: flex; flex-direction: column; gap: 14px; align-items: center; }
    .tick { width: 64px; height: 64px; border-radius: 50%; background: linear-gradient(135deg, var(--gold), var(--gold-deep));
      color: #fff; font-size: 2rem; display: flex; align-items: center; justify-content: center; }
  `],
})
export class VisitComponent {
  lang = inject(LangService);
  private api = inject(ApiService);
  private state = inject(WizardStateService);
  private selection = inject(SelectionService);
  private router = inject(Router);

  plan = signal<VisitPlanItem[]>([]);
  loading = signal(true);
  busy = signal(false);
  booked = signal(false);
  dates: string[] = [];
  times: string[] = [];
  today = new Date().toISOString().slice(0, 10);

  constructor() {
    const token = this.state.token();
    if (!token) { this.loading.set(false); return; }
    this.api.visitPlan(token).subscribe({
      next: (r) => { this.plan.set(r.data.visits); this.loading.set(false); },
      error: () => this.loading.set(false),
    });
  }

  anyValid(): boolean { return this.plan().some((_, i) => !!this.dates[i] && !this.dateClosed(i)); }

  /** Localized open-day names for a location's working hours. */
  openDayNames(loc: VisitPlanItem): string {
    return (loc.hours?.days ?? []).map((d) => this.lang.t('d' + d)).join(' · ');
  }

  /** 30-minute time slots within the location's open–close window. */
  slots(loc: VisitPlanItem): string[] {
    const h = loc.hours;
    return this.buildSlots(h?.open || '10:00', h?.close || '22:00');
  }

  private buildSlots(open: string, close: string): string[] {
    const [oh, om] = open.split(':').map(Number);
    const [ch, cm] = close.split(':').map(Number);
    const out: string[] = [];
    for (let t = oh * 60 + om, end = ch * 60 + cm; t <= end; t += 30) {
      out.push(`${String(Math.floor(t / 60)).padStart(2, '0')}:${String(t % 60).padStart(2, '0')}`);
    }
    return out;
  }

  /** True when the chosen date falls on a day the location is closed. */
  dateClosed(i: number): boolean {
    const d = this.dates[i];
    const days = this.plan()[i]?.hours?.days;
    if (!d || !days || !days.length) return false;
    return !days.includes(new Date(d + 'T00:00:00').getDay()); // getDay: 0=Sun..6=Sat
  }

  confirm(): void {
    const token = this.state.token();
    if (!token) return;
    const visits = this.plan()
      .map((loc, i) => ({
        location_id: loc.location_id,
        visit_date: this.dates[i],
        visit_time: this.times[i] || undefined,
        closed: this.dateClosed(i),
      }))
      .filter((v) => !!v.visit_date && !v.closed)
      .map(({ closed, ...v }) => v);
    if (!visits.length) return;

    this.busy.set(true);
    this.api.bookVisits(token, visits).subscribe({
      next: () => { this.busy.set(false); this.booked.set(true); this.selection.clear(); },
      error: () => { this.busy.set(false); },
    });
  }
}
