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 hasPasswordQuery = false.obs;
  final hasPasswordEvent = false.obs;
  var passwordQuery = '';
  var passwordEvent = '';
  late final int mapId;
  late final Iterable<EventInfo>? eventList;
  late final Object _args;

  Rx<DateTime?> eventDate = Rx(null);
  TimeOfDay? eventStartAt;
  TimeOfDay? eventEndAt;

  Rx<DateTime?> showDate = Rx(null);
  TimeOfDay? showStartAt;
  TimeOfDay? showEndAt;

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

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

    if (args is _ArgCreate) {
      mapId = args.mapId;
      eventList = args.eventList;
    }
    if (args is _ArgEdit) {
      eventList = null;
      mapId = args.mapId;
      registerName = args.old.name;
      var d = args.old.eventStartAt;

      eventDate.value = DateTime(d.year, d.month, d.day);
      d = args.old.showStartAt;
      showDate.value = DateTime(d.year, d.month, d.day);
      eventStartAt = TimeOfDay.fromDateTime(args.old.eventStartAt);
      eventEndAt = TimeOfDay.fromDateTime(args.old.eventStopAt);

      showStartAt = TimeOfDay.fromDateTime(args.old.showStartAt);
      showEndAt = TimeOfDay.fromDateTime(args.old.showStopAt);

      passwordQuery = args.old.passwordQuery ?? '';
      hasPasswordQuery.value = args.old.passwordQuery != null;
      passwordEvent = args.old.passwordEvent ?? '';
      hasPasswordEvent.value = args.old.passwordEvent != null;
    }
    super.onInit();
  }

  void updateShowTime(DateTime? date, TimeOfDay? startAt, TimeOfDay? endAt) {
    if (date != null) {
      showDate.value = date;
    }
    if (startAt != null) {
      showStartAt = startAt;
    }
    if (endAt != null) {
      showEndAt = endAt;
    }
  }

  void updateEventTime(DateTime? date, TimeOfDay? startAt, TimeOfDay? endAt) {
    if (date != null) {
      eventDate.value = date;
    }
    if (startAt != null) {
      eventStartAt = startAt;
    }
    if (endAt != null) {
      eventEndAt = endAt;
    }
  }
}

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),
            Obx(() => _DateTimeSelect(
                title: '比赛时间',
                date: c.eventDate.value,
                startAt: c.eventStartAt,
                endAt: c.eventEndAt,
                onChanged: c.updateEventTime)),
            const SizedBox(height: 12),
            Obx(() => _DateTimeSelect(
                title: '显示时间',
                date: c.showDate.value,
                startAt: c.showStartAt,
                endAt: c.showEndAt,
                onChanged: c.updateShowTime)),
            password('查询密码', c.hasPasswordQuery, (v) {
              c.passwordQuery = v;
            }),
            // password('赛事密码', c.hasPasswordEvent, (v) {
            //   c.passwordEvent = 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)),
          );
        });
  }

  Widget password(
    String title,
    Rx<bool> hasPassword,
    void Function(String) onChanged,
  ) {
    return SizedBox(
        height: 80,
        child: Row(mainAxisSize: MainAxisSize.min, children: [
          Obx(() => Switch(
              value: hasPassword.value,
              onChanged: (v) {
                hasPassword.value = v;
              })),
          Text(title),
          const SizedBox(width: 12),
          Obx(() => Expanded(
              child: Visibility(
                  visible: hasPassword.value,
                  child: _TextField(hint: '请输入密码', onChanged: onChanged))))
        ]));
  }

  void _onRegister() {
    final showDate = controller.showDate;
    final showTimeStartAt = controller.showStartAt;
    final showTimeStopAt = controller.showEndAt;
    final evenDate = controller.eventDate;
    final eventTimeStartAt = controller.eventStartAt;
    final eventTimeStopAt = controller.eventEndAt;
    final selected = controller.selected.value;
    final args = controller._args;
    var selectedId = -1;
    if (args is _ArgCreate) {
      if (selected == null) {
        Get.snackbar('错误', '请选择一个活动');
        return;
      }
      selectedId = selected.id;
    }
    if (args is _ArgEdit) {
      selectedId = args.old.id;
    }

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

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

    if (showTimeStopAt == null) {
      Get.snackbar('错误', '请选择结束时间');
      return;
    }
    if (evenDate.value == null) {
      Get.snackbar('错误', '请选择日期');
      return;
    }
    if (eventTimeStartAt == null) {
      Get.snackbar('错误', '请选择开始时间');
      return;
    }

    if (eventTimeStopAt == null) {
      Get.snackbar('错误', '请选择结束时间');
      return;
    }
    final eventStartAt = evenDate.value!
        .copyWith(hour: eventTimeStartAt.hour, minute: eventTimeStartAt.minute);
    final eventStopAt = evenDate.value!
        .copyWith(hour: eventTimeStopAt.hour, minute: eventTimeStopAt.minute);

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

    final showStartAt = showDate.value!
        .copyWith(hour: showTimeStartAt.hour, minute: showTimeStartAt.minute);
    final showStopAt = showDate.value!
        .copyWith(hour: showTimeStopAt.hour, minute: showTimeStopAt.minute);

    if (showStartAt.isAfter(showStopAt)) {
      Get.snackbar('错误', '结束时间应晚于开始时间');
      return;
    }
    Get.back(
        result: EventRegisterInfo()
          ..id = selectedId
          ..name = controller.registerName
          ..showStartAt = showStartAt
          ..showStopAt = showStopAt
          ..eventStartAt = eventStartAt
          ..eventStopAt = eventStopAt
          ..passwordQuery = controller.hasPasswordQuery.value
              ? controller.passwordQuery
              : null
          ..passwordEvent = controller.hasPasswordEvent.value
              ? controller.passwordEvent
              : 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)
          )),
    );
  }
}

class _DateTimeSelect extends StatefulWidget {
  const _DateTimeSelect(
      {required this.title,
      this.date,
      this.startAt,
      this.endAt,
      required this.onChanged});

  final String title;
  final DateTime? date;
  final TimeOfDay? startAt;
  final TimeOfDay? endAt;
  final void Function(DateTime? date, TimeOfDay? startAt, TimeOfDay? endAt)
      onChanged;

  @override
  State<StatefulWidget> createState() {
    return _DateTimeSelectState();
  }
}

class _DateTimeSelectState extends State<_DateTimeSelect> {
  DateTime? date;
  TimeOfDay? startAt;
  TimeOfDay? endAt;

  @override
  void initState() {
    date = widget.date;
    startAt = widget.startAt;
    endAt = widget.endAt;
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(widget.title),
        Row(children: [
          Expanded(
              child: _TextField(
                  hint: '日期',
                  readOnly: true,
                  initText: dateString(date),
                  onTap: () async {
                    date = await _showDatePicker(context, date);
                    setState(() {});
                    widget.onChanged(date, null, null);
                  })),
          const SizedBox(width: 15.64),
          Expanded(
              child: _TextField(
                  hint: '开始时间',
                  readOnly: true,
                  initText: startAt?.format(context),
                  onTap: () async {
                    startAt = await _showTimePicker(context, startAt);
                    setState(() {});
                    widget.onChanged(null, startAt, null);
                  })),
          const SizedBox(width: 15.64),
          Expanded(
              child: _TextField(
                  hint: '结束时间',
                  readOnly: true,
                  initText: endAt?.format(context),
                  onTap: () async {
                    endAt = await _showTimePicker(context, endAt);
                    setState(() {});
                    widget.onChanged(null, null, endAt);
                  })),
        ]),
      ],
    );
  }
}
