import 'package:track_common/widget/prelude.dart';

import '../../service/api.dart';
import 'field_control.dart';

class _ArgCreate {
  int mapId = 0;
  Iterable<EventInfo> eventList = [];
}

class _ArgEdit {
  int mapId = 0;
  EventRegisterInfo old = EventRegisterInfo();
}

Future<EventRegisterInfo?> showEventRegisterDialog(
    int mapId, Iterable<EventInfo> eventList) async {
  return await Get.dialog(const RegisterDialog(),
      arguments: _ArgCreate()
        ..mapId = mapId
        ..eventList = eventList);
}

Future<EventRegisterInfo?> showEventEditDialog(
    int mapId, EventRegisterInfo old) async {
  return await Get.dialog(const RegisterDialog(),
      arguments: _ArgEdit()
        ..mapId = mapId
        ..old = old);
}

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 hasPassword = false.obs;
  var password = '';
  late final int mapId;
  late final Iterable<EventInfo>? eventList;

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

  @override
  void onInit() {
    final args = Get.arguments;

    if (args is _ArgCreate) {
      mapId = args.mapId;
      eventList = args.eventList;
    }
    if (args is _ArgEdit) {
      eventList = null;
      mapId = args.mapId;
      registerName = args.old.name;
      final d = args.old.startAt;
      date.value = DateTime(d.year, d.month, d.day);
      registerStartAt.value = TimeOfDay.fromDateTime(args.old.startAt);
      registerStopAt.value = TimeOfDay.fromDateTime(args.old.stopAt);
      password = args.old.password ?? '';
      hasPassword.value = args.old.password != null;
    }
    super.onInit();
  }
}

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

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
        init: RegisterDialogController(),
        builder: (c) {
          final children = <Widget>[];
          final eventList = controller.eventList;

          if (eventList != null) {
            children.addAll([
              SizedBox(
                  child: DropdownMenu<EventInfo>(
                      key: GlobalKey(),
                      width: 320,
                      hintText: '请选择活动',
                      onSelected: (one) {
                        controller.selected.value = one;
                      },
                      inputDecorationTheme: InputDecorationTheme(
                        border: textBorder,
                        isDense: true,
                      ),
                      dropdownMenuEntries: eventList
                          .map((e) => DropdownMenuEntry<EventInfo>(
                              value: e, label: e.name))
                          .toList())),
              const SizedBox(height: 21.34),
            ]);
          }
          children.addAll([
            _TextField(
              hint: '请输入名称',
              onChanged: (v) {
                c.registerName = v;
              },
              initText: controller.registerName.isEmpty
                  ? null
                  : controller.registerName,
            ),
            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.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: Text(eventList != null ? '注 册' : '确 定')))
          ]);

          return AlertDialog(
            title: Center(
                child: Text(
              eventList != null ? '注册比赛' : '编辑比赛',
              style: const TextStyle(fontSize: 17),
            )),
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(17.78)),
            content: SizedBox(
                width: 320,
                child: ListView(shrinkWrap: true, children: children)),
          );
        });
  }

  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: EventRegisterInfo()
          ..id = selected.id
          ..name = controller.registerName
          ..startAt = startAt
          ..stopAt = stopAt
          ..password =
              controller.hasPassword.value ? controller.password : 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)
          )),
    );
  }
}
