import { Component, OnInit, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { IaParserService, IaParsedBooking } from '../services/ia-parser.service';

@Component({
  selector: 'app-reserva-form',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, RouterModule],
  templateUrl: './reserva-form.component.html',
  styleUrls: ['./reserva-form.component.css']
})
export class ReservaFormComponent implements OnInit {
  private fb = inject(FormBuilder);
  private route = inject(ActivatedRoute);
  private router = inject(Router);
  private iaParser = inject(IaParserService);

  // Exponer Signals del servicio IA a la plantilla
  isLoadingIa = this.iaParser.isLoading;

  // Reactivo Form
  bookingForm!: FormGroup;

  // Estado del asistente
  aiPrompt = signal<string>('');
  aiSuccessMessage = signal<string>('');

  ngOnInit(): void {
    this.initForm();

    // Capturar QueryParams desde la URL
    this.route.queryParams.subscribe(params => {
      const fecha = params['fecha'] || '';
      const tipo = params['tipo'] || 'room';

      this.bookingForm.patchValue({
        date: fecha,
        resourceType: tipo
      });
    });
  }

  private initForm(): void {
    this.bookingForm = this.fb.group({
      title: ['', [Validators.required, Validators.minLength(3)]],
      resourceType: ['room', [Validators.required]],
      resourceName: ['', [Validators.required]],
      date: ['', [Validators.required]],
      startTime: ['', [Validators.required]],
      endTime: ['', [Validators.required]],
      attendees: [1, [Validators.required, Validators.min(1)]],
      hasProjector: [false],
      notes: ['']
    });
  }

  /**
   * Envía el prompt de lenguaje natural del Asistente IA para parsear y auto-llenar los campos.
   */
  processAiPrompt(promptText: string): void {
    if (!promptText.trim()) return;

    this.iaParser.parseNaturalLanguage(promptText).subscribe({
      next: (parsedData: IaParsedBooking) => {
        // Rellenar formulario reactivamente con los datos estructurados devueltos por la IA
        this.bookingForm.patchValue({
          title: parsedData.title || this.bookingForm.get('title')?.value,
          resourceType: parsedData.resourceType || this.bookingForm.get('resourceType')?.value,
          resourceName: parsedData.resourceName || this.bookingForm.get('resourceName')?.value,
          date: parsedData.date || this.bookingForm.get('date')?.value,
          startTime: parsedData.startTime || this.bookingForm.get('startTime')?.value,
          endTime: parsedData.endTime || this.bookingForm.get('endTime')?.value,
          attendees: parsedData.attendees || this.bookingForm.get('attendees')?.value,
          hasProjector: parsedData.hasProjector !== undefined ? parsedData.hasProjector : this.bookingForm.get('hasProjector')?.value,
          notes: parsedData.notes || this.bookingForm.get('notes')?.value
        });

        this.aiSuccessMessage.set('¡Los campos del formulario se han pre-llenado automáticamente gracias al Asistente IA!');
        setTimeout(() => this.aiSuccessMessage.set(''), 5000);
      },
      error: (err) => {
        console.error('Error procesando prompt con IA:', err);
      }
    });
  }

  onSubmit(): void {
    if (this.bookingForm.invalid) {
      this.bookingForm.markAllAsTouched();
      return;
    }

    console.log('Reserva creada exitosamente:', this.bookingForm.value);
    
    // Regresar al calendario
    this.router.navigate(['/reservas/calendario']);
  }
}
