import 'dart:async';
import 'package:didvan/constants/assets.dart';
import 'package:didvan/config/design_config.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:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:provider/provider.dart';

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

  @override
  State<VerifyOtpScreen> createState() => _VerifyOtpScreenState();
}

class _VerifyOtpScreenState extends State<VerifyOtpScreen>
    with TickerProviderStateMixin {
  String _otpCode = '';
  bool _hasError = false;
  Timer? _timer;
  int _remainingTime = 120;

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

  late Animation<Offset> _headerSlideAnimation;
  late Animation<Offset> _contentSlideAnimation;
  late Animation<double> _fadeAnimation;
  late Animation<double> _buttonScaleAnimation;
  late Animation<double> _buttonFadeAnimation;

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

  void _startTimer() {
    _remainingTime = 120;
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_remainingTime > 0) {
        setState(() {
          _remainingTime--;
        });
      } else {
        _timer?.cancel();
      }
    });
  }

  String get _formattedTime {
    final minutes = (_remainingTime ~/ 60).toString().padLeft(2, '0');
    final seconds = (_remainingTime % 60).toString().padLeft(2, '0');
    return '$minutes:$seconds';
  }

  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.4, curve: Curves.easeOutCubic),
    ));

    _contentSlideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _slideController,
      curve: const Interval(0.2, 0.8, 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() {
    _timer?.cancel();
    _slideController.dispose();
    _fadeController.dispose();
    _buttonController.dispose();
    super.dispose();
  }

  Future<void> _verifyCode(String code) async {
    if (code.length != 6) return;

    final state = context.read<ChangePasswordState>();
    final success = await state.verifyOtpToken(code);

    if (mounted) {
      if (success) {
        state.currentPageIndex = 1;
      } else {
        setState(() {
          _hasError = true;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final userProvider = context.read<UserProvider>();
    final phoneNumber = userProvider.user.phoneNumber;
    final errorColor = Theme.of(context).colorScheme.error;

    return Material(
      child: Stack(
        children: [
          Container(
            padding: const EdgeInsets.only(bottom: 150),
            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: _contentSlideAnimation,
                  child: FadeTransition(
                    opacity: _fadeAnimation,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 25.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Center(
                              child: Image.asset(
                                'lib/assets/images/empty_states/change password.png',
                                height: 320,
                              ),
                            ),
                          ),
                          const SizedBox(height: 24),
                          DidvanText(
                            'تغییر رمز عبور',
                            style: Theme.of(context)
                                .textTheme
                                .headlineSmall
                                ?.copyWith(
                                    fontWeight: FontWeight.bold, fontSize: 22),
                          ),
                          const SizedBox(height: 14),
                          Text.rich(
                            TextSpan(
                              style: Theme.of(context)
                                  .textTheme
                                  .bodyMedium
                                  ?.copyWith(
                                    color: const Color.fromARGB(
                                        255, 102, 102, 102),
                                    height: 1.5,
                                  ),
                              children: [
                                const TextSpan(
                                    text: 'ما یک کد تأیید 6 رقمی به شماره '),
                                TextSpan(
                                  text: phoneNumber,
                                  style: TextStyle(
                                    color:
                                        Theme.of(context).colorScheme.primary,
                                    fontWeight: FontWeight.bold,
                                    textBaseline: TextBaseline.alphabetic,
                                  ),
                                ),
                                const TextSpan(
                                    text:
                                        ' ارسال کرده‌ایم. لطفاً کد خود را در زیر وارد کنید 👇'),
                              ],
                            ),
                            textAlign: TextAlign.start,
                            textDirection: TextDirection.rtl,
                          ),
                          const SizedBox(height: 32),
                          Directionality(
                            textDirection: TextDirection.ltr,
                            child: PinCodeTextField(
                              keyboardType: TextInputType.number,
                              animationType: AnimationType.scale,
                              cursorColor:
                                  Theme.of(context).colorScheme.onSurface,
                              hintCharacter: '-',
                              pinTheme: PinTheme(
                                fieldHeight: 58,
                                fieldWidth: 58,
                                selectedColor: _hasError
                                    ? const Color.fromARGB(255, 190, 18, 60)
                                    : Theme.of(context).colorScheme.primary,
                                inactiveColor: _hasError
                                    ? errorColor
                                    : Theme.of(context).colorScheme.outline,
                                activeFillColor: _hasError
                                    ? const Color.fromARGB(255, 190, 18, 60)
                                    : Theme.of(context).colorScheme.primary,
                                activeColor: _hasError
                                    ? const Color.fromARGB(255, 190, 18, 60)
                                    : Theme.of(context).colorScheme.primary,
                                borderRadius: DesignConfig.lowBorderRadius,
                                borderWidth: 1,
                                shape: PinCodeFieldShape.box,
                              ),
                              appContext: context,
                              length: 6,
                              onChanged: (value) {
                                setState(() {
                                  _otpCode = value;
                                  if (_hasError) _hasError = false;
                                });
                              },
                              onCompleted: (value) {
                                _verifyCode(value);
                              },
                            ),
                          ),
                          if (_hasError)
                            Padding(
                              padding: const EdgeInsets.only(top: 8.0),
                              child: SizedBox(
                                width: double.infinity,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    SvgPicture.asset(
                                        'lib/assets/icons/error.svg'),
                                    const SizedBox(
                                      width: 10,
                                    ),
                                    const Text(
                                      'کد وارد شده صحیح نمی‌باشد',
                                      style: TextStyle(
                                        color: Color.fromARGB(255, 190, 18, 60),
                                        fontSize: 12,
                                        fontWeight: FontWeight.bold,
                                      ),
                                      textAlign: TextAlign.center,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Positioned(
            left: 20,
            right: 20,
            bottom: 20,
            child: FadeTransition(
              opacity: _buttonFadeAnimation,
              child: ScaleTransition(
                scale: _buttonScaleAnimation,
                child: Column(
                  children: [
                    DidvanButton(
                      title: 'تأیید',
                      onPressed: () {
                        _verifyCode(_otpCode);
                      },
                      imagepath: 'lib/assets/icons/verify.svg',
                      enabled: _otpCode.length == 6,
                    ),
                    const SizedBox(height: 8),
                    TextButton(
                      onPressed: _remainingTime == 0
                          ? () {
                              context.read<ChangePasswordState>().sendOtp();
                              _startTimer();
                              setState(() {
                                _hasError = false;
                              });
                            }
                          : null,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          SvgPicture.asset(
                            'lib/assets/icons/clock.svg',
                            color: const Color.fromARGB(255, 0, 126, 167),
                          ),
                          if (_remainingTime > 0) ...[
                            const SizedBox(width: 8),
                            DidvanText(
                              _formattedTime,
                              style: Theme.of(context)
                                  .textTheme
                                  .bodyMedium
                                  ?.copyWith(
                                      color: const Color.fromARGB(
                                          255, 0, 126, 167),
                                      fontWeight: FontWeight.bold),
                            ),
                          ],
                          DidvanText(
                            _remainingTime > 0
                                ? ' تا دریافت مجدد کد'
                                : ' دریافت مجدد کد',
                            style: Theme.of(context)
                                .textTheme
                                .bodyMedium
                                ?.copyWith(
                                  fontWeight: FontWeight.bold,
                                  color: const Color.fromARGB(255, 0, 126, 167),
                                ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
