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 { DynamicField } from '../chart-config/chart-config-manager.component';
import { DynamicFieldService } from '../chart-config/dynamic-field.service';

@Component({
  selector: 'app-chart-type-fields',
  templateUrl: './chart-type-fields.component.html',
  styleUrls: ['./chart-type-fields.component.scss']
})
export class ChartTypeFieldsComponent implements OnInit {
  chartType: ChartType | null = null;
  dynamicFields: DynamicField[] = [];
  newDynamicField: Partial<DynamicField> = {
    isRequired: false,
    showInUi: true
  };
  selectedDynamicField: DynamicField | 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 dynamicFieldService: DynamicFieldService,
    private route: ActivatedRoute,
    private router: Router
  ) { }

  ngOnInit(): void {
    const chartTypeId = Number(this.route.snapshot.paramMap.get('id'));
    if (chartTypeId) {
      this.loadChartType(chartTypeId);
      this.loadDynamicFields(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'));
      }
    });
  }

  loadDynamicFields(chartTypeId: number): void {
    this.loadingState = ClrLoadingState.LOADING;
    this.dynamicFieldService.getDynamicFieldsByChartType(chartTypeId).subscribe({
      next: (data) => {
        this.dynamicFields = data;
        this.loadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error loading dynamic fields:', error);
        this.showError('Error loading dynamic fields: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

  createDynamicField(): void {
    if (!this.chartType || !this.newDynamicField.fieldName) {
      this.showError('Field name is required');
      return;
    }

    // Create a copy without the chartType property
    const fieldData: Partial<DynamicField> = {
      fieldName: this.newDynamicField.fieldName,
      fieldLabel: this.newDynamicField.fieldLabel,
      fieldType: this.newDynamicField.fieldType,
      fieldOptions: this.newDynamicField.fieldOptions,
      isRequired: this.newDynamicField.isRequired,
      showInUi: this.newDynamicField.showInUi,
      sortOrder: this.newDynamicField.sortOrder
    };

    this.loadingState = ClrLoadingState.LOADING;
    this.dynamicFieldService.createDynamicField(fieldData, this.chartType.id).subscribe({
      next: (data) => {
        this.dynamicFields.push(data);
        this.newDynamicField = { isRequired: false, showInUi: true };
        this.showAddForm = false;
        this.showSuccess('Dynamic field created successfully');
        this.loadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error creating dynamic field:', error);
        this.showError('Error creating dynamic field: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

  updateDynamicField(): void {
    if (!this.selectedDynamicField || !this.selectedDynamicField.fieldName) {
      this.showError('Field name is required');
      return;
    }

    console.log('Updating dynamic field:', this.selectedDynamicField);
    this.loadingState = ClrLoadingState.LOADING;
    this.dynamicFieldService.updateDynamicField(this.selectedDynamicField.id, this.selectedDynamicField).subscribe({
      next: (data) => {
        const index = this.dynamicFields.findIndex(df => df.id === data.id);
        if (index !== -1) {
          this.dynamicFields[index] = data;
        }
        this.selectedDynamicField = null;
        this.showSuccess('Dynamic field updated successfully');
        this.loadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error updating dynamic field:', error);
        this.showError('Error updating dynamic field: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

  deleteDynamicField(id: number): void {
    if (!confirm('Are you sure you want to delete this dynamic field?')) {
      return;
    }

    this.loadingState = ClrLoadingState.LOADING;
    this.dynamicFieldService.deleteDynamicField(id).subscribe({
      next: () => {
        this.dynamicFields = this.dynamicFields.filter(df => df.id !== id);
        this.showSuccess('Dynamic field deleted successfully');
        this.loadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error deleting dynamic field:', error);
        this.showError('Error deleting dynamic field: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

  selectDynamicFieldForEdit(dynamicField: DynamicField): void {
    this.selectedDynamicField = { ...dynamicField };
  }

  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']);
    }
  }
}