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

@Component({
  selector: 'app-chart-type-manager',
  templateUrl: './chart-type-manager.component.html',
  styleUrls: ['./chart-type-manager.component.scss']
})
export class ChartTypeManagerComponent implements OnInit {
  chartTypes: ChartType[] = [];
  chartTypeLoadingState: ClrLoadingState = ClrLoadingState.DEFAULT;

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

  // Error handling
  errorMessage: string | null = null;
  successMessage: string | null = null;

  constructor(private chartTypeService: ChartTypeService) { }

  ngOnInit(): void {
    this.loadChartTypes();
  }

  // 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);
  }

  // Chart Type Methods
  loadChartTypes(): void {
    this.chartTypeLoadingState = ClrLoadingState.LOADING;
    this.chartTypeService.getAllChartTypes().subscribe({
      next: (data) => {
        // Process the data to ensure dates are properly formatted
        this.chartTypes = data.map(chartType => ({
          ...chartType,
          createdAt: this.formatDate(chartType.createdAt),
          updatedAt: this.formatDate(chartType.updatedAt)
        }));
        this.chartTypeLoadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error loading chart types:', error);
        this.showError('Error loading chart types: ' + (error.error?.message || error.message || 'Unknown error'));
        this.chartTypeLoadingState = ClrLoadingState.ERROR;
      }
    });
  }

  // Format date to handle both string and object formats
  private formatDate(date: any): string {
    if (!date) return '';
    
    // If it's already a string, return as is
    if (typeof date === 'string') {
      return date;
    }
    
    // If it's an object, try to convert to string
    if (typeof date === 'object') {
      // Handle various date object formats
      if (date instanceof Date) {
        return date.toISOString();
      }
      
      // Handle ISO string within object
      if (date.date) {
        return date.date;
      }
      
      // Handle other object formats
      try {
        return new Date(date).toISOString();
      } catch {
        return '';
      }
    }
    
    return '';
  }

  deleteChartType(id: number): void {
    if (!confirm('Are you sure you want to delete this chart type?')) {
      return;
    }

    this.chartTypeLoadingState = ClrLoadingState.LOADING;
    this.chartTypeService.deleteChartType(id).subscribe({
      next: () => {
        this.chartTypes = this.chartTypes.filter(ct => ct.id !== id);
        this.showSuccess('Chart type deleted successfully');
        this.chartTypeLoadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error deleting chart type:', error);
        this.showError('Error deleting chart type: ' + (error.error?.message || error.message || 'Unknown error'));
        this.chartTypeLoadingState = ClrLoadingState.ERROR;
      }
    });
  }
}