import { CommonModule } from '@angular/common';
import { Component, EventEmitter, Input, Output, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { CutoverI18nService } from '../core/cutover-i18n.service';
import { JourneyField } from './journey.models';

@Component({
  selector: 'app-journey-step-form',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <div class="field-grid">
      <label class="field-card" *ngFor="let field of fields">
        <span class="field-card__label">{{ t(field.label) }}</span>
        <ng-container [ngSwitch]="field.type">
          <textarea *ngSwitchCase="'textarea'" [(ngModel)]="formValues[field.key]" rows="4"></textarea>
          <select *ngSwitchCase="'select'" [(ngModel)]="formValues[field.key]">
            <option *ngFor="let option of field.options ?? []" [ngValue]="option.value">
              {{ t(option.label) }}
            </option>
          </select>
          <input
            *ngSwitchCase="'file'"
            type="file"
            accept=".pdf,.png,.jpg,.jpeg,application/pdf,image/png,image/jpeg"
            (change)="fileSelected.emit({ key: field.key, event: $event })" />
          <input *ngSwitchDefault [(ngModel)]="formValues[field.key]" [type]="resolveInputType(field)" />
        </ng-container>
        <small *ngIf="selectedFileNames[field.key]">{{ t('Selected file:') }} {{ selectedFileNames[field.key] }}</small>
      </label>
    </div>
  `
})
export class JourneyStepFormComponent {
  private readonly i18n = inject(CutoverI18nService);

  @Input() fields: readonly JourneyField[] = [];
  @Input() formValues: Record<string, string> = {};
  @Input() selectedFileNames: Record<string, string> = {};

  @Output() fileSelected = new EventEmitter<{ key: string; event: Event }>();

  protected t(value: string): string {
    return this.i18n.text(value);
  }

  protected resolveInputType(field: JourneyField): string {
    return field.type === 'number' ? 'number' : field.type === 'date' ? 'date' : 'text';
  }
}
