import { bluetoothService, BluetoothDevice } from '../model/BluetoothService';
import { ExpenseItem } from '../model/ExpenseModel';
import { promptAction } from '@kit.ArkUI';

interface PairedDevice {
  device: BluetoothDevice;
  connected: boolean;
  lastSync: string;
  syncedCount: number;
}

@Component
export struct DevicePage {
  @Consume expenses: ExpenseItem[] = [];
  @State devices: PairedDevice[] = [];
  @State bluetoothOn: boolean = false;
  @State loading: boolean = false;
  @State autoSync: boolean = false;
  @State syncExpense: boolean = true;
  @State syncIncome: boolean = true;
  @State showSyncResult: boolean = false;
  @State syncMessage: string = '';
  onDataChanged?: () => void;

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

  loadDeviceList(): void {
    this.bluetoothOn = bluetoothService.isBluetoothEnabled();
    if (!this.bluetoothOn) return;

    const paired = bluetoothService.getPairedDevices();
    const result: PairedDevice[] = [];
    for (const d of paired) {
      result.push({
        device: d,
        connected: false,
        lastSync: '从未同步',
        syncedCount: 0
      });
    }
    this.devices = result;
  }

  async refreshDevices(): Promise<void> {
    this.loading = true;
    this.loadDeviceList();
    this.loading = false;
    if (!this.bluetoothOn) {
      promptAction.showToast({ message: '蓝牙未开启' });
    } else if (this.devices.length === 0) {
      promptAction.showToast({ message: '未发现配对设备' });
    }
  }

  async connectDevice(device: PairedDevice): Promise<void> {
    if (device.connected) return;
    promptAction.showToast({ message: `正在连接 ${device.device.deviceName}...` });
    device.connected = true;
  }

  async syncToDevice(device: PairedDevice): Promise<void> {
    if (this.expenses.length === 0) {
      promptAction.showToast({ message: '没有可同步的数据' });
      return;
    }
    if (!device.connected) {
      await this.connectDevice(device);
    }

    let data = this.expenses;
    if (!this.syncExpense) {
      data = data.filter(item => item.type !== '消费');
    }
    if (!this.syncIncome) {
      data = data.filter(item => item.type !== '收入');
    }

    this.loading = true;
    const now = new Date();
    bluetoothService.connectAndSend(
      device.device.deviceId,
      data,
      (success: boolean, _data?: ExpenseItem[], error?: string) => {
        this.loading = false;
        if (success) {
          device.lastSync = `${now.getMonth() + 1}/${now.getDate()} ${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
          device.syncedCount = data.length;
          this.syncMessage = `已同步 ${data.length} 条记录`;
          this.showSyncResult = true;
          setTimeout(() => { this.showSyncResult = false; }, 2000);
        } else {
          promptAction.showToast({ message: error || '同步失败' });
        }
      },
      (current: number, total: number) => {
        this.syncMessage = `传输中 ${Math.round((current / total) * 100)}%`;
        this.showSyncResult = true;
      }
    );
  }

  getSyncStatus(device: PairedDevice): string {
    if (device.syncedCount === 0) return '未同步';
    return `已同步 ${device.syncedCount} 条`;
  }

  build() {
    Column() {
      if (this.showSyncResult) {
        Row() {
          Text(this.syncMessage)
            .fontSize(13)
            .fontColor('#FFFFFF')
            .padding({ left: 16, right: 16, top: 10, bottom: 10 })
            .backgroundColor('#4F6EF7')
            .borderRadius(20)
        }
        .width('100%')
        .justifyContent(FlexAlign.Center)
        .margin({ top: 12, bottom: 4 })
        .transition(TransitionEffect.OPACITY.animation({ duration: 300 }))
      }

      Scroll() {
        Column() {
          // Bluetooth status bar
          Row() {
            Circle({ width: 8, height: 8 })
              .fill(this.bluetoothOn ? '#2BA471' : '#C9CDD4')
              .margin({ right: 8 })

            Text(this.bluetoothOn ? '蓝牙已开启' : '蓝牙未开启')
              .fontSize(13)
              .fontColor(this.bluetoothOn ? '#2BA471' : '#86909C')

            Blank()

            Button('刷新')
              .fontSize(12)
              .height(30)
              .backgroundColor('transparent')
              .fontColor('#4F6EF7')
              .padding({ left: 12, right: 12 })
              .onClick(() => { this.refreshDevices(); })
          }
          .width('100%')
          .backgroundColor('#FFFFFF')
          .borderRadius(12)
          .padding({ left: 16, right: 8, top: 10, bottom: 10 })
          .margin({ top: 16, bottom: 12, left: 16, right: 16 })

          // Device list
          if (!this.bluetoothOn) {
            Column() {
              Text('📡')
                .fontSize(36)
                .margin({ bottom: 10 })
              Text('请先开启蓝牙')
                .fontSize(14)
                .fontColor('#86909C')
              Button('开启蓝牙')
                .fontSize(13)
                .height(36)
                .backgroundColor('#4F6EF7')
                .fontColor('#FFFFFF')
                .borderRadius(18)
                .padding({ left: 24, right: 24 })
                .margin({ top: 14 })
                .onClick(() => {
                  bluetoothService.enableBluetooth();
                  bluetoothService.waitForBluetoothOn(10000).then((ok) => {
                    if (ok) {
                      this.bluetoothOn = true;
                      this.loadDeviceList();
                    } else {
                      promptAction.showToast({ message: '无法开启蓝牙' });
                    }
                  });
                })
            }
            .width('100%')
            .padding({ top: 40, bottom: 40 })
          } else if (this.devices.length === 0) {
            Column() {
              Text('⌚')
                .fontSize(40)
                .margin({ bottom: 10 })
              Text('暂无配对设备')
                .fontSize(14)
                .fontColor('#86909C')
              Text('请在系统蓝牙设置中配对您的手表')
                .fontSize(12)
                .fontColor('#C9CDD4')
                .margin({ top: 6 })
            }
            .width('100%')
            .padding({ top: 30, bottom: 30 })
          } else {
            Text('已配对设备')
              .fontSize(13)
              .fontColor('#86909C')
              .width('100%')
              .padding({ left: 16, bottom: 8 })

            List() {
              ForEach(this.devices, (device: PairedDevice) => {
                ListItem() {
                  Column() {
                    Row() {
                      Circle({ width: 46, height: 46 })
                        .fill('rgba(79,110,247,0.1)')
                        .border({ width: 2, color: device.connected ? '#2BA471' : '#E5E6EB' })

                      Column() {
                        Text(device.device.deviceName)
                          .fontSize(15)
                          .fontWeight(FontWeight.Medium)
                          .fontColor('#1D2129')

                        Row() {
                          Circle({ width: 6, height: 6 })
                            .fill(device.connected ? '#2BA471' : '#C9CDD4')
                            .margin({ right: 4 })
                          Text(device.connected ? '已连接' : '未连接')
                            .fontSize(11)
                            .fontColor(device.connected ? '#2BA471' : '#C9CDD4')
                        }
                        .margin({ top: 3 })
                      }
                      .margin({ left: 12 })
                      .layoutWeight(1)
                      .alignItems(HorizontalAlign.Start)

                      Button(this.loading ? '同步中...' : '同步')
                        .fontSize(12)
                        .height(32)
                        .backgroundColor('#4F6EF7')
                        .fontColor('#FFFFFF')
                        .borderRadius(16)
                        .padding({ left: 14, right: 14 })
                        .enabled(!this.loading)
                        .onClick(() => { this.syncToDevice(device); })
                    }
                    .width('100%')

                    Row() {
                      Text(`上次同步: ${device.lastSync}`)
                        .fontSize(11)
                        .fontColor('#A9AEB8')

                      Blank()

                      Text(this.getSyncStatus(device))
                        .fontSize(11)
                        .fontColor(device.syncedCount > 0 ? '#2BA471' : '#A9AEB8')
                    }
                    .width('100%')
                    .margin({ top: 10, left: 58 })
                  }
                  .width('100%')
                  .backgroundColor('#FFFFFF')
                  .borderRadius(14)
                  .padding(14)
                  .margin({ bottom: 10 })
                }
              })
            }
            .width('100%')
            .padding({ left: 16, right: 16 })
            .scrollBar(BarState.Off)
          }

          // Sync settings
          Text('同步设置')
            .fontSize(15)
            .fontWeight(FontWeight.Bold)
            .fontColor('#1D2129')
            .width('100%')
            .padding({ left: 16, top: 24, bottom: 10 })

          Column() {
            this.SettingItem('发送消费记录', this.syncExpense, (on: boolean) => { this.syncExpense = on; })
            Divider().color('#F2F3F5').margin({ left: 16 })
            this.SettingItem('发送收入记录', this.syncIncome, (on: boolean) => { this.syncIncome = on; })
          }
          .width('100%')
          .backgroundColor('#FFFFFF')
          .borderRadius(14)
          .padding({ top: 4, bottom: 4 })
          .margin({ left: 16, right: 16 })

          // Watch app settings
          Text('手表应用')
            .fontSize(15)
            .fontWeight(FontWeight.Bold)
            .fontColor('#1D2129')
            .width('100%')
            .padding({ left: 16, top: 20, bottom: 10 })

          Column() {
            this.SettingItem('手表端显示消费明细', true, (_on: boolean) => {})
            Divider().color('#F2F3F5').margin({ left: 16 })
            this.SettingItem('手表端显示收入明细', true, (_on: boolean) => {})
            Divider().color('#F2F3F5').margin({ left: 16 })
            this.SettingItem('手表端震动提醒', false, (_on: boolean) => {})
          }
          .width('100%')
          .backgroundColor('#FFFFFF')
          .borderRadius(14)
          .padding({ top: 4, bottom: 4 })
          .margin({ left: 16, right: 16, bottom: 24 })
        }
        .width('100%')
      }
      .scrollBar(BarState.Off)
      .layoutWeight(1)
    }
    .width('100%')
    .height('100%')
  }

  @Builder
  SettingItem(label: string, checked: boolean, onChange: (on: boolean) => void) {
    Row() {
      Text(label)
        .fontSize(14)
        .fontColor('#1D2129')
        .layoutWeight(1)

      Toggle({ type: ToggleType.Switch, isOn: checked })
        .selectedColor('#4F6EF7')
        .onChange(onChange)
    }
    .width('100%')
    .padding({ left: 16, right: 16, top: 12, bottom: 12 })
  }
}
