import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ModalService, ModalConfig } from '../../services/modal.service';
import { LoggerService } from '../../services/logger.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-modal',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './modal.component.html',
  styleUrl: './modal.component.scss'
})
export class ModalComponent implements OnInit, OnDestroy {
  config: ModalConfig | null = null;
  inputValue: string = '';
  private subscription?: Subscription;

  constructor(
    private modalService: ModalService,
    private logger: LoggerService
  ) {}

  ngOnInit() {
    this.subscription = this.modalService.getModal().subscribe(config => {
      this.logger.debug('ModalComponent: Received config:', config);
      this.config = config;
      if (config && config.type === 'prompt') {
        this.inputValue = config.inputValue || '';
      }
    });
  }

  ngOnDestroy() {
    this.subscription?.unsubscribe();
  }

  confirm() {
    this.logger.debug('ModalComponent: confirm() called, config:', this.config);
    if (this.config) {
      if (this.config.type === 'prompt') {
        this.modalService.closeModal({ confirmed: true, inputValue: this.inputValue });
      } else {
        this.modalService.closeModal({ confirmed: true });
      }
    }
  }

  cancel() {
    this.logger.debug('ModalComponent: cancel() called');
    this.modalService.closeModal({ confirmed: false });
  }

  getIconPath(): string {
    if (!this.config) return '';
    switch (this.config.type) {
      case 'error':
        return 'M12 9V11M12 15H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z';
      case 'warning':
        return 'M12 9V11M12 15H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z';
      case 'success':
        return 'M20 6L9 17L4 12';
      case 'confirm':
        return 'M9 12L11 14L15 10M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z';
      default:
        return 'M13 16H12V12H11M12 8H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z';
    }
  }

  getIconViewBox(): string {
    if (!this.config) return '0 0 24 24';
    return this.config.type === 'success' ? '0 0 24 24' : '0 0 24 24';
  }
}

