import { ExpenseItem, addExpense as addToStore, generateId, EXPENSE_CATEGORIES, INCOME_CATEGORIES, CATEGORY_COLORS } from '../model/ExpenseModel';
import { aiClassify, submitBill } from '../model/ApiService';
import { promptAction } from '@kit.ArkUI';

@Component
export struct AddExpense {
  @State amount: string = '';
  @State selectedCategory: string = EXPENSE_CATEGORIES[0];
  @State remark: string = '';
  @State showSuccess: boolean = false;
  @State selectedType: '消费' | '收入' = '消费';
  @State showAmountError: boolean = false;
  @State useAI: boolean = false;
  @State aiLoading: boolean = false;
  @State aiResult: string = '';
  @State submitting: boolean = false;
  onSaved?: () => void;

  aboutToAppear(): void {
    this.selectedCategory = this.selectedType === '消费' ? EXPENSE_CATEGORIES[0] : INCOME_CATEGORIES[0];
  }

  onTypeChange(newType: '消费' | '收入'): void {
    this.selectedType = newType;
    this.selectedCategory = newType === '消费' ? EXPENSE_CATEGORIES[0] : INCOME_CATEGORIES[0];
    this.useAI = false;
    this.aiResult = '';
  }

  async doAddExpense(): Promise<void> {
    const amt = parseFloat(this.amount);
    if (isNaN(amt) || amt <= 0) {
      this.showAmountError = true;
      return;
    }
    this.showAmountError = false;
    this.submitting = true;

    let category = this.selectedCategory;
    let message = '';

    try {
      if (this.useAI && this.selectedType === '消费') {
        this.aiLoading = true;
        this.aiResult = '';
        const aiResp = await aiClassify(this.selectedType, amt, this.remark.trim());
        this.aiLoading = false;

        if (aiResp.code === 200 && aiResp.category) {
          category = aiResp.category;
          message = aiResp.message || '';
          this.aiResult = `AI识别: ${category} — ${message || ''}`;
          this.selectedCategory = category;
          const billResult = await submitBill(this.selectedType, category, amt, this.remark.trim());
          if (billResult.code !== 200) {
            promptAction.showToast({ message: '服务器同步失败，已保存到本地' });
          }
        } else {
          this.aiResult = aiResp.msg || 'AI分类失败,请手动选择';
          this.submitting = false;
          return;
        }
      } else {
        submitBill(this.selectedType, category, amt, this.remark.trim())
          .then(result => {
            if (result.code !== 200) {
              promptAction.showToast({ message: '服务器同步失败，已保存到本地' });
            }
          })
          .catch(() => promptAction.showToast({ message: '网络不可用，已保存到本地' }));
      }

      const item: ExpenseItem = {
        id: generateId(),
        type: this.selectedType,
        category: category,
        amount: amt,
        remark: this.remark.trim(),
        message: message,
        createTime: new Date().toISOString()
      };

      await addToStore(item);
      this.onSaved?.();

      this.amount = '';
      this.remark = '';
      this.aiResult = '';
      this.useAI = false;
      this.selectedCategory = this.selectedType === '消费' ? EXPENSE_CATEGORIES[0] : INCOME_CATEGORIES[0];
      this.showSuccess = true;
      setTimeout(() => { this.showSuccess = false; }, 1800);
    } finally {
      this.submitting = false;
    }
  }

  build() {
    Stack() {
      Scroll() {
        Column() {
          Row() {
            Button('消费')
              .fontSize(14)
              .fontWeight(FontWeight.Medium)
              .layoutWeight(1)
              .height(42)
              .borderRadius(21)
              .backgroundColor(this.selectedType === '消费' ? '#E85545' : 'rgba(255,255,255,0.7)')
              .fontColor(this.selectedType === '消费' ? '#FFFFFF' : '#86909C')
              .onClick(() => { this.onTypeChange('消费'); })

            Button('收入')
              .fontSize(14)
              .fontWeight(FontWeight.Medium)
              .layoutWeight(1)
              .height(42)
              .borderRadius(21)
              .backgroundColor(this.selectedType === '收入' ? '#2BA471' : 'rgba(255,255,255,0.7)')
              .fontColor(this.selectedType === '收入' ? '#FFFFFF' : '#86909C')
              .onClick(() => { this.onTypeChange('收入'); })
              .margin({ left: 10 })
          }
          .width('100%')
          .padding({ left: 16, right: 16 })
          .margin({ top: 20, bottom: 20 })

          Row() {
            Text('¥')
              .fontSize(32)
              .fontWeight(FontWeight.Bold)
              .fontColor(this.selectedType === '消费' ? '#E85545' : '#2BA471')

            TextInput({ text: this.amount, placeholder: '0.00' })
              .fontSize(36)
              .fontWeight(FontWeight.Bold)
              .type(InputType.Number)
              .maxLength(10)
              .backgroundColor('transparent')
              .layoutWeight(1)
              .onChange((value: string) => {
                const filtered = value.replace(/[^\d.]/g, '');
                const parts = filtered.split('.');
                if (parts.length > 2) {
                  this.amount = parts[0] + '.' + parts.slice(1).join('');
                } else {
                  this.amount = filtered;
                }
                this.showAmountError = false;
              })
          }
          .width('100%')
          .padding({ left: 16, right: 16 })

          if (this.showAmountError) {
            Text('请输入有效的金额')
              .fontSize(12)
              .fontColor('#E85545')
              .width('100%')
              .padding({ left: 16, top: 4 })
          }

          Divider().margin({ top: 18, bottom: 18 }).color('#E5E6EB')

          Column() {
            if (this.selectedType === '消费') {
              Row() {
                Text('选择类别')
                  .fontSize(13)
                  .fontColor('#86909C')

                Blank()

                Row() {
                  Text('AI 智能分类')
                    .fontSize(12)
                    .fontColor(this.useAI ? '#4F6EF7' : '#86909C')
                    .margin({ right: 6 })

                  Toggle({ type: ToggleType.Switch, isOn: this.useAI })
                    .selectedColor('#4F6EF7')
                    .onChange((on: boolean) => {
                      this.useAI = on;
                      this.aiResult = '';
                    })
                }
              }
              .width('100%')
              .margin({ bottom: 10 })

              if (this.useAI) {
                TextInput({ text: this.remark, placeholder: '输入消费内容，AI 自动识别分类...' })
                  .height(48)
                  .width('100%')
                  .backgroundColor('rgba(79,110,247,0.06)')
                  .borderRadius(12)
                  .padding({ left: 14, right: 14 })
                  .border({ width: 1, color: 'rgba(79,110,247,0.2)' })
                  .onChange((value: string) => { this.remark = value; })

                if (this.aiLoading) {
                  Row() {
                    LoadingProgress().width(16).height(16).color('#4F6EF7')
                    Text('AI 正在识别...')
                      .fontSize(12)
                      .fontColor('#4F6EF7')
                      .margin({ left: 8 })
                  }
                  .margin({ top: 12 })
                }

                if (this.aiResult) {
                  Row() {
                    Text(this.aiResult)
                      .fontSize(13)
                      .fontColor('#1D2129')
                      .backgroundColor('rgba(79,110,247,0.08)')
                      .borderRadius(8)
                      .padding({ left: 12, right: 12, top: 8, bottom: 8 })
                  }
                  .width('100%')
                  .margin({ top: 10 })
                }
              } else {
                Grid() {
                  ForEach(EXPENSE_CATEGORIES, (cat: string) => {
                    GridItem() {
                      Column() {
                        Circle({ width: 42, height: 42 })
                          .fill(CATEGORY_COLORS[cat] || '#8899A6')
                          .opacity(this.selectedCategory === cat ? 1.0 : 0.4)
                          .shadow(this.selectedCategory === cat ?
                            { radius: 8, color: (CATEGORY_COLORS[cat] || '#8899A6') + '50', offsetY: 3 } :
                            { radius: 0, color: 'transparent', offsetY: 0 })

                        Text(cat)
                          .fontSize(11)
                          .fontWeight(this.selectedCategory === cat ? FontWeight.Medium : FontWeight.Normal)
                          .fontColor(this.selectedCategory === cat ? '#1D2129' : '#86909C')
                          .margin({ top: 6 })
                      }
                      .padding({ top: 5, bottom: 5, left: 2, right: 2 })
                    }
                    .onClick(() => { this.selectedCategory = cat; })
                  })
                }
                .columnsTemplate('1fr 1fr 1fr 1fr')
                .rowsGap(8)
                .columnsGap(8)
                .width('100%')
              }
            }

            if (this.selectedType === '收入') {
              Text('收入类别')
                .fontSize(13)
                .fontColor('#86909C')
                .width('100%')
                .margin({ bottom: 10 })

              Grid() {
                ForEach(INCOME_CATEGORIES, (cat: string) => {
                  GridItem() {
                    Column() {
                      Circle({ width: 42, height: 42 })
                        .fill(CATEGORY_COLORS[cat] || '#546E7A')
                        .opacity(this.selectedCategory === cat ? 1.0 : 0.4)
                        .shadow(this.selectedCategory === cat ?
                          { radius: 8, color: (CATEGORY_COLORS[cat] || '#546E7A') + '50', offsetY: 3 } :
                          { radius: 0, color: 'transparent', offsetY: 0 })

                      Text(cat)
                        .fontSize(11)
                        .fontWeight(this.selectedCategory === cat ? FontWeight.Medium : FontWeight.Normal)
                        .fontColor(this.selectedCategory === cat ? '#1D2129' : '#86909C')
                        .margin({ top: 6 })
                    }
                    .padding({ top: 5, bottom: 5, left: 2, right: 2 })
                  }
                  .onClick(() => { this.selectedCategory = cat; })
                })
              }
              .columnsTemplate('1fr 1fr 1fr 1fr')
              .rowsGap(8)
              .columnsGap(8)
              .width('100%')
            }

            if (!this.useAI || this.selectedType === '收入') {
              Divider().margin({ top: 18, bottom: 14 }).color('#E5E6EB')

              TextInput({ text: this.remark, placeholder: '添加备注（选填）' })
                .height(48)
                .width('100%')
                .backgroundColor('rgba(0,0,0,0.03)')
                .borderRadius(12)
                .padding({ left: 14, right: 14 })
                .onChange((value: string) => { this.remark = value; })
            }

            Blank()
          }
          .height(380)
          .width('100%')

          Button(this.submitting ? '添加中...' : '确认添加')
            .width('100%')
            .height(50)
            .fontSize(16)
            .fontWeight(FontWeight.Bold)
            .backgroundColor(this.selectedType === '消费' ? '#E85545' : '#2BA471')
            .fontColor('#FFFFFF')
            .borderRadius(25)
            .margin({ top: 24 })
            .shadow({ radius: 10, color: this.selectedType === '消费' ? 'rgba(232,85,69,0.3)' : 'rgba(43,164,113,0.3)', offsetY: 4 })
            .enabled(!this.submitting)
            .onClick(() => { this.doAddExpense(); })

          Blank().height(20)
        }
        .width('100%')
        .padding({ left: 16, right: 16 })
      }
      .scrollBar(BarState.Off)

      if (this.showSuccess) {
        Column() {
          Text('✓ 添加成功')
            .fontSize(15)
            .fontColor('#FFFFFF')
            .padding({ left: 28, right: 28, top: 12, bottom: 12 })
            .backgroundColor(this.selectedType === '消费' ? '#E85545' : '#2BA471')
            .borderRadius(22)
            .shadow({ radius: 12, color: 'rgba(0,0,0,0.15)', offsetY: 4 })
        }
        .position({ bottom: 50 })
        .transition(TransitionEffect.OPACITY.animation({ duration: 300, curve: Curve.EaseOut }))
      }
    }
    .width('100%')
    .height('100%')
  }
}
