import 'package:base_project/commans/widgets/custom_textform_field.dart';
import 'package:base_project/commans/widgets/custome_elevated_button.dart';
import 'package:base_project/resources/app_colors.dart';
import 'package:base_project/utils/managers/user_manager.dart';
import 'package:base_project/utils/validator/text_feild_validator.dart';
import 'package:base_project/view_model/profile/profile_view_model.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:base_project/core/providers/dynamic_theme_provider.dart';
import 'package:base_project/core/constants/ui_constants.dart';
import 'package:base_project/shared/widgets/app_bar/modern_app_bar.dart';
import 'package:base_project/shared/widgets/inputs/modern_text_field.dart';
import 'package:base_project/shared/widgets/buttons/modern_button.dart';

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

  @override
  State<ChangePassword> createState() => _ChangePasswordState();
}

class _ChangePasswordState extends State<ChangePassword>
    with TickerProviderStateMixin {
  final ValueNotifier<bool> _obscureTextCurrentPass = ValueNotifier<bool>(true);
  final ValueNotifier<bool> _obscureTextNewPass = ValueNotifier<bool>(true);
  final ValueNotifier<bool> _obscureTextConfirmPass = ValueNotifier<bool>(true);

  final TextEditingController _currentPassController = TextEditingController();
  final TextEditingController _newPassController = TextEditingController();
  final TextEditingController _confirmPassController = TextEditingController();

  // Global key for the form
  final _formKey = GlobalKey<FormState>();

  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: UIConstants.durationSlow,
      vsync: this,
    );

    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: UIConstants.curveNormal,
    ));

    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: UIConstants.curveNormal,
    ));

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _animationController.forward();
    });
  }

  @override
  void dispose() {
    _currentPassController.dispose();
    _newPassController.dispose();
    _confirmPassController.dispose();
    _obscureTextCurrentPass.dispose();
    _obscureTextNewPass.dispose();
    _obscureTextConfirmPass.dispose();
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<DynamicThemeProvider>(
      builder: (context, dynamicThemeProvider, child) {
        final colorScheme = dynamicThemeProvider.getCurrentColorScheme(
            Theme.of(context).brightness == Brightness.dark);
        final textTheme = Theme.of(context).textTheme;

        return Scaffold(
          appBar: ModernAppBar(
            title: 'Change Password',
            automaticallyImplyLeading: true,
            leading: IconButton(
              icon: Icon(Icons.arrow_back),
              onPressed: () => Navigator.pop(context),
            ),
            showThemeToggle: false,
            showUserProfile: false,
          ),
          body: AnimatedBuilder(
            animation: _animationController,
            builder: (context, child) {
              return FadeTransition(
                opacity: _fadeAnimation,
                child: SlideTransition(
                  position: _slideAnimation,
                  child: Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [
                          colorScheme.primary.withOpacity(0.1),
                          colorScheme.secondary.withOpacity(0.05),
                          colorScheme.surface,
                        ],
                        stops: const [0.0, 0.3, 1.0],
                      ),
                    ),
                    child: SingleChildScrollView(
                      padding: UIConstants.getResponsivePadding(
                        context,
                        mobile: UIConstants.screenPaddingMedium,
                        tablet: UIConstants.screenPaddingLarge,
                        desktop: UIConstants.screenPaddingLarge,
                      ),
                      child: Form(
                        key: _formKey,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            // Security Header Section
                            _buildSecurityHeader(
                                context, colorScheme, textTheme),

                            SizedBox(
                                height: UIConstants.getResponsiveSpacing(
                              context,
                              mobile: UIConstants.spacing32,
                              tablet: UIConstants.spacing40,
                              desktop: UIConstants.spacing48,
                            )),

                            // Password Form Section
                            _buildPasswordForm(context, colorScheme, textTheme),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        );
      },
    );
  }

  Widget _buildSecurityHeader(
      BuildContext context, ColorScheme colorScheme, TextTheme textTheme) {
    return Container(
      padding: UIConstants.getResponsivePadding(
        context,
        mobile: UIConstants.cardPaddingLarge,
        tablet: UIConstants.cardPaddingLarge,
        desktop: UIConstants.cardPaddingLarge,
      ),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.95),
        borderRadius: BorderRadius.circular(UIConstants.radius24),
        border: Border.all(
          color: colorScheme.surface.withOpacity(0.2),
          width: 1,
        ),
        boxShadow: [
          BoxShadow(
            color: colorScheme.primary.withOpacity(0.1),
            blurRadius: 20,
            offset: const Offset(0, 10),
            spreadRadius: 5,
          ),
        ],
      ),
      child: Column(
        children: [
          // Security Icon
          Container(
            padding: const EdgeInsets.all(UIConstants.spacing20),
            decoration: BoxDecoration(
              color: colorScheme.primary.withOpacity(0.1),
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.security,
              size: UIConstants.getResponsiveValue(
                context,
                mobile: 40,
                tablet: 48,
                desktop: 56,
              ),
              color: colorScheme.primary,
            ),
          ),

          SizedBox(height: UIConstants.spacing24),

          Text(
            'Change Password',
            style: textTheme.headlineSmall?.copyWith(
              fontWeight: FontWeight.w700,
              color: colorScheme.primary,
            ),
            textAlign: TextAlign.center,
          ),

          SizedBox(height: UIConstants.spacing12),

          Text(
            'Update your account security by changing your password. Make sure to use a strong password.',
            style: textTheme.bodyMedium?.copyWith(
              color: colorScheme.onSurfaceVariant,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildPasswordForm(
      BuildContext context, ColorScheme colorScheme, TextTheme textTheme) {
    return Container(
      padding: UIConstants.getResponsivePadding(
        context,
        mobile: UIConstants.cardPaddingLarge,
        tablet: UIConstants.cardPaddingLarge,
        desktop: UIConstants.cardPaddingLarge,
      ),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.95),
        borderRadius: BorderRadius.circular(UIConstants.radius24),
        border: Border.all(
          color: colorScheme.surface.withOpacity(0.2),
          width: 1,
        ),
        boxShadow: [
          BoxShadow(
            color: colorScheme.primary.withOpacity(0.1),
            blurRadius: 20,
            offset: const Offset(0, 10),
            spreadRadius: 5,
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Password Details',
            style: textTheme.titleLarge?.copyWith(
              fontWeight: FontWeight.w600,
              color: colorScheme.primary,
            ),
          ),
          SizedBox(height: UIConstants.spacing24),

          // Current Password Field
          ValueListenableBuilder(
            valueListenable: _obscureTextCurrentPass,
            builder: (context, value, child) {
              return ModernTextField(
                label: 'Current Password',
                hint: 'Enter your current password',
                controller: _currentPassController,
                prefixIcon: Icon(Icons.lock_outline),
                suffixIcon: IconButton(
                  icon: Icon(
                    _obscureTextCurrentPass.value
                        ? Icons.visibility_off
                        : Icons.visibility,
                  ),
                  onPressed: () {
                    _obscureTextCurrentPass.value =
                        !_obscureTextCurrentPass.value;
                  },
                ),
                obscureText: _obscureTextCurrentPass.value,
                validator: TextFieldValidator.validatePassword,
              );
            },
          ),

          SizedBox(
              height: UIConstants.getResponsiveSpacing(
            context,
            mobile: UIConstants.spacing20,
            tablet: UIConstants.spacing24,
            desktop: UIConstants.spacing24,
          )),

          // New Password Field
          ValueListenableBuilder(
            valueListenable: _obscureTextNewPass,
            builder: (context, value, child) {
              return ModernTextField(
                label: 'New Password',
                hint: 'Enter your new password',
                controller: _newPassController,
                prefixIcon: Icon(Icons.lock_outline),
                suffixIcon: IconButton(
                  icon: Icon(
                    _obscureTextNewPass.value
                        ? Icons.visibility_off
                        : Icons.visibility,
                  ),
                  onPressed: () {
                    _obscureTextNewPass.value = !_obscureTextNewPass.value;
                  },
                ),
                obscureText: _obscureTextNewPass.value,
                validator: TextFieldValidator.validatePassword,
              );
            },
          ),

          SizedBox(
              height: UIConstants.getResponsiveSpacing(
            context,
            mobile: UIConstants.spacing20,
            tablet: UIConstants.spacing24,
            desktop: UIConstants.spacing24,
          )),

          // Confirm Password Field
          ValueListenableBuilder(
            valueListenable: _obscureTextConfirmPass,
            builder: (context, value, child) {
              return ModernTextField(
                label: 'Confirm New Password',
                hint: 'Confirm your new password',
                controller: _confirmPassController,
                prefixIcon: Icon(Icons.lock_outline),
                suffixIcon: IconButton(
                  icon: Icon(
                    _obscureTextConfirmPass.value
                        ? Icons.visibility_off
                        : Icons.visibility,
                  ),
                  onPressed: () {
                    _obscureTextConfirmPass.value =
                        !_obscureTextConfirmPass.value;
                  },
                ),
                obscureText: _obscureTextConfirmPass.value,
                validator: (value) {
                  return TextFieldValidator.validateConfirmPassword(
                      value, _newPassController.text);
                },
              );
            },
          ),

          SizedBox(
              height: UIConstants.getResponsiveSpacing(
            context,
            mobile: UIConstants.spacing32,
            tablet: UIConstants.spacing40,
            desktop: UIConstants.spacing48,
          )),

          // Change Password Button
          Consumer<ProfileViewModel>(
            builder: (context, provider, _) {
              return ModernButton(
                text: 'Change Password',
                type: ModernButtonType.primary,
                size: ModernButtonSize.large,
                isLoading: provider.isUpdating,
                icon: Icon(Icons.security),
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    final uId = UserManager().userId;

                    final data = {
                      "userId": uId,
                      "oldPassword": _currentPassController.text,
                      "newPassword": _newPassController.text,
                      "confirmPassword": _confirmPassController.text,
                    };

                    provider.changePassword(data);
                  }
                },
              );
            },
          ),
        ],
      ),
    );
  }
}
