import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:get/get.dart';
import 'package:loopin/IM/controller/im_user_info_controller.dart';

class NickName extends StatefulWidget {
  const NickName({super.key});

  @override
  State<NickName> createState() => _NickNameState();
}

class _NickNameState extends State<NickName> {
  final _formKey = GlobalKey<FormBuilderState>();
  final userInfoController = Get.find<ImUserInfoController>();

  void _save() async {
    if (_formKey.currentState?.saveAndValidate() ?? false) {
      final nickname = _formKey.currentState?.fields['nickname']?.value;
      final result = await userInfoController.updateNickname(nickname);
      if (result) {
        Get.back();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).unfocus(),
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: const Text('修改昵称'),
          actions: [
            TextButton(
              onPressed: _save,
              child: const Text(
                '保存',
                style: TextStyle(color: Colors.red, fontSize: 16),
              ),
            ),
          ],
        ),
        body: Padding(
          padding: const EdgeInsets.all(16),
          child: FormBuilder(
              key: _formKey,
              child: Obx(() {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '我的昵称',
                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    FormBuilderTextField(
                      name: 'nickname',
                      initialValue: userInfoController.nickname.value,
                      decoration: const InputDecoration(
                        hintText: '请输入昵称',
                        border: OutlineInputBorder(),
                        contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                      ),
                      maxLength: 8,
                      validator: FormBuilderValidators.compose([
                        FormBuilderValidators.required(errorText: '昵称不能为空'),
                        FormBuilderValidators.maxLength(8, errorText: '昵称不能超过8个字符'),
                      ]),
                    ),
                    const SizedBox(height: 8),
                    const Text(
                      '昵称最长支持20个字符，请文明用语',
                      style: TextStyle(fontSize: 12, color: Colors.grey),
                    ),
                  ],
                );
              })),
        ),
      ),
    );
  }
}
