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

@Component({
  selector: 'app-chart-type-templates',
  templateUrl: './chart-type-templates.component.html',
  styleUrls: ['./chart-type-templates.component.scss']
})
export class ChartTypeTemplatesComponent implements OnInit {
  chartType: ChartType | null = null;
  chartTemplates: ChartTemplate[] = [];
  newChartTemplate: Partial<ChartTemplate> = {
    isDefault: false
  };
  selectedChartTemplate: ChartTemplate | null = null;
  showAddForm = false;
  
  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 chartTemplateService: ChartTemplateService,
    private route: ActivatedRoute,
    private router: Router
  ) { }

  ngOnInit(): void {
    const chartTypeId = Number(this.route.snapshot.paramMap.get('id'));
    if (chartTypeId) {
      this.loadChartType(chartTypeId);
      this.loadChartTemplates(chartTypeId);
    } 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.chartTypeService.getChartTypeById(id).subscribe({
      next: (data) => {
        this.chartType = data;
      },
      error: (error) => {
        console.error('Error loading chart type:', error);
        this.showError('Error loading chart type: ' + (error.error?.message || error.message || 'Unknown error'));
      }
    });
  }

  loadChartTemplates(chartTypeId: number): void {
    this.loadingState = ClrLoadingState.LOADING;
    this.chartTemplateService.getChartTemplatesByChartType(chartTypeId).subscribe({
      next: (data) => {
        this.chartTemplates = data;
        this.loadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error loading chart templates:', error);
        this.showError('Error loading chart templates: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

  createChartTemplate(): void {
    if (!this.chartType || !this.newChartTemplate.templateName) {
      this.showError('Template name is required');
      return;
    }

    // Create a copy without the chartType property
    const templateData: Partial<ChartTemplate> = {
      templateName: this.newChartTemplate.templateName,
      templateHtml: this.newChartTemplate.templateHtml,
      templateCss: this.newChartTemplate.templateCss,
      isDefault: this.newChartTemplate.isDefault
    };

    this.loadingState = ClrLoadingState.LOADING;
    this.chartTemplateService.createChartTemplate(templateData, this.chartType.id).subscribe({
      next: (data) => {
        this.chartTemplates.push(data);
        this.newChartTemplate = { isDefault: false };
        this.showAddForm = false;
        this.showSuccess('Chart template created successfully');
        this.loadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error creating chart template:', error);
        this.showError('Error creating chart template: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

  updateChartTemplate(): void {
    if (!this.selectedChartTemplate || !this.selectedChartTemplate.templateName) {
      this.showError('Template name is required');
      return;
    }

    this.loadingState = ClrLoadingState.LOADING;
    this.chartTemplateService.updateChartTemplate(this.selectedChartTemplate.id, this.selectedChartTemplate).subscribe({
      next: (data) => {
        const index = this.chartTemplates.findIndex(ct => ct.id === data.id);
        if (index !== -1) {
          this.chartTemplates[index] = data;
        }
        this.selectedChartTemplate = null;
        this.showSuccess('Chart template updated successfully');
        this.loadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error updating chart template:', error);
        this.showError('Error updating chart template: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

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

    this.loadingState = ClrLoadingState.LOADING;
    this.chartTemplateService.deleteChartTemplate(id).subscribe({
      next: () => {
        this.chartTemplates = this.chartTemplates.filter(ct => ct.id !== id);
        this.showSuccess('Chart template deleted successfully');
        this.loadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error deleting chart template:', error);
        this.showError('Error deleting chart template: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

  selectChartTemplateForEdit(chartTemplate: ChartTemplate): void {
    this.selectedChartTemplate = { ...chartTemplate };
  }

  goBack(): void {
    if (this.chartType) {
      this.router.navigate(['/cns-portal/dashboardbuilder/chart-types/edit', this.chartType.id]);
    } else {
      this.router.navigate(['/cns-portal/dashboardbuilder/chart-types']);
    }
  }
}