import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AlertController } from '@ionic/angular';
import { CloudObject, CloudQuery } from 'src/lib/ncloud';

interface FarmField {
  id: string;
  name: string;
  area: number;
  location: string;
  currentCrop: string;
  growthStage: string;
  daysPlanted: number;
  soilType?: string;
}

interface CropDistribution {
  name: string;
  area: number;
  percentage: number;
}

@Component({
  selector: 'app-tab3',
  templateUrl: './tab3.page.html',
  styleUrls: ['./tab3.page.scss'],
})
export class Tab3Page implements OnInit {
  fields: FarmField[] = [];
  showFieldForm = false;
  editingField: FarmField | null = null;
  fieldForm: FormGroup;

  private cloudQuery = new CloudQuery('FarmField');

  constructor(
    private fb: FormBuilder,
    private alertCtrl: AlertController
  ) {
    this.fieldForm = this.fb.group({
      name: ['', Validators.required],
      area: ['', [Validators.required, Validators.min(0.1)]],
      location: [''],
      currentCrop: ['冬小麦', Validators.required],
      growthStage: ['播种期', Validators.required],
      soilType: ['粘壤土']
    });
  }

  async ngOnInit() {
    await this.loadFields();
    await this.initializeSampleData();
  }

  async loadFields() {
    try {
      const cloudFields = await this.cloudQuery.find();
      this.fields = cloudFields.map(field => ({
        id: field.id || '',
        name: field.get('name'),
        area: field.get('area'),
        location: field.get('location'),
        currentCrop: field.get('currentCrop'),
        growthStage: field.get('growthStage') || '播种期',
        daysPlanted: field.get('daysPlanted') || 0,
        soilType: field.get('soilType')
      }));
    } catch (error) {
      console.error('加载农田数据失败:', error);
    }
  }

  async saveField() {
    if (this.fieldForm.invalid) return;

    const fieldData = this.fieldForm.value;
    const fieldObject = new CloudObject('FarmField');

    if (this.editingField && this.editingField.id) {
      fieldObject.id = this.editingField.id;
      fieldObject.set(fieldData);
      await fieldObject.save();
    } else {
      fieldObject.set({
        ...fieldData,
        daysPlanted: 0
      });
      const savedField = await fieldObject.save();

      this.fields.push({
        id: savedField.id || '',
        daysPlanted: 0,
        ...fieldData
      });
    }

    await this.loadFields();
    this.cancelEdit();
  }

  async confirmDelete() {
    if (!this.editingField || !this.editingField.id) return;

    const alert = await this.alertCtrl.create({
      header: '确认删除',
      message: `确定要删除农田 "${this.editingField.name}" 吗？`,
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '删除',
          handler: async () => {
            await this.deleteField(this.editingField!.id);
          }
        }
      ]
    });

    await alert.present();
  }

  async deleteField(fieldId: string) {
    try {
      const fieldObject = new CloudObject('FarmField');
      fieldObject.id = fieldId;
      await fieldObject.destroy();

      this.fields = this.fields.filter(f => f.id !== fieldId);
      this.cancelEdit();
    } catch (error) {
      console.error('删除农田失败:', error);
    }
  }

  async initializeSampleData() {
    const query = new CloudQuery('FarmField');
    const existingFields = await query.find();

    if (existingFields.length === 0) {
      const sampleFields = [
        {
          name: '北区小麦田',
          area: 5.2,
          location: '农场北侧',
          currentCrop: '冬小麦',
          growthStage: '生长期',
          daysPlanted: 45,
          soilType: '粘壤土'
        },
        {
          name: '南区玉米地',
          area: 3.8,
          location: '农场南侧',
          currentCrop: '春玉米',
          growthStage: '苗期',
          daysPlanted: 22,
          soilType: '砂壤土'
        }
      ];

      for (const field of sampleFields) {
        const fieldObject = new CloudObject('FarmField');
        fieldObject.set(field);
        await fieldObject.save();
      }

      await this.loadFields();
    }
  }

  get totalArea(): number {
    return this.fields.reduce((sum, field) => sum + field.area, 0);
  }

  get cropDistribution(): CropDistribution[] {
    const cropMap = new Map<string, number>();
    
    this.fields.forEach(field => {
      const current = cropMap.get(field.currentCrop) || 0;
      cropMap.set(field.currentCrop, current + field.area);
    });

    const total = this.totalArea;
    return Array.from(cropMap.entries()).map(([name, area]) => ({
      name,
      area,
      percentage: Math.round((area / total) * 100)
    }));
  }

  getCropImage(crop: string): string {
    const cropImages: {[key: string]: string} = {
      '冬小麦': 'assets/images/wheat-icon.png',
      '春玉米': 'assets/images/corn-icon.png',
      '水稻': 'assets/images/rice-icon.png',
      '大豆': 'assets/images/soybean-icon.png'
    };
    return cropImages[crop] || 'assets/images/crop-default.png';
  }

  getCropColor(crop: string): string {
    const cropColors: {[key: string]: string} = {
      '冬小麦': 'primary',
      '春玉米': 'warning',
      '水稻': 'success',
      '大豆': 'tertiary'
    };
    return cropColors[crop] || 'medium';
  }

  getStageColor(stage: string): string {
    const stageColors: {[key: string]: string} = {
      '播种期': 'primary',
      '苗期': 'success',
      '生长期': 'warning',
      '成熟期': 'danger',
      '收获期': 'tertiary'
    };
    return stageColors[stage] || 'medium';
  }

  getStageDays(stage: string): number {
    const stageDays: {[key: string]: number} = {
      '播种期': 10,
      '苗期': 20,
      '生长期': 30,
      '成熟期': 15,
      '收获期': 5
    };
    return stageDays[stage] || 0;
  }

  toggleFieldForm() {
    this.showFieldForm = !this.showFieldForm;
    if (!this.showFieldForm) {
      this.editingField = null;
      this.fieldForm.reset({
        currentCrop: '冬小麦',
        growthStage: '播种期',
        soilType: '粘壤土'
      });
    }
  }

  editField(field: FarmField) {
    this.editingField = field;
    this.fieldForm.patchValue({
      name: field.name,
      area: field.area,
      location: field.location,
      currentCrop: field.currentCrop,
      growthStage: field.growthStage,
      soilType: field.soilType
    });
    this.showFieldForm = true;
  }

  cancelEdit() {
    this.showFieldForm = false;
    this.editingField = null;
    this.fieldForm.reset({
      currentCrop: '冬小麦',
      growthStage: '播种期',
      soilType: '粘壤土'
    });
  }
}