import 'package:didvan/constants/assets.dart';
import 'package:didvan/providers/user.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/views/profile/change_password/change_password_state.dart';
import 'package:didvan/views/widgets/didvan/button.dart';
import 'package:didvan/views/widgets/didvan/scaffold.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:didvan/views/widgets/didvan/text_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';

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

  @override
  State<NewPasswordScreen> createState() => _NewPasswordScreenState();
}

class _NewPasswordScreenState extends State<NewPasswordScreen>
    with TickerProviderStateMixin {
  String _newPassword = '';
  final _formKey = GlobalKey<FormState>();

  late AnimationController _slideController;
  late AnimationController _fadeController;
  late AnimationController _buttonController;

  late Animation<Offset> _headerSlideAnimation;
  late Animation<Offset> _field1SlideAnimation;
  late Animation<Offset> _field2SlideAnimation;

  late Animation<double> _fadeAnimation;
  late Animation<double> _buttonScaleAnimation;
  late Animation<double> _buttonFadeAnimation;

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _startAnimations();
  }

  void _initializeAnimations() {
    _slideController = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );

    _fadeController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );

    _buttonController = AnimationController(
      duration: const Duration(milliseconds: 600),
      vsync: this,
    );

    _headerSlideAnimation = Tween<Offset>(
      begin: const Offset(0, -1),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _slideController,
      curve: const Interval(0.0, 0.3, curve: Curves.easeOutCubic),
    ));

    _field1SlideAnimation = Tween<Offset>(
      begin: const Offset(-1.2, 0),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _slideController,
      curve: const Interval(0.2, 0.5, curve: Curves.easeOutCubic),
    ));

    _field2SlideAnimation = Tween<Offset>(
      begin: const Offset(-1.2, 0),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _slideController,
      curve: const Interval(0.35, 0.65, curve: Curves.easeOutCubic),
    ));


    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _fadeController,
      curve: Curves.easeIn,
    ));

    _buttonScaleAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _buttonController,
      curve: Curves.elasticOut,
    ));

    _buttonFadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _buttonController,
      curve: Curves.easeIn,
    ));
  }

  void _startAnimations() {
    _slideController.forward();
    _fadeController.forward();
    Future.delayed(const Duration(milliseconds: 700), () {
      if (mounted) {
        _buttonController.forward();
      }
    });
  }

  @override
  void dispose() {
    _slideController.dispose();
    _fadeController.dispose();
    _buttonController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Stack(
        children: [
          Container(
            padding: const EdgeInsets.only(bottom: 80),
            child: Form(
              key: _formKey,
              child: DidvanScaffold(
                padding: const EdgeInsets.only(
                  top: 16,
                  left: 0,
                  right: 0,
                ),
                appBarData: null,
                showSliversFirst: true,
                slivers: [
                  SliverAppBar(
                    pinned: true,
                    backgroundColor: Theme.of(context).colorScheme.surface,
                    automaticallyImplyLeading: false,
                    leadingWidth: 200,
                    leading: SlideTransition(
                      position: _headerSlideAnimation,
                      child: FadeTransition(
                        opacity: _fadeAnimation,
                        child: Padding(
                          padding: const EdgeInsetsDirectional.only(start: 0.0),
                          child: SvgPicture.asset(
                            Assets.horizontalLogoWithText,
                            fit: BoxFit.contain,
                            height: 80,
                          ),
                        ),
                      ),
                    ),
                    actions: [
                      SlideTransition(
                        position: _headerSlideAnimation,
                        child: FadeTransition(
                          opacity: _buttonFadeAnimation,
                          child: IconButton(
                              onPressed: () {
                                Navigator.of(context).pushNamed(Routes.bookmarks);
                              },
                              icon: SvgPicture.asset(
                                  'lib/assets/icons/hugeicons_telescope-01.svg')),
                        ),
                      ),
                      SlideTransition(
                        position: _headerSlideAnimation,
                        child: FadeTransition(
                          opacity: _fadeAnimation,
                          child: IconButton(
                            onPressed: () => Navigator.of(context).pop(),
                            icon: SvgPicture.asset(
                              'lib/assets/icons/arrow-left.svg',
                              color: const Color.fromARGB(255, 102, 102, 102),
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(width: 8),
                    ],
                  ),
                ],
                children: [
                  const SizedBox(height: 24),
                  SlideTransition(
                    position: _headerSlideAnimation,
                    child: FadeTransition(
                      opacity: _fadeAnimation,
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 25.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Center(
                              child: Image.asset(
                                'lib/assets/images/empty_states/change password.png',
                                width: 300,
                                height: 300,
                              ),
                            ),
                            const SizedBox(height: 24),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: DidvanText(
                                'تغییر رمز عبور',
                                style: Theme.of(context)
                                    .textTheme
                                    .headlineSmall
                                    ?.copyWith(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 18
                                    ),
                                    textAlign: TextAlign.start,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(height: 5,),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 25.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SlideTransition(
                          position: _field1SlideAnimation,
                          child: FadeTransition(
                            opacity: _fadeAnimation,
                            child: DidvanTextField(
                              title: 'رمز عبور جدید',
                              hintText: 'رمز عبور جدید خود را وارد کنید.',
                              onChanged: (value) {
                                setState(() {
                                  _newPassword = value;
                                });
                              },
                              obsecureText: true,
                              prefixSvgPath: 'lib/assets/icons/key.svg',
                              validator: (value) {
                                if (value.isEmpty) {
                                  return 'رمز عبور جدید خود را وارد کنید.';
                                }
                                if (value.length < 8) {
                                  return 'رمز عبور نمی‌تواند کمتر از 8 کاراکتر باشد';
                                }
                                return null;
                              },
                            ),
                          ),
                        ),
                        const SizedBox(height: 16),
                        SlideTransition(
                          position: _field2SlideAnimation,
                          child: FadeTransition(
                            opacity: _fadeAnimation,
                            child: DidvanTextField(
                              title: 'تکرار رمز عبور جدید',
                              hintText: 'رمز عبور جدید خود را مجددا وارد کنید.',
                              onChanged: (value) {},
                              obsecureText: true,
                              prefixSvgPath: 'lib/assets/icons/key.svg',
                              validator: (value) {
                                if (value.isEmpty) {
                                  return 'رمز عبور جدید خود را مجددا وارد کنید.';
                                }
                                if (value != _newPassword) {
                                  return 'تکرار رمز عبور با رمز جدید یکسان نیست';
                                }
                                return null;
                              },
                            ),
                          ),
                        ),
                        const SizedBox(height: 16),
                        // SlideTransition(
                        //   position: _infoSlideAnimation,
                        //   child: FadeTransition(
                        //     opacity: _fadeAnimation,
                        //     child: Container(
                        //       padding: const EdgeInsets.all(16),
                        //       decoration: BoxDecoration(
                        //         color: Theme.of(context)
                        //             .colorScheme
                        //             .primary
                        //             .withOpacity(0.05),
                        //         borderRadius: BorderRadius.circular(12),
                        //         border: Border.all(
                        //           color: Theme.of(context)
                        //               .colorScheme
                        //               .primary
                        //               .withOpacity(0.2),
                        //           width: 1,
                        //         ),
                        //       ),
                        //       child: Row(
                        //         crossAxisAlignment: CrossAxisAlignment.start,
                        //         children: [
                        //           Icon(
                        //             Icons.info_outline,
                        //             color: Theme.of(context).colorScheme.primary,
                        //             size: 20,
                        //           ),
                        //           const SizedBox(width: 12),
                        //           Expanded(
                        //             child: Column(
                        //               crossAxisAlignment:
                        //                   CrossAxisAlignment.start,
                        //               children: [
                        //                 DidvanText(
                        //                   'نکات مهم:',
                        //                   style: Theme.of(context)
                        //                       .textTheme
                        //                       .bodySmall
                        //                       ?.copyWith(
                        //                         fontWeight: FontWeight.bold,
                        //                         color: Theme.of(context)
                        //                             .colorScheme
                        //                             .primary,
                        //                       ),
                        //                 ),
                        //                 const SizedBox(height: 4),
                        //                 DidvanText(
                        //                   '• رمز عبور حداقل 8 کاراکتر باشد\n• از ترکیب حروف و اعداد استفاده کنید\n• رمز عبور را به صورت دوره‌ای تغییر دهید',
                        //                   style: Theme.of(context)
                        //                       .textTheme
                        //                       .bodySmall
                        //                       ?.copyWith(
                        //                         color: const Color.fromARGB(
                        //                             255, 102, 102, 102),
                        //                         height: 1.5,
                        //                       ),
                        //                 ),
                        //               ],
                        //             ),
                        //           ),
                        //         ],
                        //       ),
                        //     ),
                        //   ),
                        // ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          Positioned(
            left: 20,
            right: 20,
            bottom: 20,
            child: FadeTransition(
              opacity: _buttonFadeAnimation,
              child: ScaleTransition(
                scale: _buttonScaleAnimation,
                child: DidvanButton(
                  title: 'ذخیره تغییرات',
                  onPressed: () async {
                    if (_formKey.currentState!.validate()) {
                      final changePasswordState =
                          context.read<ChangePasswordState>();
                      changePasswordState.newPassword = _newPassword;
                      
                      final userProvider = context.read<UserProvider>();
                      final success =
                          await changePasswordState.changePassword(userProvider);
                      
                      if (success && mounted) {
                        Navigator.of(context).pushNamedAndRemoveUntil(
                          Routes.profile,
                          (route) => false,
                        );
                      }
                    }
                  },
                  imagepath: 'lib/assets/icons/verify.svg',
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
