import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:real_estate_mobile/core/constants/app_colors.dart';
import 'package:real_estate_mobile/features/profile/presentation/providers/profile_provider.dart';
import 'package:real_estate_mobile/features/profile/presentation/widgets/profile_shared_widgets.dart';

class ChangePasswordTab extends ConsumerStatefulWidget {
  const ChangePasswordTab({super.key});

  @override
  ConsumerState<ChangePasswordTab> createState() => _ChangePasswordTabState();
}

class _ChangePasswordTabState extends ConsumerState<ChangePasswordTab> {
  final _currentPasswordController = TextEditingController();
  final _newPasswordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  bool _showCurrentPassword = false;
  bool _showNewPassword = false;
  bool _showConfirmPassword = false;
  bool _isChangingPassword = false;

  @override
  void dispose() {
    _currentPasswordController.dispose();
    _newPasswordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      padding: const EdgeInsets.fromLTRB(27, 10, 27, 30),
      children: [
        const Text(
          'Password & Security',
          style: TextStyle(
            fontFamily: 'Fractul',
            fontSize: 15,
            fontWeight: FontWeight.w700,
            color: AppColors.primaryDark,
          ),
        ),
        const SizedBox(height: 8),
        const Text(
          'Update your password to keep your account secure.',
          style: TextStyle(
            fontFamily: 'SourceSerif4',
            fontSize: 14,
            fontWeight: FontWeight.w400,
            color: AppColors.primaryDark,
          ),
        ),
        const SizedBox(height: 30),

        _buildPasswordField(
          label: 'Current Password',
          controller: _currentPasswordController,
          obscure: !_showCurrentPassword,
          onToggle: () =>
              setState(() => _showCurrentPassword = !_showCurrentPassword),
        ),
        const SizedBox(height: 24),
        _buildPasswordField(
          label: 'New Password',
          controller: _newPasswordController,
          obscure: !_showNewPassword,
          onToggle: () =>
              setState(() => _showNewPassword = !_showNewPassword),
        ),
        const SizedBox(height: 4),
        Text(
          'Min 8 characters, 1 uppercase, 1 lowercase, 1 number',
          style: TextStyle(
            fontFamily: 'SourceSerif4',
            fontSize: 11,
            color: AppColors.primaryDark.withValues(alpha: 0.5),
          ),
        ),
        const SizedBox(height: 24),
        _buildPasswordField(
          label: 'Confirm New Password',
          controller: _confirmPasswordController,
          obscure: !_showConfirmPassword,
          onToggle: () =>
              setState(() => _showConfirmPassword = !_showConfirmPassword),
        ),
        const SizedBox(height: 40),
        ProfileActionButtons(
          onSave: _changePassword,
          onCancel: () => context.go('/home'),
          isSaving: _isChangingPassword,
          saveLabel: 'Update Password',
        ),
      ],
    );
  }

  Widget _buildPasswordField({
    required String label,
    required TextEditingController controller,
    required bool obscure,
    required VoidCallback onToggle,
  }) {
    final borderSide = BorderSide(
      color: AppColors.primaryDark.withValues(alpha: 0.1),
      width: 1,
    );
    final border = OutlineInputBorder(
      borderRadius: BorderRadius.circular(7),
      borderSide: borderSide,
    );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontFamily: 'Fractul',
            fontSize: 14,
            fontWeight: FontWeight.w400,
            color: AppColors.primaryDark,
          ),
        ),
        const SizedBox(height: 14),
        TextField(
          controller: controller,
          obscureText: obscure,
          style: const TextStyle(
            fontFamily: 'SourceSerif4',
            fontSize: 14,
            fontWeight: FontWeight.w400,
            color: AppColors.primaryDark,
          ),
          decoration: InputDecoration(
            contentPadding:
                const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
            border: border,
            enabledBorder: border,
            focusedBorder: border,
            suffixIcon: GestureDetector(
              onTap: onToggle,
              child: Icon(
                obscure ? Icons.visibility_off_outlined : Icons.visibility_outlined,
                size: 18,
                color: AppColors.primaryDark.withValues(alpha: 0.5),
              ),
            ),
            suffixIconConstraints: const BoxConstraints(minWidth: 40),
          ),
        ),
      ],
    );
  }

  Future<void> _changePassword() async {
    final current = _currentPasswordController.text.trim();
    final newPw = _newPasswordController.text.trim();
    final confirm = _confirmPasswordController.text.trim();

    if (current.isEmpty || newPw.isEmpty || confirm.isEmpty) {
      _showSnackBar('Please fill in all fields', isError: true);
      return;
    }

    final passwordRegex = RegExp(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$');
    if (!passwordRegex.hasMatch(newPw)) {
      _showSnackBar(
          'Password must be at least 8 characters with uppercase, lowercase, and number',
          isError: true);
      return;
    }

    if (newPw != confirm) {
      _showSnackBar('Passwords do not match', isError: true);
      return;
    }

    setState(() => _isChangingPassword = true);
    try {
      final repo = ref.read(profileRepositoryProvider);
      await repo.changePassword(current, newPw);
      _currentPasswordController.clear();
      _newPasswordController.clear();
      _confirmPasswordController.clear();
      _showSnackBar('Password changed successfully');
    } catch (e) {
      _showSnackBar('$e', isError: true);
    } finally {
      if (mounted) setState(() => _isChangingPassword = false);
    }
  }

  void _showSnackBar(String message, {bool isError = false}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: isError ? Colors.red : const Color(0xFF638559),
      ),
    );
  }
}
