import { Component, Input, Output, EventEmitter, signal, computed } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { DesignerAssignmentComponent, DesignerAssignment, QuotationItem } from '../designer-assignment/designer-assignment.component';
import { QuotationDetailComponent } from '../quotation-detail/quotation-detail.component';

export interface OrderFormData {
  orderAmount: number;
  decorationType: string;
  smallImageTime: string;
  largeImageTime?: string;
  requirementReason: string;
}

@Component({
  selector: 'app-order-form',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, DesignerAssignmentComponent, QuotationDetailComponent],
  templateUrl: './order-form.component.html',
  styleUrls: ['./order-form.component.scss']
})
export class OrderFormComponent {
  @Input() initialData?: Partial<OrderFormData>;
  @Output() formChange = new EventEmitter<OrderFormData>();
  @Output() validChange = new EventEmitter<boolean>();

  orderForm: FormGroup;
  quotationItems = signal<QuotationItem[]>([]);
  selectedDesigners = signal<DesignerAssignment[]>([]);

  // 计算总金额是否匹配
  totalAmountMatch = computed(() => {
    const formAmount = this.orderForm?.get('orderAmount')?.value || 0;
    const quotationTotal = this.quotationItems().reduce((sum, item) => sum + item.amount, 0);
    return Math.abs(formAmount - quotationTotal) < 0.01;
  });

  constructor(private fb: FormBuilder) {
    this.orderForm = this.createForm();
    this.setupFormSubscription();
  }

  ngOnInit() {
    if (this.initialData) {
      this.orderForm.patchValue(this.initialData);
    }
  }

  private createForm(): FormGroup {
    return this.fb.group({
      orderAmount: [0, [Validators.required, Validators.min(0.01)]],
      decorationType: ['', Validators.required],
      smallImageTime: ['', Validators.required],
      largeImageTime: [''],
      requirementReason: ['', [Validators.required, Validators.minLength(10)]]
    });
  }

  private setupFormSubscription() {
    this.orderForm.valueChanges.subscribe(value => {
      this.formChange.emit(value);
      this.validChange.emit(this.isFormValid());
    });
  }

  onQuotationChange(items: QuotationItem[]) {
    this.quotationItems.set(items);
    
    // 自动更新订单总金额
    const totalAmount = items.reduce((sum, item) => sum + item.amount, 0);
    this.orderForm.patchValue({ orderAmount: totalAmount }, { emitEvent: false });
    
    this.emitFormChange();
  }

  onDesignerChange(designers: DesignerAssignment[]) {
    this.selectedDesigners.set(designers);
    this.emitFormChange();
  }

  private emitFormChange() {
    const formData: OrderFormData = {
      ...this.orderForm.value,
      quotationItems: this.quotationItems(),
      designerAssignments: this.selectedDesigners()
    };
    this.formChange.emit(formData);
    this.validChange.emit(this.isFormValid());
  }

  isFormValid(): boolean {
    const formValid = this.orderForm.valid;
    const hasQuotation = this.quotationItems().length > 0;
    const hasDesigners = this.selectedDesigners().length > 0;
    const amountMatch = this.totalAmountMatch();
    
    return formValid && hasQuotation && hasDesigners && amountMatch;
  }

  getFormData(): OrderFormData & { quotationItems: QuotationItem[], designerAssignments: DesignerAssignment[] } {
    return {
      ...this.orderForm.value,
      quotationItems: this.quotationItems(),
      designerAssignments: this.selectedDesigners()
    };
  }

  resetForm() {
    this.orderForm.reset();
    this.quotationItems.set([]);
    this.selectedDesigners.set([]);
  }
}