/// Change Password Page
///
/// Allows users to change their password.
/// Features:
/// - Current password verification
/// - New password with validation
/// - Password confirmation
/// - Show/hide password toggles
/// - Security tips
library;

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.dart';

/// Change Password Page
///
/// Page for changing user password with validation and security tips.
class ChangePasswordPage extends HookConsumerWidget {
  const ChangePasswordPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // Form key for validation
    final formKey = useMemoized(() => GlobalKey<FormState>());

    // Password controllers
    final currentPasswordController = useTextEditingController();
    final newPasswordController = useTextEditingController();
    final confirmPasswordController = useTextEditingController();

    // Password visibility states
    final currentPasswordVisible = useState<bool>(false);
    final newPasswordVisible = useState<bool>(false);
    final confirmPasswordVisible = useState<bool>(false);

    // Password match state
    final passwordsMatch = useState<bool?>(null);

    // Listen to password changes for validation
    useEffect(() {
      void listener() {
        final newPass = newPasswordController.text;
        final confirmPass = confirmPasswordController.text;

        if (confirmPass.isEmpty) {
          passwordsMatch.value = null;
        } else {
          passwordsMatch.value = newPass == confirmPass;
        }
      }

      newPasswordController.addListener(listener);
      confirmPasswordController.addListener(listener);

      return () {
        newPasswordController.removeListener(listener);
        confirmPasswordController.removeListener(listener);
      };
    }, []);

    final colorScheme = Theme.of(context).colorScheme;

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      appBar: AppBar(
        backgroundColor: colorScheme.surface,
        elevation: 0,
        leading: IconButton(
          icon: FaIcon(FontAwesomeIcons.arrowLeft, color: colorScheme.onSurface, size: 20),
          onPressed: () => context.pop(),
        ),
        title: Text(
          'Thay đổi mật khẩu',
          style: TextStyle(
            color: colorScheme.onSurface,
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        centerTitle: false,
        actions: const [SizedBox(width: AppSpacing.sm)],
      ),
      body: Form(
        key: formKey,
        child: SingleChildScrollView(
          child: Column(
            children: [
              const SizedBox(height: AppSpacing.md),

              // Form Card
              Container(
                margin: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
                padding: const EdgeInsets.all(AppSpacing.md),
                decoration: BoxDecoration(
                  color: colorScheme.surface,
                  borderRadius: BorderRadius.circular(AppRadius.card),
                  boxShadow: [
                    BoxShadow(
                      color: colorScheme.shadow.withValues(alpha: 0.05),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Title
                    Text(
                      'Cập nhật mật khẩu',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: colorScheme.onSurface,
                      ),
                    ),

                    const SizedBox(height: AppSpacing.lg),

                    // Current Password
                    _buildPasswordField(
                      colorScheme: colorScheme,
                      label: 'Mật khẩu hiện tại',
                      controller: currentPasswordController,
                      isVisible: currentPasswordVisible,
                      required: true,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Vui lòng nhập mật khẩu hiện tại';
                        }
                        return null;
                      },
                    ),

                    const SizedBox(height: AppSpacing.md),

                    // New Password
                    _buildPasswordField(
                      colorScheme: colorScheme,
                      label: 'Mật khẩu mới',
                      controller: newPasswordController,
                      isVisible: newPasswordVisible,
                      required: true,
                      helpText: 'Mật khẩu phải có ít nhất 6 ký tự',
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Vui lòng nhập mật khẩu mới';
                        }
                        if (value.length < 6) {
                          return 'Mật khẩu phải có ít nhất 6 ký tự';
                        }
                        return null;
                      },
                    ),

                    const SizedBox(height: AppSpacing.md),

                    // Confirm Password
                    _buildPasswordField(
                      colorScheme: colorScheme,
                      label: 'Nhập lại mật khẩu mới',
                      controller: confirmPasswordController,
                      isVisible: confirmPasswordVisible,
                      required: true,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Vui lòng nhập lại mật khẩu mới';
                        }
                        if (value != newPasswordController.text) {
                          return 'Mật khẩu không khớp';
                        }
                        return null;
                      },
                    ),

                    // Password match indicator
                    if (passwordsMatch.value != null) ...[
                      const SizedBox(height: 8),
                      Row(
                        children: [
                          FaIcon(
                            passwordsMatch.value == true
                                ? FontAwesomeIcons.solidCircleCheck
                                : FontAwesomeIcons.circleXmark,
                            size: 14,
                            color: passwordsMatch.value == true
                                ? AppColors.success
                                : AppColors.danger,
                          ),
                          const SizedBox(width: 8),
                          Text(
                            passwordsMatch.value == true
                                ? 'Mật khẩu khớp'
                                : 'Mật khẩu không khớp',
                            style: TextStyle(
                              fontSize: 14,
                              color: passwordsMatch.value == true
                                  ? AppColors.success
                                  : AppColors.danger,
                            ),
                          ),
                        ],
                      ),
                    ],

                    const SizedBox(height: AppSpacing.lg),

                    // Security Tips
                    _buildSecurityTips(colorScheme),
                  ],
                ),
              ),

              const SizedBox(height: AppSpacing.lg),

              // Action Buttons
              _buildActionButtons(
                context: context,
                colorScheme: colorScheme,
                formKey: formKey,
                currentPasswordController: currentPasswordController,
                newPasswordController: newPasswordController,
                confirmPasswordController: confirmPasswordController,
              ),

              const SizedBox(height: AppSpacing.lg),
            ],
          ),
        ),
      ),
    );
  }

  /// Build password field with show/hide toggle
  Widget _buildPasswordField({
    required ColorScheme colorScheme,
    required String label,
    required TextEditingController controller,
    required ValueNotifier<bool> isVisible,
    bool required = false,
    String? helpText,
    String? Function(String?)? validator,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        RichText(
          text: TextSpan(
            text: label,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              color: colorScheme.onSurface,
            ),
            children: [
              if (required)
                const TextSpan(
                  text: ' *',
                  style: TextStyle(color: AppColors.danger),
                ),
            ],
          ),
        ),
        const SizedBox(height: 8),
        TextFormField(
          controller: controller,
          obscureText: !isVisible.value,
          validator: validator,
          decoration: InputDecoration(
            hintText: 'Nhập $label',
            hintStyle: TextStyle(
              color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6),
              fontSize: 14,
            ),
            filled: true,
            fillColor: colorScheme.surfaceContainerLowest,
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 12,
            ),
            suffixIcon: IconButton(
              icon: FaIcon(
                isVisible.value ? FontAwesomeIcons.eyeSlash : FontAwesomeIcons.eye,
                size: 18,
                color: colorScheme.onSurfaceVariant,
              ),
              onPressed: () {
                isVisible.value = !isVisible.value;
              },
            ),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(color: colorScheme.outlineVariant),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(color: colorScheme.outlineVariant),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: BorderSide(
                color: colorScheme.primary,
                width: 2,
              ),
            ),
            errorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: const BorderSide(color: AppColors.danger),
            ),
            focusedErrorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(AppRadius.input),
              borderSide: const BorderSide(color: AppColors.danger, width: 2),
            ),
          ),
        ),
        if (helpText != null) ...[
          const SizedBox(height: 8),
          Text(
            helpText,
            style: TextStyle(fontSize: 12, color: colorScheme.onSurfaceVariant),
          ),
        ],
      ],
    );
  }

  /// Build security tips section
  Widget _buildSecurityTips(ColorScheme colorScheme) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: colorScheme.surfaceContainerLowest,
        borderRadius: BorderRadius.circular(AppRadius.card),
        border: Border.all(color: colorScheme.outlineVariant),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Gợi ý bảo mật:',
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: colorScheme.onSurface,
            ),
          ),
          const SizedBox(height: 12),
          _buildSecurityTip('Sử dụng ít nhất 8 ký tự', colorScheme),
          _buildSecurityTip('Kết hợp chữ hoa, chữ thường và số', colorScheme),
          _buildSecurityTip('Bao gồm ký tự đặc biệt (!@#\$%^&*)', colorScheme),
          _buildSecurityTip('Không sử dụng thông tin cá nhân', colorScheme),
          _buildSecurityTip('Thường xuyên thay đổi mật khẩu', colorScheme),
        ],
      ),
    );
  }

  /// Build individual security tip
  Widget _buildSecurityTip(String text, ColorScheme colorScheme) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const FaIcon(
            FontAwesomeIcons.circleCheck,
            size: 14,
            color: AppColors.success,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              text,
              style: TextStyle(
                fontSize: 13,
                color: colorScheme.onSurfaceVariant,
                height: 1.4,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Build action buttons
  Widget _buildActionButtons({
    required BuildContext context,
    required ColorScheme colorScheme,
    required GlobalKey<FormState> formKey,
    required TextEditingController currentPasswordController,
    required TextEditingController newPasswordController,
    required TextEditingController confirmPasswordController,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      child: Row(
        children: [
          // Cancel Button
          Expanded(
            child: OutlinedButton(
              onPressed: () {
                context.pop();
              },
              style: OutlinedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 14),
                side: BorderSide(color: colorScheme.outlineVariant),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(AppRadius.button),
                ),
              ),
              child: Text(
                'Hủy bỏ',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: colorScheme.onSurface,
                ),
              ),
            ),
          ),

          const SizedBox(width: AppSpacing.sm),

          // Change Password Button
          Expanded(
            flex: 2,
            child: ElevatedButton.icon(
              onPressed: () {
                if (formKey.currentState?.validate() ?? false) {
                  _changePassword(
                    context,
                    currentPasswordController.text,
                    newPasswordController.text,
                  );
                }
              },
              icon: const FaIcon(FontAwesomeIcons.key, size: 18),
              label: const Text(
                'Đổi mật khẩu',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: colorScheme.primary,
                foregroundColor: colorScheme.onPrimary,
                padding: const EdgeInsets.symmetric(vertical: 14),
                elevation: 0,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(AppRadius.button),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Change password
  void _changePassword(
    BuildContext context,
    String currentPassword,
    String newPassword,
  ) {
    // TODO: Implement actual password change with backend
    // For now, just show success message

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Mật khẩu đã được thay đổi thành công!'),
        backgroundColor: AppColors.success,
        duration: Duration(seconds: 2),
      ),
    );

    // Navigate back after a short delay
    Future.delayed(const Duration(milliseconds: 500), () {
      if (context.mounted) {
        context.pop();
      }
    });
  }
}
