import { bluetoothService, BluetoothDevice, TransferProgressCallback, TransferResultCallback } from '../model/BluetoothService';
import { ExpenseItem, loadExpenses, saveExpenses } from '../model/ExpenseModel';

enum TransferState {
  IDLE,
  SELECTING,
  SCANNING,
  CONNECTING,
  TRANSFERRING,
  WAITING,
  COMPLETE,
  ERROR
}

@Component
export struct BluetoothTransfer {
  @State state: TransferState = TransferState.IDLE;
  @State stateMessage: string = '';
  @State errorMessage: string = '';
  @State discoveredDevices: BluetoothDevice[] = [];
  @State selectedDevice: BluetoothDevice | null = null;
  @State transferProgress: number = 0;
  @State transferTotal: number = 0;
  @State receivedRecords: ExpenseItem[] = [];
  @State receivedCount: number = 0;
  @Consume expenses: ExpenseItem[] = [];
  @State selectedIds: Set<string> = new Set();
  @State selectedCount: number = 0;
  @State bluetoothReady: boolean = false;
  onDataChanged?: () => void;

  aboutToAppear(): void {
    if (!this.expenses) {
      this.expenses = [];
    }
    this.bluetoothReady = bluetoothService.isBluetoothEnabled();
  }

  onDismiss(): void {
    bluetoothService.destroy();
    this.state = TransferState.IDLE;
  }

  async ensureBluetooth(): Promise<boolean> {
    if (this.bluetoothReady) return true;
    this.stateMessage = '正在打开蓝牙...';
    bluetoothService.enableBluetooth();
    const ok = await bluetoothService.waitForBluetoothOn(10000);
    if (ok) {
      this.bluetoothReady = true;
      this.stateMessage = '';
      return true;
    }
    this.errorMessage = '无法打开蓝牙，请确认蓝牙权限已开启';
    this.state = TransferState.ERROR;
    return false;
  }

  // ===== 发送流程 =====

  async startSend(): Promise<void> {
    if (this.expenses.length === 0) {
      this.errorMessage = '没有可发送的记录';
      this.state = TransferState.ERROR;
      return;
    }
    if (!(await this.ensureBluetooth())) return;
    this.state = TransferState.SELECTING;
    this.selectedIds.clear();
    this.selectedCount = 0;
    this.stateMessage = '选择要发送的记录';
  }

  toggleSelect(id: string): void {
    if (this.selectedIds.has(id)) {
      this.selectedIds.delete(id);
    } else {
      this.selectedIds.add(id);
    }
    this.selectedCount = this.selectedIds.size;
  }

  selectAll(): void {
    if (this.selectedIds.size === this.expenses.length) {
      this.selectedIds.clear();
      this.selectedCount = 0;
    } else {
      for (const item of this.expenses) {
        this.selectedIds.add(item.id);
      }
      this.selectedCount = this.selectedIds.size;
    }
  }

  confirmSelection(): void {
    if (this.selectedCount === 0) {
      this.errorMessage = '请至少选择一条记录';
      this.state = TransferState.ERROR;
      return;
    }
    this.discoveredDevices = [];
    this.state = TransferState.SCANNING;
    this.stateMessage = '正在搜索附近的蓝牙设备...';

    bluetoothService.startDiscovery((device: BluetoothDevice) => {
      const exists = this.discoveredDevices.some(d => d.deviceId === device.deviceId);
      if (!exists) {
        this.discoveredDevices = [...this.discoveredDevices, device];
      }
    });

    setTimeout(() => {
      if (this.state === TransferState.SCANNING) {
        bluetoothService.stopDiscovery();
        if (this.discoveredDevices.length === 0) {
          this.errorMessage = '未发现蓝牙设备，请确保对方开启了"接收"模式且蓝牙已打开';
          this.state = TransferState.ERROR;
        }
      }
    }, 12000);
  }

  async sendToDevice(device: BluetoothDevice): Promise<void> {
    this.selectedDevice = device;
    this.state = TransferState.CONNECTING;
    this.stateMessage = `正在连接 ${device.deviceName}...`;

    const selectedData = this.expenses.filter(item => this.selectedIds.has(item.id));

    bluetoothService.connectAndSend(
      device.deviceId,
      selectedData,
      (success: boolean, _data?: ExpenseItem[], error?: string) => {
        if (success) {
          this.state = TransferState.COMPLETE;
          this.stateMessage = `成功发送 ${this.selectedCount} 条记录到 ${device.deviceName}`;
        } else {
          this.errorMessage = error || '发送失败';
          this.state = TransferState.ERROR;
        }
      },
      (current: number, total: number) => {
        this.transferProgress = current;
        this.transferTotal = total;
        this.state = TransferState.TRANSFERRING;
      }
    );
  }

  // ===== 接收流程 =====

  async startReceive(): Promise<void> {
    if (!(await this.ensureBluetooth())) return;
    this.state = TransferState.WAITING;
    this.stateMessage = `等待发送方连接...\n本机名称: ${bluetoothService.getLocalDeviceName()}`;
    this.receivedRecords = [];
    this.receivedCount = 0;

    bluetoothService.startServer(
      (success: boolean, data?: ExpenseItem[], error?: string) => {
        if (success && data) {
          this.receivedRecords = data;
          this.receivedCount = data.length;
          this.state = TransferState.COMPLETE;
          this.stateMessage = `接收完成，共 ${data.length} 条记录`;
        } else {
          this.errorMessage = error || '接收数据失败';
          this.state = TransferState.ERROR;
        }
      },
      (current: number, _total: number) => {
        this.transferProgress = current;
        this.state = TransferState.TRANSFERRING;
      }
    );
  }

  async importReceivedData(): Promise<void> {
    if (this.receivedRecords.length === 0) return;
    const current = await loadExpenses();
    const all = [...this.receivedRecords, ...current];
    await saveExpenses(all);
    this.onDataChanged?.();
    this.onDismiss();
  }

  // ===== 格式化辅助 =====

  formatProgress(): string {
    if (this.transferTotal > 0) {
      const pct = Math.round((this.transferProgress / this.transferTotal) * 100);
      return `${pct}%`;
    }
    if (this.transferProgress > 0) {
      return `${(this.transferProgress / 1024).toFixed(1)} KB`;
    }
    return '';
  }

  getDeviceIcon(index: number): string {
    const icons = ['📱', '💻', '⌚', '🎧'];
    return icons[index % icons.length];
  }

  formatDateShort(iso: string): string {
    const d = new Date(iso);
    if (isNaN(d.getTime())) return '--';
    return `${d.getMonth() + 1}/${d.getDate()}`;
  }

  // ===== 构建 =====

  build() {
    if (this.state === TransferState.IDLE) {
      Column() {
        this.buildBackdrop()
        this.buildIdleView()
      }
      .width('100%').height('100%')
    } else {
      Column() {
        this.buildBackdrop()
        this.buildContentCard()
      }
      .width('100%').height('100%')
    }
  }

  @Builder
  buildBackdrop() {
    Column()
      .width('100%').height('100%')
      .backgroundColor('rgba(0,0,0,0.45)')
      .onClick(() => {
        if (this.state === TransferState.IDLE || this.state === TransferState.COMPLETE || this.state === TransferState.ERROR ||
            this.state === TransferState.WAITING || this.state === TransferState.TRANSFERRING) {
          this.onDismiss();
        }
      })
  }

  @Builder
  buildIdleView() {
    Column() {
      Text('蓝牙传输')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .fontColor('#1D2129')
        .margin({ bottom: 8 })

      Text('将记账数据发送到附近的设备，或从其他设备接收数据')
        .fontSize(13)
        .fontColor('#86909C')
        .textAlign(TextAlign.Center)
        .margin({ bottom: 28 })
        .padding({ left: 20, right: 20 })

      Row() {
        this.buildActionButton('📤', '发送', '#4F6EF7', () => { this.startSend(); })
        this.buildActionButton('📥', '接收', '#2BA471', () => { this.startReceive(); })
      }
      .width('100%')
      .justifyContent(FlexAlign.SpaceEvenly)
    }
    .width('84%')
    .backgroundColor('#FFFFFF')
    .borderRadius(20)
    .padding({ top: 28, bottom: 28, left: 20, right: 20 })
  }

  @Builder
  buildActionButton(icon: string, label: string, color: string, action: () => void) {
    Column() {
      Column() {
        Text(icon).fontSize(36)
        Text(label)
          .fontSize(15)
          .fontWeight(FontWeight.Medium)
          .fontColor('#FFFFFF')
          .margin({ top: 6 })
      }
      .width(110).height(110)
      .borderRadius(18)
      .justifyContent(FlexAlign.Center)
      .backgroundColor(color)
      .shadow({ radius: 12, color: color + '40', offsetY: 4 })
      .onClick(action)
    }
  }

  @Builder
  buildContentCard() {
    Column() {
      this.buildHeader()

      if (this.state === TransferState.SELECTING) {
        this.buildSelectView()
      } else if (this.state === TransferState.SCANNING || this.state === TransferState.CONNECTING || this.state === TransferState.TRANSFERRING) {
        this.buildScanOrTransferView()
      } else if (this.state === TransferState.WAITING) {
        this.buildWaitingView()
      } else if (this.state === TransferState.COMPLETE) {
        this.buildCompleteView()
      } else if (this.state === TransferState.ERROR) {
        this.buildErrorView()
      }
    }
    .width('88%')
    .maxHeight('82%')
    .backgroundColor('#FFFFFF')
    .borderRadius(20)
    .padding({ top: 0, bottom: 20, left: 16, right: 16 })
  }

  @Builder
  buildHeader() {
    Row() {
      if (this.state === TransferState.SELECTING || this.state === TransferState.SCANNING || this.state === TransferState.CONNECTING || this.state === TransferState.WAITING) {
        Button('✕').fontSize(16).backgroundColor('transparent').fontColor('#86909C')
          .onClick(() => {
            bluetoothService.destroy();
            this.onDismiss();
          })
      } else {
        Blank().width(36)
      }

      Text(this.getTitle())
        .fontSize(17)
        .fontWeight(FontWeight.Bold)
        .fontColor('#1D2129')
        .layoutWeight(1)
        .textAlign(TextAlign.Center)

      if (this.state === TransferState.SELECTING || this.state === TransferState.SCANNING || this.state === TransferState.CONNECTING || this.state === TransferState.WAITING) {
        Blank().width(36)
      } else {
        Blank().width(36)
      }
    }
    .width('100%')
    .height(52)
    .padding({ left: 4, right: 4 })
  }

  getTitle(): string {
    switch (this.state) {
      case TransferState.SELECTING: return '选择记录';
      case TransferState.SCANNING: return '搜索设备';
      case TransferState.CONNECTING: return '正在连接';
      case TransferState.TRANSFERRING: return '传输中';
      case TransferState.WAITING: return '等待连接';
      case TransferState.COMPLETE: return '传输完成';
      case TransferState.ERROR: return '传输失败';
      default: return '';
    }
  }

  @Builder
  buildSelectView() {
    Column() {
      Row() {
        Button(this.selectedIds.size === this.expenses.length ? '取消全选' : '全选')
          .fontSize(12)
          .height(30)
          .backgroundColor('transparent')
          .fontColor('#4F6EF7')
          .onClick(() => { this.selectAll(); })

        Blank()

        Text(`已选 ${this.selectedCount} 条`)
          .fontSize(12).fontColor('#86909C')

        Button('发送')
          .fontSize(13)
          .height(32)
          .backgroundColor(this.selectedCount > 0 ? '#4F6EF7' : '#C9CDD4')
          .fontColor('#FFFFFF')
          .borderRadius(16)
          .padding({ left: 16, right: 16 })
          .enabled(this.selectedCount > 0)
          .onClick(() => { this.confirmSelection(); })
          .margin({ left: 10 })
      }
      .width('100%')
      .padding({ left: 4, right: 4, bottom: 10 })

      List() {
        ForEach(this.expenses, (item: ExpenseItem) => {
          ListItem() {
            Row() {
              Checkbox()
                .select(this.selectedIds.has(item.id))
                .selectedColor('#4F6EF7')
                .onChange((checked: boolean) => { this.toggleSelect(item.id); })

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

                  if (item.remark) {
                    Text(item.remark)
                      .fontSize(11).fontColor('#A9AEB8')
                      .maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis })
                      .margin({ left: 8 })
                  }
                }

                Text(this.formatDateShort(item.createTime))
                  .fontSize(10).fontColor('#C9CDD4').margin({ top: 2 })
              }
              .margin({ left: 10 }).layoutWeight(1).alignItems(HorizontalAlign.Start)

              Text(`${item.type === '消费' ? '-' : '+'}¥${(item.amount || 0).toFixed(2)}`)
                .fontSize(15).fontWeight(FontWeight.Bold)
                .fontColor(item.type === '消费' ? '#E85545' : '#2BA471')
            }
            .width('100%')
            .padding({ top: 10, bottom: 10, left: 8, right: 8 })
            .borderRadius(10)
            .backgroundColor('#F8F9FC')
            .margin({ top: 3, bottom: 3 })
          }
        })
      }
      .width('100%')
      .layoutWeight(1)
      .scrollBar(BarState.Off)
      .divider({ strokeWidth: 0 })
    }
    .width('100%')
    .layoutWeight(1)
  }

  @Builder
  buildScanOrTransferView() {
    Column() {
      if (this.state === TransferState.SCANNING) {
        LoadingProgress().width(32).height(32).color('#4F6EF7').margin({ bottom: 16 })
        Text(this.stateMessage)
          .fontSize(13).fontColor('#86909C').margin({ bottom: 16 })

        if (this.discoveredDevices.length > 0) {
          Text(`发现 ${this.discoveredDevices.length} 台设备`)
            .fontSize(12).fontColor('#A9AEB8').margin({ bottom: 10 })

          List() {
            ForEach(this.discoveredDevices, (device: BluetoothDevice, index: number) => {
              ListItem() {
                Row() {
                  Text(this.getDeviceIcon(index)).fontSize(24)
                  Column() {
                    Text(device.deviceName).fontSize(14).fontWeight(FontWeight.Medium).fontColor('#1D2129')
                    Text(device.deviceId).fontSize(10).fontColor('#A9AEB8').maxLines(1)
                  }
                  .margin({ left: 12 }).layoutWeight(1).alignItems(HorizontalAlign.Start)

                  Button('连接')
                    .fontSize(12).height(30)
                    .backgroundColor('#4F6EF7').fontColor('#FFFFFF')
                    .borderRadius(15).padding({ left: 14, right: 14 })
                    .onClick(() => { this.sendToDevice(device); })
                }
                .width('100%')
                .padding({ top: 12, bottom: 12, left: 12, right: 12 })
                .borderRadius(12)
                .backgroundColor('#F8F9FC')
                .margin({ top: 3, bottom: 3 })
              }
            })
          }
          .width('100%')
          .layoutWeight(1)
          .scrollBar(BarState.Off)
        }
      } else if (this.state === TransferState.CONNECTING) {
        LoadingProgress().width(32).height(32).color('#4F6EF7').margin({ bottom: 16 })
        Text(this.stateMessage).fontSize(13).fontColor('#86909C')
      } else if (this.state === TransferState.TRANSFERRING) {
        Text('📡').fontSize(40).margin({ bottom: 12 })
        Text('正在传输数据...').fontSize(14).fontWeight(FontWeight.Medium).fontColor('#1D2129').margin({ bottom: 8 })
        Text(this.formatProgress()).fontSize(28).fontWeight(FontWeight.Bold).fontColor('#4F6EF7')
      }
    }
    .width('100%')
    .layoutWeight(1)
    .justifyContent(FlexAlign.Center)
    .padding({ bottom: 40 })
  }

  @Builder
  buildWaitingView() {
    Column() {
      Column() {
        Text('📡').fontSize(48).margin({ bottom: 12 })
        Text('等待发送方连接')
          .fontSize(15).fontWeight(FontWeight.Medium).fontColor('#1D2129').margin({ bottom: 8 })
        Text(this.stateMessage)
          .fontSize(12).fontColor('#86909C')
          .textAlign(TextAlign.Center).margin({ bottom: 20 })

        LoadingProgress().width(28).height(28).color('#2BA471')
      }
      .width('100%').layoutWeight(1).justifyContent(FlexAlign.Center)

      Button('取消等待')
        .width('100%').height(44)
        .fontSize(14).backgroundColor('rgba(0,0,0,0.05)').fontColor('#86909C')
        .borderRadius(22)
        .onClick(() => {
          bluetoothService.stopServer();
          this.onDismiss();
        })
    }
    .width('100%')
    .layoutWeight(1)
  }

  @Builder
  buildCompleteView() {
    Column() {
      Text('✓').fontSize(48).fontColor('#2BA471').margin({ bottom: 12 })
      Text('传输完成')
        .fontSize(18).fontWeight(FontWeight.Bold).fontColor('#1D2129').margin({ bottom: 8 })
      Text(this.stateMessage)
        .fontSize(13).fontColor('#86909C').textAlign(TextAlign.Center).margin({ bottom: 20 })

      if (this.receivedRecords.length > 0) {
        Text(`收到 ${this.receivedRecords.length} 条记账记录`)
          .fontSize(13).fontColor('#4F6EF7').margin({ bottom: 16 })

        Row() {
          this.buildCompleteButton('导入数据', '#2BA471', () => { this.importReceivedData(); })
          this.buildCompleteButton('取消', '#86909C', () => { this.onDismiss(); })
        }
        .width('100%')
        .justifyContent(FlexAlign.SpaceEvenly)
      } else {
        this.buildCompleteButton('完成', '#4F6EF7', () => { this.onDismiss(); })
      }
    }
    .width('100%').layoutWeight(1).justifyContent(FlexAlign.Center)
  }

  @Builder
  buildCompleteButton(label: string, color: string, action: () => void) {
    Button(label)
      .fontSize(14).height(42)
      .backgroundColor(color).fontColor('#FFFFFF')
      .borderRadius(21).padding({ left: 32, right: 32 })
      .onClick(action)
  }

  @Builder
  buildErrorView() {
    Column() {
      Text('✕').fontSize(40).fontColor('#E85545').margin({ bottom: 12 })
      Text('传输失败').fontSize(18).fontWeight(FontWeight.Bold).fontColor('#1D2129').margin({ bottom: 8 })
      Text(this.errorMessage)
        .fontSize(13).fontColor('#86909C').textAlign(TextAlign.Center).margin({ bottom: 24 })
        .padding({ left: 20, right: 20 })

      Row() {
        this.buildCompleteButton('重试', '#4F6EF7', () => {
          this.state = TransferState.IDLE;
          this.onDismiss();
        })
        this.buildCompleteButton('关闭', 'rgba(0,0,0,0.05)', () => { this.onDismiss(); })
      }
      .width('100%')
      .justifyContent(FlexAlign.SpaceEvenly)
    }
    .width('100%').layoutWeight(1).justifyContent(FlexAlign.Center)
  }
}
