import { ExpenseItem, EXPENSE_CATEGORIES, INCOME_CATEGORIES, CATEGORY_COLORS, loadExpenses } from '../model/ExpenseModel';

@Component
export struct Overview {
  @Consume @Watch('onExpensesChange') expenses: ExpenseItem[] = [];
  @State totalIncome: number = 0;
  @State totalExpense: number = 0;
  @State categoryTotals: Record<string, number> = {};
  @State incomeTotals: Record<string, number> = {};
  @State loaded: boolean = false;

  aboutToAppear(): void {
    this.calcTotals();
  }

  onExpensesChange(): void {
    this.calcTotals();
    this.loaded = true;
  }

  async refreshFromStore(): Promise<void> {
    this.expenses = await loadExpenses();
    this.calcTotals();
  }

  calcTotals(): void {
    let income = 0;
    let expense = 0;
    const catMap: Record<string, number> = {};
    for (const cat of EXPENSE_CATEGORIES) {
      catMap[cat] = 0;
    }
    const incMap: Record<string, number> = {};
    for (const cat of INCOME_CATEGORIES) {
      incMap[cat] = 0;
    }

    const now = new Date();
    const thisMonth = now.getMonth();
    const thisYear = now.getFullYear();

    for (const item of this.expenses) {
      const d = new Date(item.createTime);
      if (isNaN(d.getTime())) continue;
      if (d.getFullYear() === thisYear && d.getMonth() === thisMonth) {
        if (item.type === '收入') {
          income += item.amount || 0;
          if (incMap[item.category] !== undefined) {
            incMap[item.category] += item.amount || 0;
          } else {
            incMap['其他收入'] += item.amount || 0;
          }
        } else {
          expense += item.amount || 0;
          if (catMap[item.category] !== undefined) {
            catMap[item.category] += item.amount || 0;
          } else {
            catMap['其他'] += item.amount || 0;
          }
        }
      }
    }

    this.totalIncome = income;
    this.totalExpense = expense;
    this.categoryTotals = catMap;
    this.incomeTotals = incMap;
  }

  build() {
    Column() {
      Row() {
        this.SummaryCard('总收入', this.totalIncome, '#2BA471')

        this.SummaryCard('总支出', this.totalExpense, '#E85545')

        this.SummaryCard('结余', this.totalIncome - this.totalExpense, '#4F6EF7')

        Column() {
          Button('刷新')
            .fontSize(12)
            .height(32)
            .backgroundColor('#4F6EF7')
            .fontColor('#FFFFFF')
            .borderRadius(16)
            .padding({ left: 12, right: 12 })
            .onClick(() => { this.refreshFromStore(); })
        }
        .justifyContent(FlexAlign.Center)
        .padding({ left: 4, right: 8 })
      }
      .width('100%')
      .justifyContent(FlexAlign.SpaceEvenly)
      .padding({ top: 16, bottom: 6 })

      if (!this.loaded) {
        Column() {
          LoadingProgress().width(40).height(40)
        }
        .width('100%')
        .layoutWeight(1)
        .justifyContent(FlexAlign.Center)
      } else {
        Scroll() {
          Column() {
            if (this.totalExpense > 0) {
              Row() {
                Text('消费分类')
                  .fontSize(15)
                  .fontWeight(FontWeight.Bold)
                  .fontColor('#1D2129')
              }
              .width('100%')
              .padding({ left: 16, top: 12, bottom: 8 })

              Grid() {
                ForEach(EXPENSE_CATEGORIES.filter(c => (this.categoryTotals[c] || 0) > 0).sort((a, b) => (this.categoryTotals[b] || 0) - (this.categoryTotals[a] || 0)),
                  (cat: string) => {
                    GridItem() {
                      this.CategoryCard(cat, this.categoryTotals[cat] || 0, false)
                    }
                  })
              }
              .columnsTemplate('1fr 1fr')
              .columnsGap(8)
              .rowsGap(8)
              .width('100%')
              .padding({ left: 16, right: 16 })
            }

            if (this.totalIncome > 0) {
              Row() {
                Text('收入来源')
                  .fontSize(15)
                  .fontWeight(FontWeight.Bold)
                  .fontColor('#1D2129')
              }
              .width('100%')
              .padding({ left: 16, top: 16, bottom: 8 })

              Grid() {
                ForEach(INCOME_CATEGORIES.filter(c => (this.incomeTotals[c] || 0) > 0).sort((a, b) => (this.incomeTotals[b] || 0) - (this.incomeTotals[a] || 0)),
                  (cat: string) => {
                    GridItem() {
                      this.CategoryCard(cat, this.incomeTotals[cat] || 0, true)
                    }
                  })
              }
              .columnsTemplate('1fr 1fr')
              .columnsGap(8)
              .rowsGap(8)
              .width('100%')
              .padding({ left: 16, right: 16 })
            }

            if (this.totalExpense === 0 && this.totalIncome === 0) {
              Column() {
                Text('💰')
                  .fontSize(40)
                  .margin({ bottom: 10 })
                Text('本月暂无记录')
                  .fontSize(14)
                  .fontColor('#86909C')
              }
              .width('100%')
              .padding({ top: 60 })
            }

            Blank().height(16)
          }
        }
        .layoutWeight(1)
        .scrollBar(BarState.Off)
      }
    }
    .width('100%')
    .height('100%')
  }

  @Builder
  SummaryCard(label: string, amount: number, color: string) {
    Column() {
      Stack() {
        Progress({ value: 100, total: 100, type: ProgressType.Ring })
          .width(72)
          .height(72)
          .color('#E5E6EB')
          .style({ strokeWidth: 4, scaleCount: 1, scaleWidth: 0 })

        Progress({ value: this.getRingProgress(amount, label), total: 100, type: ProgressType.Ring })
          .width(72)
          .height(72)
          .color(color)
          .style({ strokeWidth: 4, scaleCount: 1, scaleWidth: 0 })

        Column() {
          Text((amount || 0).toFixed(0))
            .fontSize(15)
            .fontWeight(FontWeight.Bold)
            .fontColor('#1D2129')
          Text('¥')
            .fontSize(9)
            .fontColor('#86909C')
        }
      }

      Text(label)
        .fontSize(11)
        .fontColor('#86909C')
        .margin({ top: 5 })
    }
  }

  getRingProgress(amount: number, label: string): number {
    const amt = amount || 0;
    if (label === '总收入') {
      return this.totalIncome > 0 ? Math.min(100, (amt / this.totalIncome) * 100) : 0;
    } else if (label === '总支出') {
      return this.totalExpense > 0 ? Math.min(100, (amt / this.totalExpense) * 100) : 0;
    }
    const total = (this.totalIncome || 0) + (this.totalExpense || 0);
    if (total === 0) return 0;
    return Math.min(100, (amt / total) * 100);
  }

  @Builder
  CategoryCard(cat: string, amount: number, isIncome: boolean) {
    Column() {
      Row() {
        Circle({ width: 10, height: 10 })
          .fill(CATEGORY_COLORS[cat] || '#8899A6')
        Text(cat)
          .fontSize(13)
          .fontWeight(FontWeight.Medium)
          .fontColor('#4E5969')
          .margin({ left: 8 })
        Blank()
      }
      .width('100%')

      Text(`${isIncome ? '+' : '-'}¥${(amount || 0).toFixed(2)}`)
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .fontColor(isIncome ? '#2BA471' : '#E85545')
        .margin({ top: 10 })

      Progress({
        value: amount,
        total: isIncome ? (this.totalIncome || 1) : (this.totalExpense || 1),
        type: ProgressType.Linear
      })
        .width('100%')
        .height(4)
        .color(CATEGORY_COLORS[cat] || '#8899A6')
        .style({ strokeRadius: 2 })
        .margin({ top: 8 })
    }
    .width('100%')
    .backgroundColor('#FFFFFF')
    .borderRadius(14)
    .padding(14)
    .shadow({ radius: 8, color: 'rgba(0,0,0,0.04)', offsetY: 2 })
  }
}
