import { AppCardComponent, KeyValueComponent } from '@/shared/components';
import { CommonModule } from '@angular/common';
import { Component, effect, EventEmitter, Input, Output, signal } from '@angular/core';
import { Button } from 'primeng/button';
import { IPosEntity, POS_VARIANT_FIELDS, PosVariant } from './models/posEntity.model';

@Component({
  selector: 'app-pos-entity-display',
  standalone: true,
  imports: [CommonModule, AppCardComponent, Button, KeyValueComponent],
  templateUrl: './pos-display.component.html',
})
export class PosDisplayComponent {
  @Input() variant: PosVariant = 'full';
  @Input() pos = signal<IPosEntity | undefined>(undefined);
  @Input() editMode = signal<boolean>(false);
  @Input() cardTitle = 'اطلاعات پایانه‌ی فروش';
  @Input() showMoreActions = true;

  @Output() editModeChange = new EventEmitter<boolean>();
  @Output() onMoreAction = new EventEmitter<void>();
  @Output() onSubmit = new EventEmitter<void>();

  visibleFields = signal<Array<keyof IPosEntity>>([]);
  isEditing = signal<boolean>(false);

  constructor() {
    effect(() => {
      this.visibleFields.set(POS_VARIANT_FIELDS[this.variant] || POS_VARIANT_FIELDS.full);
    });

    effect(() => {
      this.isEditing.set(this.editMode());
    });
  }

  get fieldLabels(): Record<string, string> {
    return {
      name: 'عنوان',
      pos_type: 'نوع پایانه',
      serial_number: 'شماره سریال',
      device: 'نوع دستگاه',
      model: 'مدل دستگاه',
      provider: 'ارایه‌دهنده',
    };
  }

  isFieldVisible(field: keyof IPosEntity): boolean {
    return this.visibleFields().includes(field);
  }

  getFieldValue(field: keyof IPosEntity): any {
    const posData = this.pos();
    if (!posData) return null;

    if (field === 'device' && posData.device) {
      return posData.device.name;
    }
    if (field === 'provider' && posData.provider) {
      return posData.provider.name;
    }
    return posData[field];
  }

  toggleEditMode(): void {
    const newMode = !this.isEditing();
    this.isEditing.set(newMode);
    this.editModeChange.emit(newMode);
  }

  handleMoreAction(): void {
    this.onMoreAction.emit();
  }

  handleSubmit(): void {
    this.onSubmit.emit();
  }
}
