import 'package:app_business/service/api.dart';
import 'package:grpc/grpc.dart';
import 'package:track_common/service/map_watch.dart';
import 'package:track_common/track_common.dart';
import 'package:track_common/view/home/field_control/field_control.dart';
import 'package:track_common/view/home/field_control/field_control_controller.dart';
import 'package:track_common/widget/prelude.dart';

class FieldControlPageImpl extends FieldControlPage {
  const FieldControlPageImpl({super.key});

  @override
  Widget rightColumn(BuildContext context) {
    return Obx(() {
      final mapWatch = controller.mapWatch;
      debug('${identityHashCode(controller)}');
      return Container(
          width: 370,
          padding: const EdgeInsets.all(6.4),
          height: double.infinity,
          color: Colors.white,
          child: Column(
            children: [
              Container(
                  padding: const EdgeInsets.only(bottom: 8),
                  width: double.infinity,
                  child: DarkButton(
                      onPressed: mapWatch != null
                          ? () => _onTapRegister(context, mapWatch)
                          : null,
                      child: const Text('注册比赛'))),
              const Expanded(child: EventInfoView())
            ],
          ));
    });
  }

  Future<void> _onTapRegister(BuildContext context, MapWatch mapWatch) async {
    final r = await Get.dialog(const RegisterDialog(), arguments: mapWatch.id)
        as RegisterInfo?;

    if (r != null) {
      Get.find<ApiService>()
          .stub
          .toMatchRegusterAdd(ToMatchRegusterAddRequest()
            ..actId = r.id
            ..regName = r.name
            ..startAt = r.startAt.toPb()
            ..stopAt = r.stopAt.toPb()
            ..isQueryPwd = r.passwordQuery != null
            ..queryPasswd = r.passwordQuery ?? '')
          .then((p0) {}, onError: (e) {
        if (e is GrpcError) {
          if (context.mounted) {
            ScaffoldMessenger.of(context)
                .showSnackBar(SnackBar(content: Text('注册失败：{${e.message}')));
          }
        }
      });
    }
  }
}

class EventInfo {
  int id = 0;
  String name = '';
}

class RegisterInfo {
  var id = 0;
  var name = '';
  var startAt = DateTime.now();
  var stopAt = DateTime.now();
  String? password;
  String? passwordQuery;
}

class FieldControlControllerImpl extends FieldControlController {
  @override
  void onInit() {
    debug('init');
    super.onInit();
  }

  @override
  void onClose() {
    super.onClose();
    debug('close');
  }
}

class RegisterDialogController extends GetxController {
  var registerName = '';
  final date = Rx<DateTime?>(null);
  final registerStartAt = Rx<TimeOfDay?>(null);
  final registerStopAt = Rx<TimeOfDay?>(null);
  final selected = Rx<EventInfo?>(null);
  final eventList = <EventInfo>[].obs;
  final hasPassword = false.obs;
  final hasPasswordQuery = false.obs;
  var password = '';
  var passwordQuery = '';
  late final int mapId;
  final api = Get.find<ApiService>();

  String? get dateString {
    final d = date.value;
    if (d != null) {
      return '${d.month}/${d.day}';
    }
    return null;
  }

  @override
  void onInit() {
    mapId = Get.arguments as int;
    api.stub.toActivitySelectList(IdRequest()..id = Int64(mapId)).then((r) {
      eventList.value = r.list
          .map((e) => EventInfo()
            ..id = e.actId
            ..name = e.actName)
          .toList();
    });
    super.onInit();
  }
}

class RegisterDialog extends GetView<RegisterDialogController> {
  const RegisterDialog({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
        init: RegisterDialogController(),
        builder: (c) {
          return AlertDialog(
            title: const Center(
                child: Text(
              '注册比赛',
              style: TextStyle(fontSize: 17),
            )),
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(17.78)),
            content: SizedBox(
                width: 320,
                child: ListView(
                  shrinkWrap: true,
                  children: [
                    Obx(() => SizedBox(
                        child: DropdownMenu<EventInfo>(
                            key: GlobalKey(),
                            width: 320,
                            hintText: '请选择活动',
                            onSelected: (one) {
                              controller.selected.value = one;
                            },
                            inputDecorationTheme: InputDecorationTheme(
                              border: textBorder,
                              isDense: true,
                            ),
                            dropdownMenuEntries: controller.eventList
                                .map((e) => DropdownMenuEntry<EventInfo>(
                                    value: e, label: e.name))
                                .toList()))),
                    const SizedBox(height: 21.34),
                    _TextField(
                        hint: '请输入名称',
                        onChanged: (v) {
                          c.registerName = v;
                        }),
                    const SizedBox(height: 21.34),
                    Row(children: [
                      Expanded(
                          child: Obx(() => _TextField(
                              hint: '日期',
                              readOnly: true,
                              initText: c.dateString,
                              onTap: () async {
                                c.date.value = await _showDatePicker(
                                    context, c.date.value);
                              }))),
                      const SizedBox(width: 15.64),
                      Expanded(
                          child: Obx(() => _TextField(
                              hint: '开始时间',
                              readOnly: true,
                              initText:
                                  c.registerStartAt.value?.format(context),
                              onTap: () async {
                                c.registerStartAt.value = await _showTimePicker(
                                    context, c.registerStartAt.value);
                              }))),
                      const SizedBox(width: 15.64),
                      Expanded(
                          child: Obx(() => _TextField(
                              hint: '结束时间',
                              readOnly: true,
                              initText: c.registerStopAt.value?.format(context),
                              onTap: () async {
                                c.registerStopAt.value = await _showTimePicker(
                                    context, c.registerStopAt.value);
                              }))),
                    ]),
                    const SizedBox(height: 21.34),
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Obx(() => Switch(
                            value: c.hasPasswordQuery.value,
                            onChanged: (v) {
                              c.hasPasswordQuery.value = v;
                            })),
                        const Text('查询密码'),
                        const SizedBox(width: 12),
                        Obx(() => Expanded(
                            child: Visibility(
                                visible: c.hasPasswordQuery.value,
                                child: _TextField(
                                    hint: '请输入密码',
                                    onChanged: (v) {
                                      c.passwordQuery = v;
                                    })))),
                      ],
                    ),
                    const SizedBox(height: 6),
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Obx(() => Switch(
                            value: c.hasPassword.value,
                            onChanged: (v) {
                              c.hasPassword.value = v;
                            })),
                        const Text('赛事密码'),
                        const SizedBox(width: 12),
                        Obx(() => Expanded(
                            child: Visibility(
                                visible: c.hasPassword.value,
                                child: _TextField(
                                    hint: '请输入密码',
                                    onChanged: (v) {
                                      c.password = v;
                                    })))),
                      ],
                    ),
                    const SizedBox(height: 21.34),
                    SizedBox(
                        width: double.infinity,
                        child: DarkButton(
                            onPressed: _onRegister, child: const Text('注 册')))
                  ],
                )),
          );
        });
  }

  void _onRegister() {
    final date = controller.date.value;
    final timeStartAt = controller.registerStartAt.value;
    final timeStopAt = controller.registerStopAt.value;
    final selected = controller.selected.value;

    if (selected == null) {
      Get.snackbar('错误', '请选择一个活动');
      return;
    }

    if (controller.registerName.isEmpty) {
      Get.snackbar('错误', '输入名称');
      return;
    }

    if (date == null) {
      Get.snackbar('错误', '请选择日期');
      return;
    }
    if (timeStartAt == null) {
      Get.snackbar('错误', '请选择开始时间');
      return;
    }

    if (timeStopAt == null) {
      Get.snackbar('错误', '请选择结束时间');
      return;
    }

    final startAt =
        date.copyWith(hour: timeStartAt.hour, minute: timeStartAt.minute);
    final stopAt =
        date.copyWith(hour: timeStopAt.hour, minute: timeStopAt.minute);

    if (startAt.isAfter(stopAt)) {
      Get.snackbar('错误', '结束时间应晚于开始时间');
      return;
    }

    Get.back(
        result: RegisterInfo()
          ..id = selected.id
          ..name = controller.registerName
          ..startAt = startAt
          ..stopAt = stopAt
          ..password = controller.hasPassword.value ? controller.password : null
          ..passwordQuery = controller.hasPasswordQuery.value
              ? controller.passwordQuery
              : null);
  }

  Future<TimeOfDay?> _showTimePicker(
      BuildContext context, TimeOfDay? init) async {
    final TimeOfDay? time = await showTimePicker(
      context: context,
      initialTime: init ?? TimeOfDay.now(),
    );
    return time;
  }

  Future<DateTime?> _showDatePicker(
      BuildContext context, DateTime? init) async {
    final DateTime? time = await showDatePicker(
      context: context,
      initialDate: init ?? DateTime.now(),
      firstDate: DateTime.now(),
      lastDate: DateTime.now().add(365.days),
    );
    return time;
  }
}

final textBorder = OutlineInputBorder(
  borderSide: const BorderSide(width: 0.71, color: Color(0xff818181)),
  borderRadius: BorderRadius.circular(2.13),
);

class _TextField extends StatelessWidget {
  const _TextField(
      {required this.hint,
      this.onChanged,
      this.readOnly = false,
      this.onTap,
      this.initText});

  final String hint;
  final void Function(String)? onChanged;
  final bool readOnly;
  final void Function()? onTap;
  final String? initText;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: TextFormField(
          key: GlobalKey(),
          initialValue: initText,
          maxLines: 1,
          onChanged: onChanged,
          onTap: onTap,
          readOnly: readOnly,
          decoration: InputDecoration(
            hintText: hint,
            border: textBorder,
            isDense: true,
            // contentPadding: const EdgeInsets.all(8.53)
          )),
    );
  }
}
