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

@Component({
  selector: 'app-edit-chart-type',
  templateUrl: './edit-chart-type.component.html',
  styleUrls: ['./edit-chart-type.component.scss']
})
export class EditChartTypeComponent implements OnInit {
  chartType: ChartType | null = null;
  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 route: ActivatedRoute,
    private router: Router
  ) { }

  ngOnInit(): void {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    if (id) {
      this.loadChartType(id);
    } else {
      this.showError('Invalid chart type ID');
    }
  }

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

  loadChartType(id: number): void {
    this.loadingState = ClrLoadingState.LOADING;
    this.chartTypeService.getChartTypeById(id).subscribe({
      next: (data) => {
        // Process the data to ensure dates are properly formatted
        this.chartType = {
          ...data,
          createdAt: this.formatDate(data.createdAt),
          updatedAt: this.formatDate(data.updatedAt)
        };
        this.loadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error loading chart type:', error);
        this.showError('Error loading chart type: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = 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 '';
  }

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

    this.loadingState = ClrLoadingState.LOADING;
    this.chartTypeService.updateChartType(this.chartType.id, this.chartType).subscribe({
      next: (data) => {
        // Process the data to ensure dates are properly formatted
        this.chartType = {
          ...data,
          createdAt: this.formatDate(data.createdAt),
          updatedAt: this.formatDate(data.updatedAt)
        };
        this.showSuccess('Chart type updated 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 updating chart type:', error);
        this.showError('Error updating chart type: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

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

  onDelete(): void {
    if (!this.chartType) return;
    
    if (confirm('Are you sure you want to delete this chart type? This action cannot be undone.')) {
      this.loadingState = ClrLoadingState.LOADING;
      this.chartTypeService.deleteChartType(this.chartType.id).subscribe({
        next: () => {
          this.showSuccess('Chart type deleted 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 deleting chart type:', error);
          this.showError('Error deleting chart type: ' + (error.error?.message || error.message || 'Unknown error'));
          this.loadingState = ClrLoadingState.ERROR;
        }
      });
    }
  }
}