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 { UiComponentService } from '../chart-config/ui-component.service';
import { ComponentPropertyService } from '../chart-config/component-property.service';
import { UiComponent, ComponentProperty } from '../chart-config/chart-config-manager.component';

@Component({
  selector: 'app-chart-type-ui-components',
  templateUrl: './chart-type-ui-components.component.html',
  styleUrls: ['./chart-type-ui-components.component.scss']
})
export class ChartTypeUiComponentsComponent implements OnInit {
  chartType: ChartType | null = null;
  uiComponents: UiComponent[] = [];
  newUiComponent: Partial<UiComponent> = {
    isRequired: false
  };
  selectedUiComponent: UiComponent | null = null;
  showAddForm = false;
  
  // Component Properties
  componentProperties: ComponentProperty[] = [];
  selectedComponentProperty: ComponentProperty | null = null;
  newComponentProperty: Partial<ComponentProperty> = {};
  showAddComponentPropertyForm = false;
  componentPropertyLoadingState: ClrLoadingState = ClrLoadingState.DEFAULT;
  
  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 uiComponentService: UiComponentService,
    private componentPropertyService: ComponentPropertyService,
    private route: ActivatedRoute,
    private router: Router
  ) { }

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

  loadUiComponents(chartTypeId: number): void {
    this.loadingState = ClrLoadingState.LOADING;
    this.uiComponentService.getUiComponentsByChartType(chartTypeId).subscribe({
      next: (data) => {
        this.uiComponents = data;
        this.loadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error loading UI components:', error);
        this.showError('Error loading UI components: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

  createUiComponent(): void {
    if (!this.chartType || !this.newUiComponent.componentName) {
      this.showError('Component name is required');
      return;
    }

    this.loadingState = ClrLoadingState.LOADING;
    
    // Create a complete chartType object with only the ID (following the pattern in chart-config-manager)
    const chartTypeWithId = { 
      id: this.chartType.id,
      name: '',
      displayName: '',
      description: '',
      isActive: true,
      createdAt: '',
      updatedAt: ''
    };

    const componentData = {
      ...this.newUiComponent,
      chartType: chartTypeWithId
    };
    
    this.uiComponentService.createUiComponent(componentData).subscribe({
      next: (data) => {
        this.uiComponents.push(data);
        this.newUiComponent = { isRequired: false };
        this.showAddForm = false;
        this.showSuccess('UI component created successfully');
        this.loadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error creating UI component:', error);
        this.showError('Error creating UI component: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

  updateUiComponent(): void {
    if (!this.selectedUiComponent || !this.selectedUiComponent.componentName) {
      this.showError('Component name is required');
      return;
    }

    this.loadingState = ClrLoadingState.LOADING;
    this.uiComponentService.updateUiComponent(this.selectedUiComponent.id, this.selectedUiComponent).subscribe({
      next: (data) => {
        const index = this.uiComponents.findIndex(uc => uc.id === data.id);
        if (index !== -1) {
          this.uiComponents[index] = data;
        }
        this.selectedUiComponent = null;
        this.showSuccess('UI component updated successfully');
        this.loadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error updating UI component:', error);
        this.showError('Error updating UI component: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

  deleteUiComponent(id: number): void {
    if (!confirm('Are you sure you want to delete this UI component?')) {
      return;
    }

    this.loadingState = ClrLoadingState.LOADING;
    this.uiComponentService.deleteUiComponent(id).subscribe({
      next: () => {
        this.uiComponents = this.uiComponents.filter(uc => uc.id !== id);
        this.showSuccess('UI component deleted successfully');
        this.loadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error deleting UI component:', error);
        this.showError('Error deleting UI component: ' + (error.error?.message || error.message || 'Unknown error'));
        this.loadingState = ClrLoadingState.ERROR;
      }
    });
  }

  selectUiComponentForEdit(uiComponent: UiComponent): void {
    this.selectedUiComponent = { ...uiComponent };
  }

  // Component Property Methods
  loadComponentProperties(componentId: number): void {
    if (!componentId) {
      this.componentProperties = [];
      return;
    }
    
    this.componentPropertyLoadingState = ClrLoadingState.LOADING;
    this.componentPropertyService.getComponentPropertiesByComponent(componentId).subscribe({
      next: (data) => {
        this.componentProperties = data;
        this.componentPropertyLoadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error loading component properties:', error);
        this.showError('Error loading component properties: ' + (error.error?.message || error.message || 'Unknown error'));
        this.componentPropertyLoadingState = ClrLoadingState.ERROR;
      }
    });
  }

  createComponentProperty(): void {
    if (!this.selectedUiComponent) {
      this.showError('Please select a UI component first');
      return;
    }

    if (!this.newComponentProperty.propertyName) {
      this.showError('Property name is required');
      return;
    }

    this.componentPropertyLoadingState = ClrLoadingState.LOADING;
    
    // Create a complete component object with only the ID
    const componentWithId = { 
      id: this.selectedUiComponent.id
    } as UiComponent;

    const componentPropertyData = {
      ...this.newComponentProperty,
      component: componentWithId
    };

    this.componentPropertyService.createComponentProperty(componentPropertyData).subscribe({
      next: (data) => {
        this.componentProperties.push(data);
        this.newComponentProperty = {};
        this.showAddComponentPropertyForm = false;
        this.showSuccess('Component property created successfully');
        this.componentPropertyLoadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error creating component property:', error);
        this.showError('Error creating component property: ' + (error.error?.message || error.message || 'Unknown error'));
        this.componentPropertyLoadingState = ClrLoadingState.ERROR;
      }
    });
  }

  updateComponentProperty(): void {
    if (!this.selectedComponentProperty || !this.selectedComponentProperty.propertyName) {
      this.showError('Property name is required');
      return;
    }

    this.componentPropertyLoadingState = ClrLoadingState.LOADING;
    this.componentPropertyService.updateComponentProperty(this.selectedComponentProperty.id, this.selectedComponentProperty).subscribe({
      next: (data) => {
        const index = this.componentProperties.findIndex(cp => cp.id === data.id);
        if (index !== -1) {
          this.componentProperties[index] = data;
        }
        this.selectedComponentProperty = null;
        this.showSuccess('Component property updated successfully');
        this.componentPropertyLoadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error updating component property:', error);
        this.showError('Error updating component property: ' + (error.error?.message || error.message || 'Unknown error'));
        this.componentPropertyLoadingState = ClrLoadingState.ERROR;
      }
    });
  }

  deleteComponentProperty(id: number): void {
    if (!confirm('Are you sure you want to delete this component property?')) {
      return;
    }

    this.componentPropertyLoadingState = ClrLoadingState.LOADING;
    this.componentPropertyService.deleteComponentProperty(id).subscribe({
      next: () => {
        this.componentProperties = this.componentProperties.filter(cp => cp.id !== id);
        this.showSuccess('Component property deleted successfully');
        this.componentPropertyLoadingState = ClrLoadingState.SUCCESS;
      },
      error: (error) => {
        console.error('Error deleting component property:', error);
        this.showError('Error deleting component property: ' + (error.error?.message || error.message || 'Unknown error'));
        this.componentPropertyLoadingState = ClrLoadingState.ERROR;
      }
    });
  }

  selectComponentPropertyForEdit(componentProperty: ComponentProperty): void {
    this.selectedComponentProperty = { ...componentProperty };
  }

  // Helper method to view properties for a UI component
  onViewComponentProperties(uiComponent: UiComponent): void {
    this.selectedUiComponent = uiComponent;
    this.loadComponentProperties(uiComponent.id);
  }

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