import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/widgets/alert/data_alert_model.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../preference/data_preference.dart';
import '../../resouce/base_color.dart';
import '../../shared/router_gage.dart';
import '../../widgets/back_button.dart';
import '../../widgets/support_button.dart';
import '../login/login_viewmodel.dart';
import 'change_pass_viewmodel.dart';

class ChangePassScreen extends BaseScreen {
  const ChangePassScreen({super.key});

  @override
  State<ChangePassScreen> createState() => _ChangePassScreenState();
}

class _ChangePassScreenState extends BaseState<ChangePassScreen> with BasicState {
  final TextEditingController _passController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  final viewModel = Get.put(ChangePassViewModel());
  final _phone = DataPreference.instance.phone ?? "";

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _focusNode.requestFocus();
    });

    viewModel.onShowAlertError = (message) {
      showAlertError(content: message);
    };
  }

  @override
  void dispose() {
    _focusNode.dispose();
    _passController.dispose();
    super.dispose();
  }

  @override
  Widget createBody() {
    return GestureDetector(
      onTap: hideKeyboard,
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          automaticallyImplyLeading: false,
          backgroundColor: Colors.white,
          centerTitle: true,
          leading: CustomBackButton(),
          actions: [SupportButton()],
        ),
        backgroundColor: Colors.white,
        body: SafeArea(
          child: Stack(
            children: [
              SingleChildScrollView(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Text(
                      "Đổi mật khẩu",
                      style: TextStyle(color: BaseColor.second600, fontSize: 24, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 16),
                    _buildWelcomeText(),
                    const SizedBox(height: 16),
                    _buildPasswordField(),
                    _buildErrorText(),
                    const SizedBox(height: 8),
                    _buildActionRow(),
                    const SizedBox(height: 8),
                  ],
                ),
              ),
              SizedBox.expand(),
              Positioned(left: 0, right: 0, bottom: 16, child: _buildContinueButton()),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildWelcomeText() {
    return RichText(
      text: TextSpan(
        style: const TextStyle(fontSize: 14, color: BaseColor.second500),
        children: [
          const TextSpan(text: "Nhập mật khẩu đăng nhập cho tài khoản "),
          TextSpan(
            text: _phone,
            style: const TextStyle(fontWeight: FontWeight.w500, color: BaseColor.primary500),
          ),
        ],
      ),
    );
  }

  Widget _buildPasswordField() {
    return Obx(() {
      return TextField(
        controller: _passController,
        focusNode: _focusNode,
        keyboardType: TextInputType.number,
        obscureText: !viewModel.isPasswordVisible.value,
        onChanged: viewModel.onPasswordChanged,
        decoration: InputDecoration(
          hintText: "Nhập mật khẩu",
          prefixIcon: const Icon(Icons.password, color: BaseColor.second500),
          hintStyle: const TextStyle(color: BaseColor.second200),
          fillColor: Colors.white,
          filled: true,
          contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
            borderSide: const BorderSide(color: Colors.grey, width: 1),
          ),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
            borderSide: const BorderSide(color: Colors.grey, width: 1),
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
            borderSide: const BorderSide(color: Colors.grey, width: 1),
          ),
          suffixIcon: IconButton(
            icon: Icon(
              viewModel.isPasswordVisible.value ? Icons.visibility : Icons.visibility_off,
              color: BaseColor.second500,
            ),
            onPressed: viewModel.togglePasswordVisibility,
          ),
        ),
      );
    });
  }

  Widget _buildErrorText() {
    return Obx(() {
      if (viewModel.loginState.value == LoginState.error) {
        return Padding(
          padding: const EdgeInsets.only(top: 4),
          child: Text("Sai mật khẩu, vui lòng thử lại!", style: TextStyle(color: BaseColor.primary400)),
        );
      }
      return const SizedBox.shrink();
    });
  }

  Widget _buildActionRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        TextButton(
          onPressed: () {
            final dataAlert = DataAlertModel(
              title: "Quên mật khẩu",
              content: "Bạn cần đăng xuất khỏi tài khoản này để đặt lại mật khẩu. Bạn chắc chứ?.",
              background: "assets/images/ic_pipi_03.png",
              buttons: [AlertButton(
                text: "Đồng ý",
                onPressed: () {
                  DataPreference.instance.clearLoginToken();
                  _safeBackToLogin();
                },
                bgColor: BaseColor.primary500,
                textColor: Colors.white,
                isPrimary: true,
              ),
                AlertButton(
                  text: "Huỷ",
                  onPressed: () => Get.back(),
                  bgColor: Colors.white,
                  textColor: BaseColor.second500,
                  isPrimary: false,
                ),],
            );
            showAlert(data: dataAlert);
          },
          child: const Text("Quên mật khẩu?", style: TextStyle(fontSize: 14, color: Color(0xFF3662FE))),
        ),
      ],
    );
  }

  Widget _buildContinueButton() {
    return Obx(() {
      bool enabled = false;
      Color color = BaseColor.second400;
      switch (viewModel.loginState.value) {
        case LoginState.typing:
          if (viewModel.password.value.isNotEmpty) {
            color = BaseColor.primary500;
            enabled = true;
          } else {
            enabled = false;
            color = BaseColor.second400;
          }
          break;
        case LoginState.error:
        case LoginState.idle:
        enabled = false;
        color = BaseColor.second400;
          break;
      }

      return Container(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: color,
            minimumSize: const Size.fromHeight(48),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          ),
          onPressed: () {
            enabled ? viewModel.accountCheckForPasswordChange() : null;
          },
          child: const Text(
            "Tiếp tục",
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white),
          ),
        ),
      );
    });
  }

  void _safeBackToLogin() {
    bool found = false;
    Navigator.popUntil(Get.context!, (route) {
      final matched = route.settings.name == loginScreen;
      if (matched) found = true;
      return matched;
    });
    final phone = DataPreference.instance.phone;
    if (phone != null) {
      if (!found) {
        Get.offAllNamed(loginScreen, arguments: phone);
      }
    } else {
      DataPreference.instance.clearData();
      Get.offAllNamed(onboardingScreen);
    }
  }
}
