import 'package:chat/configs/app_colors.dart';
import 'package:chat/controllers/user_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class UserInfoNicknamePage extends StatefulWidget {
  const UserInfoNicknamePage({Key? key}) : super(key: key);

  @override
  State<UserInfoNicknamePage> createState() => _UserInfoNicknamePageState();
}

class _UserInfoNicknamePageState extends State<UserInfoNicknamePage> {
  late TextEditingController _editingController;
  late String _originNickname;
  late String _nickname;

  @override
  void initState() {
    super.initState();
    _editingController = TextEditingController(text: Get.arguments['nickname']);
    _nickname = Get.arguments['nickname'];
    _originNickname = Get.arguments['nickname'];
  }

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

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
        appBar: AppBar(
          title: const Text(
            '修改昵称',
          ),
          actions: [
            TextButton(
              style: ButtonStyle(
                foregroundColor: MaterialStateProperty.resolveWith((states) {
                  if (states.contains(MaterialState.disabled)) {
                    return AppColors.unactive;
                  } else {
                    return AppColors.active;
                  }
                }),
              ),
              onPressed: _nickname.length < 2 || _originNickname == _nickname
                  ? null
                  : () async {
                      if (await UserController.to
                          .updateNickname(_editingController.text)) {
                        Get.back();
                      }
                    },
              child: const Text(
                '保存',
              ),
            ),
          ],
        ),
        body: Container(
          padding: const EdgeInsets.all(32.0),
          child: TextField(
            controller: _editingController,
            onChanged: (e) {
              setState(() {
                _nickname = e;
              });
            },
            decoration: const InputDecoration(
              labelText: '昵称',
              hintText: '请输入昵称',
              labelStyle: TextStyle(
                color: AppColors.unactive,
              ),
              focusedBorder: UnderlineInputBorder(
                borderSide: BorderSide(
                  color: AppColors.unactive,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
