import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { ClrLoadingState } from '@clr/angular';
import { ChartType, ChartTypeService } from './chart-type.service';

@Component({
  selector: 'app-add-chart-type',
  templateUrl: './add-chart-type.component.html',
  styleUrls: ['./add-chart-type.component.scss']
})
export class AddChartTypeComponent {
  chartType: Partial<ChartType> = {
    isActive: true
  };
  loadingState: ClrLoadingState = ClrLoadingState.DEFAULT;
  errorMessage: string | null = null;
  successMessage: string | null = null;

  // Make ClrLoadingState available to template
  readonly ClrLoadingState = ClrLoadingState;

  constructor(
    private chartTypeService: ChartTypeService,
    private router: Router
  ) { }

  // Show error message
  private showError(message: string): void {
    this.errorMessage = message;
    setTimeout(() => {
      this.errorMessage = null;
    }, 5000);
  }

  // Show success message
  private showSuccess(message: string): void {
    this.successMessage = message;
    setTimeout(() => {
      this.successMessage = null;
    }, 3000);
  }

  createChartType(): void {
    if (!this.chartType.name) {
      this.showError('Chart type name is required');
      return;
    }

    this.loadingState = ClrLoadingState.LOADING;
    this.chartTypeService.createChartType(this.chartType).subscribe({
      next: (data) => {
        this.showSuccess('Chart type created successfully');
        this.loadingState = ClrLoadingState.SUCCESS;
        // Redirect to chart types list after a short delay
        setTimeout(() => {
          this.router.navigate(['/cns-portal/dashboardbuilder/chart-types']);
        }, 1500);
      },
      error: (error) => {
        console.error('Error creating chart type:', error);
        this.showError('Error creating chart type: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

  onCancel(): void {
    this.router.navigate(['/cns-portal/dashboardbuilder/chart-types']);
  }
}