import { Component, Inject, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatIconModule } from '@angular/material/icon';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatTabsModule } from '@angular/material/tabs';
import { MatExpansionModule } from '@angular/material/expansion';

interface ApiIntegration {
  id: string;
  name: string;
  type: string;
  status: 'active' | 'inactive' | 'error';
  endpoint: string;
  authentication: string;
  lastTested?: string;
  description: string;
  configuration: Record<string, any>;
  createdBy: string;
  createdAt: string;
  updatedAt: string;
}

interface DialogData {
  item: ApiIntegration;
  integrationTypes: string[];
}

@Component({
  selector: 'app-api-dialog',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatButtonModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatIconModule,
    MatSlideToggleModule,
    MatTabsModule,
    MatExpansionModule
  ],
  templateUrl: './api-dialog.html',
  styleUrl: './api-dialog.scss'
})
export class ApiDialogComponent implements OnInit {
  integration: ApiIntegration;
  isEditMode: boolean;
  integrationTypes: string[] = [];
  
  // 认证方式选项
  authenticationMethods = ['API Key', 'OAuth 2.0', 'Basic Auth', 'Bearer Token', 'Webhook', '其他'];
  
  // 配置键值对
  configKeys: string[] = [];
  configValues: string[] = [];
  newConfigKey = '';
  newConfigValue = '';
  
  // 错误提示
  errors: Record<string, string> = {};

  constructor(
    public dialogRef: MatDialogRef<ApiDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData
  ) {
    this.integration = { ...data.item };
    this.isEditMode = !!this.integration.id;
    this.integrationTypes = data.integrationTypes || [];
  }

  ngOnInit(): void {
    // 初始化配置键值对
    this.initializeConfigFields();
  }

  // 初始化配置字段
  initializeConfigFields(): void {
    this.configKeys = Object.keys(this.integration.configuration);
    this.configValues = Object.values(this.integration.configuration).map(value => 
      typeof value === 'object' ? JSON.stringify(value) : value.toString()
    );
  }

  onCancel(): void {
    this.dialogRef.close();
  }

  onSave(): void {
    if (this.isFormValid()) {
      // 保存配置到integration对象
      this.saveConfigFields();
      
      // 更新时间
      this.integration.updatedAt = new Date().toLocaleString('zh-CN');
      
      // 关闭对话框并返回数据
      this.dialogRef.close(this.integration);
    }
  }

  isFormValid(): boolean {
    // 重置错误提示
    this.errors = {};
    
    // 验证必填字段
    if (!this.integration.name || !this.integration.name.trim()) {
      this.errors['name'] = '请输入集成名称';
    }
    
    if (!this.integration.type) {
      this.errors['type'] = '请选择集成类型';
    }
    
    if (!this.integration.endpoint || !this.integration.endpoint.trim()) {
      this.errors['endpoint'] = '请输入API端点';
    } else if (!this.isValidUrl(this.integration.endpoint)) {
      this.errors['endpoint'] = '请输入有效的URL';
    }
    
    if (!this.integration.authentication) {
      this.errors['authentication'] = '请选择认证方式';
    }
    
    if (!this.integration.description || !this.integration.description.trim()) {
      this.errors['description'] = '请输入描述';
    }
    
    // 验证配置字段
    for (let i = 0; i < this.configKeys.length; i++) {
      if (!this.configKeys[i] || !this.configKeys[i].trim()) {
        this.errors[`config_key_${i}`] = '配置键不能为空';
      }
      if (!this.configValues[i] || !this.configValues[i].trim()) {
        this.errors[`config_value_${i}`] = '配置值不能为空';
      }
    }
    
    // 返回是否有错误
    return Object.keys(this.errors).length === 0;
  }

  // 验证URL有效性
  isValidUrl(url: string): boolean {
    try {
      new URL(url);
      return true;
    } catch (e) {
      return false;
    }
  }

  // 保存配置字段到integration对象
  saveConfigFields(): void {
    const config: Record<string, any> = {};
    
    for (let i = 0; i < this.configKeys.length; i++) {
      const key = this.configKeys[i].trim();
      let value = this.configValues[i].trim();
      
      // 尝试解析JSON格式的值
      try {
        value = JSON.parse(value);
      } catch (e) {
        // 如果不是JSON格式，则保持原样
      }
      
      config[key] = value;
    }
    
    this.integration.configuration = config;
  }

  // 添加新的配置字段
  addConfigField(): void {
    if (this.newConfigKey.trim() && this.newConfigValue.trim()) {
      this.configKeys.push(this.newConfigKey.trim());
      this.configValues.push(this.newConfigValue.trim());
      this.newConfigKey = '';
      this.newConfigValue = '';
      
      // 清除配置字段的错误
      Object.keys(this.errors).forEach(key => {
        if (key.startsWith('config_')) {
          delete this.errors[key];
        }
      });
    }
  }

  // 删除配置字段
  removeConfigField(index: number): void {
    this.configKeys.splice(index, 1);
    this.configValues.splice(index, 1);
    
    // 清除配置字段的错误
    Object.keys(this.errors).forEach(key => {
      if (key.startsWith('config_')) {
        delete this.errors[key];
      }
    });
  }

  // 获取对话框标题
  get dialogTitle(): string {
    return this.isEditMode ? '编辑API集成' : '添加新API集成';
  }
}