import 'dart:typed_data';

import 'package:flutter/material.dart';
//import 'package:flutter/widgets.dart';
// import 'package:fluttertoast/fluttertoast.dart';
import 'package:gme_flutter/tmg_sdk.dart';

class UpdateSelfDialogPage extends StatefulWidget {
  UpdateSelfDialogPage({Key? key}) : super(key: key);
  static _UpdateSelfDialogPageState? _updateDialogPage = null;
  @override
  _UpdateSelfDialogPageState createState() {
    _updateDialogPage = _UpdateSelfDialogPageState();
    return _updateDialogPage!;
  }

  static final ValueNotifier<List<String>> _userIDListNotifier =
      ValueNotifier<List<String>>([]);

  static List<String> get _userIDList => _userIDListNotifier.value;

  static void AddUserId(String userId) {
    _userIDListNotifier.value = [..._userIDListNotifier.value, userId];
    _updateDialogPage?.initState();
  }

  static void RemoveUserId(String userId) {
    if (_userIDListNotifier.value.isEmpty) return;
    _userIDListNotifier.value =
        _userIDListNotifier.value.where((id) => id != userId).toList();
    if (_updateDialogPage != null &&
        _updateDialogPage!._selectedValue == userId) {
      _updateDialogPage!._selectedValue =
          _userIDListNotifier.value.isNotEmpty
              ? _userIDListNotifier.value.first
              : '';
      _updateDialogPage!.setState(() {});
    }
  }

  static void ClearUserIdList() {
    _userIDListNotifier.value = [];
  }
}

class _UpdateSelfDialogPageState extends State<UpdateSelfDialogPage>
    with WidgetsBindingObserver {
  // 新增类成员变量
  String _selectedValue = '';

  @override
  void initState() {
    super.initState();
    // 初始化时使用_selectUserid或第一个有效值
    _selectedValue =
        _selectUserid.isNotEmpty
            ? _selectUserid
            : (UpdateSelfDialogPage._userIDList.isNotEmpty
                ? UpdateSelfDialogPage._userIDList.first
                : '');
  }

  @override
  void dispose() {
    super.dispose();
  }

  double _positionX = 0;
  double _positionY = 0;
  double _positionZ = 0;
  String _curState = "IsEnableSpatializer";
  String _selectUserid = "mySelf";

  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: [
            ValueListenableBuilder<List<String>>(
              valueListenable: UpdateSelfDialogPage._userIDListNotifier,
              builder: (context, userIDList, _) {
                return DropdownButton<String>(
                  value: _selectedValue,
                  items:
                      userIDList.map((String value) {
                        return DropdownMenuItem<String>(
                          value: value,
                          child: Text(value),
                        );
                      }).toList(),
                  onChanged: (String? newValue) {
                    setState(() {
                      _selectUserid = newValue!;
                      _selectedValue = newValue!;
                    });
                  },
                );
              },
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                TextButton.icon(
                  onPressed: () async {
                    Float32List position = Float32List.fromList([
                      0.0,
                      0.0,
                      0.0,
                    ]);
                    Float32List axisForward = Float32List.fromList([
                      1.0,
                      0.0,
                      0.0,
                    ]);
                    Float32List axisRightward = Float32List.fromList([
                      0.0,
                      1.0,
                      0.0,
                    ]);
                    Float32List axisUpward = Float32List.fromList([
                      0.0,
                      0.0,
                      1.0,
                    ]);
                    int res = 0;
                    if (_selectUserid == "mySelf") {
                      res = await ITMGContext.GetInstance()
                          .GetRoom()
                          .UpdateSelfPosition(
                            position,
                            axisForward,
                            axisRightward,
                            axisUpward,
                          );
                    } else {
                      res = await ITMGContext.GetInstance()
                          .GetRoom()
                          .UpdateOtherPosition(_selectUserid, position);
                    }
                    if (res != 0) {
                      return;
                    }
                    setState(() {
                      _positionX = 0;
                      _positionY = 0;
                      _positionZ = 0;
                    });
                  },
                  icon: Icon(Icons.restore_sharp),
                  label: Text("Reset"),
                ),
                TextButton.icon(
                  onPressed: () {
                    Navigator.pop(context);
                    UpdateSelfDialogPage._updateDialogPage = null;
                  },
                  icon: Icon(Icons.exit_to_app),
                  label: Text("Exit"),
                ),
              ],
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text("Position X:$_positionX"),
                Slider(
                  value: _positionX,
                  onChangeEnd: (value) async {
                    Float32List position = Float32List.fromList([
                      value,
                      _positionY,
                      _positionZ,
                    ]);
                    Float32List axisForward = Float32List.fromList([
                      1.0,
                      0.0,
                      0.0,
                    ]);
                    Float32List axisRightward = Float32List.fromList([
                      0.0,
                      1.0,
                      0.0,
                    ]);
                    Float32List axisUpward = Float32List.fromList([
                      0.0,
                      0.0,
                      1.0,
                    ]);
                    int res = 0;
                    if (_selectUserid == "mySelf") {
                      res = await ITMGContext.GetInstance()
                          .GetRoom()
                          .UpdateSelfPosition(
                            position,
                            axisForward,
                            axisRightward,
                            axisUpward,
                          );
                    } else {
                      res = await ITMGContext.GetInstance()
                          .GetRoom()
                          .UpdateOtherPosition(_selectUserid, position);
                    }
                    if (res != 0) {
                      return;
                    }
                  },
                  onChanged: (value) async {
                    setState(() {
                      _positionX = value * 10 / 10;
                    });
                  },
                  min: -1,
                  max: 1,
                  divisions: 10,
                  activeColor: Colors.blueGrey,
                  inactiveColor: Colors.grey,
                ),
                Text("Position Y:$_positionY"),
                Slider(
                  value: _positionY,
                  onChangeEnd: (value) async {
                    Float32List position = Float32List.fromList([
                      _positionX,
                      value,
                      _positionZ,
                    ]);
                    Float32List axisForward = Float32List.fromList([
                      1.0,
                      0.0,
                      0.0,
                    ]);
                    Float32List axisRightward = Float32List.fromList([
                      0.0,
                      1.0,
                      0.0,
                    ]);
                    Float32List axisUpward = Float32List.fromList([
                      0.0,
                      0.0,
                      1.0,
                    ]);
                    int res = 0;
                    if (_selectUserid == "mySelf") {
                      res = await ITMGContext.GetInstance()
                          .GetRoom()
                          .UpdateSelfPosition(
                            position,
                            axisForward,
                            axisRightward,
                            axisUpward,
                          );
                    } else {
                      res = await ITMGContext.GetInstance()
                          .GetRoom()
                          .UpdateOtherPosition(_selectUserid, position);
                    }
                    if (res != 0) {
                      return;
                    }
                  },
                  onChanged: (value) async {
                    setState(() {
                      _positionY = value * 10 / 10;
                    });
                  },
                  min: -1,
                  max: 1,
                  divisions: 10,
                  activeColor: Colors.blueGrey,
                  inactiveColor: Colors.grey,
                ),
                Text("Position Z:$_positionZ"),
                Slider(
                  value: _positionZ,
                  onChangeEnd: (value) async {
                    Float32List position = Float32List.fromList([
                      _positionX,
                      _positionY,
                      value,
                    ]);
                    Float32List axisForward = Float32List.fromList([
                      1.0,
                      0.0,
                      0.0,
                    ]);
                    Float32List axisRightward = Float32List.fromList([
                      0.0,
                      1.0,
                      0.0,
                    ]);
                    Float32List axisUpward = Float32List.fromList([
                      0.0,
                      0.0,
                      1.0,
                    ]);
                    int res = 0;
                    if (_selectUserid == "mySelf") {
                      res = await ITMGContext.GetInstance()
                          .GetRoom()
                          .UpdateSelfPosition(
                            position,
                            axisForward,
                            axisRightward,
                            axisUpward,
                          );
                    } else {
                      res = await ITMGContext.GetInstance()
                          .GetRoom()
                          .UpdateOtherPosition(_selectUserid, position);
                    }
                    if (res != 0) {
                      return;
                    }
                  },
                  onChanged: (value) {
                    setState(() {
                      _positionZ = value * 10 / 10;
                    });
                  },
                  min: -1,
                  max: 1,
                  divisions: 10,
                  activeColor: Colors.blueGrey,
                  inactiveColor: Colors.grey,
                ),
                TextButton.icon(
                  onPressed: () async {
                    bool res =
                        await ITMGContext.GetInstance()
                            .GetAudioCtrl()
                            .IsEnableSpatializer();
                    print(res);
                    setState(() {
                      _curState = res ? "Yes" : "No";
                    });
                  },
                  icon: Icon(Icons.room_service),
                  label: Text("$_curState"),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
