import { promptAction } from '@kit.ArkUI';
import { ExpenseItem, INCOME_CATEGORIES, CATEGORY_COLORS, saveExpenses } from '../model/ExpenseModel';

@Component
export struct ExpenseRecords {
  @Consume expenses: ExpenseItem[] = [];
  @Consume filterCategory: string = '';
  deleteTargetId: string = '';
  onDataChanged?: () => void;
  onClearFilter?: () => void;

  confirmDelete(id: string): void {
    this.deleteTargetId = id;
    promptAction.showDialog({
      title: '确认删除',
      message: '删除后无法恢复，确定要删除这条记录吗？',
      buttons: [
        { text: '取消', color: '#86909C' },
        { text: '删除', color: '#E85545' }
      ]
    }).then(async (result: promptAction.ShowDialogSuccessResponse) => {
      if (result.index === 1) {
        await this.performDelete();
      }
      this.deleteTargetId = '';
    });
  }

  async performDelete(): Promise<void> {
    const id = this.deleteTargetId;
    const updated = this.expenses.filter((r: ExpenseItem) => r.id !== id);
    await saveExpenses(updated);
    this.onDataChanged?.();
  }

  formatDate(iso: string): string {
    const d = new Date(iso);
    if (isNaN(d.getTime())) return '--';
    const month = (d.getMonth() + 1).toString().padStart(2, '0');
    const day = d.getDate().toString().padStart(2, '0');
    const hour = d.getHours().toString().padStart(2, '0');
    const min = d.getMinutes().toString().padStart(2, '0');
    return `${month}-${day} ${hour}:${min}`;
  }

  getFilteredRecords(): ExpenseItem[] {
    if (this.filterCategory === '') return this.expenses;
    if (this.filterCategory === '收入') return this.expenses.filter(item => item.type === '收入');
    if (INCOME_CATEGORIES.indexOf(this.filterCategory) >= 0) {
      return this.expenses.filter(item => item.type === '收入' && item.category === this.filterCategory);
    }
    return this.expenses.filter(item => item.type === '消费' && item.category === this.filterCategory);
  }

  groupByDate(): Map<string, ExpenseItem[]> {
    const map = new Map<string, ExpenseItem[]>();
    for (const item of this.getFilteredRecords()) {
      const d = new Date(item.createTime);
      if (isNaN(d.getTime())) continue;
      const key = `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
      if (!map.has(key)) map.set(key, []);
      map.get(key)!.push(item);
    }
    return map;
  }

  getDayTotal(items: ExpenseItem[]): string {
    let expense = 0;
    let income = 0;
    for (const item of items) {
      if (item.type === '消费') expense += item.amount || 0;
      else income += item.amount || 0;
    }
    if (income > 0 && expense > 0) return `收 ¥${income.toFixed(2)}  支 ¥${expense.toFixed(2)}`;
    if (income > 0) return `收入 ¥${income.toFixed(2)}`;
    return `支出 ¥${expense.toFixed(2)}`;
  }

  getCategoryColor(item: ExpenseItem): string {
    return CATEGORY_COLORS[item.category] || (item.type === '收入' ? '#2BA471' : '#8899A6');
  }

  getFilterLabel(): string {
    if (this.filterCategory === '收入') return '全部收入';
    return this.filterCategory;
  }

  getDisplayCategory(item: ExpenseItem): string {
    if (item.category && item.category.length > 0) return item.category;
    return item.type === '收入' ? '收入' : '其他';
  }

  build() {
    Column() {
      if (this.filterCategory !== '') {
        Row() {
          Button('← 返回')
            .fontSize(12)
            .height(32)
            .backgroundColor('transparent')
            .fontColor('#4F6EF7')
            .padding({ left: 8, right: 12 })
            .onClick(() => { this.onClearFilter?.(); })

          Text(this.getFilterLabel())
            .fontSize(15)
            .fontWeight(FontWeight.Bold)
            .fontColor('#1D2129')

          Blank()

          Text(`${this.getFilteredRecords().length} 条`)
            .fontSize(12)
            .fontColor('#86909C')
            .padding({ right: 16 })
        }
        .width('100%')
        .height(48)
        .backgroundColor('rgba(255,255,255,0.85)')
        .padding({ left: 4 })
      }

      if (this.getFilteredRecords().length === 0) {
        Column() {
          Text('📋')
            .fontSize(48)
            .margin({ bottom: 12 })
          Text(this.filterCategory !== '' ? '暂无该类记录' : '暂无消费记录')
            .fontSize(15)
            .fontColor('#86909C')
        }
        .width('100%')
        .layoutWeight(1)
        .justifyContent(FlexAlign.Center)
      } else {
        List() {
          ForEach(Array.from(this.groupByDate().entries()),
            (entry: [string, ExpenseItem[]]) => {
              ListItem() {
                Column() {
                  Row() {
                    Text(entry[0])
                      .fontSize(13)
                      .fontWeight(FontWeight.Bold)
                      .fontColor('#86909C')

                    Blank()

                    Text(this.getDayTotal(entry[1]))
                      .fontSize(11)
                      .fontColor('#A9AEB8')
                  }
                  .width('100%')
                  .padding({ left: 16, right: 16, top: 12, bottom: 4 })

                  ForEach(entry[1], (item: ExpenseItem) => {
                    ListItem() {
                      this.RecordRow(item)
                    }
                  })
                }
                .width('100%')
                .padding({ bottom: 8 })
              }
            },
            (entry: [string, ExpenseItem[]]) => entry[0]
          )
        }
        .width('100%')
        .layoutWeight(1)
        .scrollBar(BarState.Off)
        .divider({ strokeWidth: 0.5, color: '#E5E6EB' })
      }
    }
    .width('100%')
    .height('100%')
  }

  @Builder
  RecordRow(item: ExpenseItem) {
    Row() {
      Circle({ width: 40, height: 40 })
        .fill(this.getCategoryColor(item))

      Column() {
        Row() {
          Text(this.getDisplayCategory(item))
            .fontSize(14)
            .fontWeight(FontWeight.Medium)
            .fontColor('#1D2129')

          if (item.message) {
            Text(item.message)
              .fontSize(10)
              .fontColor('#4F6EF7')
              .backgroundColor('rgba(79,110,247,0.08)')
              .borderRadius(6)
              .padding({ left: 6, right: 6, top: 2, bottom: 2 })
              .margin({ left: 6 })
              .maxLines(1)
          }
        }

        if (item.remark) {
          Text(item.remark)
            .fontSize(12)
            .fontColor('#86909C')
            .maxLines(1)
            .textOverflow({ overflow: TextOverflow.Ellipsis })
        }
      }
      .margin({ left: 12 })
      .layoutWeight(1)
      .alignItems(HorizontalAlign.Start)

      Column() {
        Text(`${item.type === '消费' ? '-' : '+'}¥${(item.amount || 0).toFixed(2)}`)
          .fontSize(16)
          .fontWeight(FontWeight.Bold)
          .fontColor(item.type === '消费' ? '#E85545' : '#2BA471')

        Text(this.formatDate(item.createTime))
          .fontSize(10)
          .fontColor('#A9AEB8')
      }
      .alignItems(HorizontalAlign.End)
    }
    .width('100%')
    .padding({ left: 16, right: 16, top: 10, bottom: 10 })
    .backgroundColor('#FFFFFF')
    .borderRadius(12)
    .shadow({ radius: 6, color: 'rgba(0,0,0,0.03)', offsetY: 1 })
    .margin({ left: 16, right: 16, top: 3, bottom: 3 })
    .gesture(
      LongPressGesture()
        .onAction(() => {
          this.confirmDelete(item.id);
        })
    )
  }
}
