import 'package:base_project/utils/toast_messages/toast_message_util.dart';
import 'package:base_project/view/auth/admin_reg_view.dart';
import 'package:base_project/view_model/auth/auth_view_model.dart';
import 'package:flutter/material.dart';
import 'package:pinput/pinput.dart';
import 'package:base_project/commans/widgets/custome_elevated_button.dart';
import 'package:provider/provider.dart';
import 'package:base_project/core/constants/ui_constants.dart';
import 'package:base_project/core/providers/dynamic_theme_provider.dart';

import 'sign_up_view.dart';

class VerifyOtpView extends StatefulWidget {
  final String? email;

  const VerifyOtpView({super.key, this.email});

  @override
  _VerifyOtpViewState createState() => _VerifyOtpViewState();
}

class _VerifyOtpViewState extends State<VerifyOtpView>
    with TickerProviderStateMixin {
  final TextEditingController _otpController = TextEditingController();
  late AnimationController _pageController;
  late AnimationController _formController;
  late Animation<double> _fade;
  late Animation<Offset> _slide;

  @override
  void initState() {
    super.initState();
    _pageController = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 800));
    _formController = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 600));
    _fade = CurvedAnimation(parent: _pageController, curve: Curves.easeInOut);
    _slide = Tween<Offset>(begin: const Offset(0, 0.2), end: Offset.zero)
        .animate(
            CurvedAnimation(parent: _pageController, curve: Curves.easeOut));
    _pageController.forward();
    Future.delayed(
        const Duration(milliseconds: 250), () => _formController.forward());
  }

  @override
  void dispose() {
    _otpController.dispose();
    _pageController.dispose();
    _formController.dispose();
    super.dispose();
  }

  void _handleVerifyButtonPress() {
    // Get the OTP value from the controller
    final otp = _otpController.text;

    // Validate OTP value
    if (otp.isEmpty || otp.length < 6) {
      // Handle invalid OTP
      print("Invalid OTP: OTP must be 6 digits.");
      ToastMessageUtil.showToast(
          message: "Invalid OTP: OTP must be 6 digits.",
          toastType: ToastType.error);
    } else {}
  }

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

        return Scaffold(
          appBar: AppBar(
            backgroundColor: colorScheme.surface,
            elevation: 0,
            leading: IconButton(
              onPressed: () => Navigator.pop(context),
              icon: const Icon(Icons.arrow_back_ios_new),
              color: colorScheme.primary,
            ),
            title: Text(
              'Verify OTP',
              style: Theme.of(context).textTheme.titleLarge?.copyWith(
                    color: colorScheme.primary,
                    fontWeight: FontWeight.w700,
                  ),
            ),
            centerTitle: true,
          ),
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  colorScheme.primary,
                  colorScheme.primary.withOpacity(0.85),
                  colorScheme.secondary.withOpacity(0.65),
                ],
                stops: const [0.0, 0.6, 1.0],
              ),
            ),
            child: Center(
              child: FadeTransition(
                opacity: _fade,
                child: SlideTransition(
                  position: _slide,
                  child: Container(
                    width: UIConstants.getResponsiveValue(
                      context,
                      mobile: double.infinity,
                      tablet: 450,
                      desktop: 500,
                    ),
                    margin: const EdgeInsets.all(UIConstants.spacing16),
                    padding: UIConstants.cardPaddingLarge,
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.95),
                      borderRadius: BorderRadius.circular(UIConstants.radius24),
                      border: Border.all(
                        color: Colors.white.withOpacity(0.3),
                        width: 1,
                      ),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.15),
                          blurRadius: 25,
                          offset: const Offset(0, 15),
                          spreadRadius: 8,
                        ),
                      ],
                    ),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.verified,
                          color: colorScheme.primary,
                          size: UIConstants.iconSizeXLarge,
                        ),
                        const SizedBox(height: UIConstants.spacing16),
                        Text(
                          'Enter the 6-digit code sent to',
                          style: Theme.of(context)
                              .textTheme
                              .bodyMedium
                              ?.copyWith(
                                color: colorScheme.onSurface.withOpacity(0.8),
                              ),
                          textAlign: TextAlign.center,
                        ),
                        Text(
                          widget.email ?? 'your email',
                          style:
                              Theme.of(context).textTheme.titleMedium?.copyWith(
                                    color: colorScheme.primary,
                                    fontWeight: FontWeight.w700,
                                  ),
                          textAlign: TextAlign.center,
                        ),
                        const SizedBox(height: UIConstants.spacing24),

                        // Pinput with theming
                        Pinput(
                          length: 6,
                          controller: _otpController,
                          pinAnimationType: PinAnimationType.fade,
                          defaultPinTheme: PinTheme(
                            width: 54,
                            height: 60,
                            textStyle: TextStyle(
                              fontSize: 20,
                              color: colorScheme.primary,
                              fontWeight: FontWeight.w700,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              border: Border.all(
                                  color: colorScheme.primary.withOpacity(0.25)),
                              borderRadius:
                                  BorderRadius.circular(UIConstants.radius12),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.05),
                                  blurRadius: 10,
                                  offset: const Offset(0, 6),
                                ),
                              ],
                            ),
                          ),
                          focusedPinTheme: PinTheme(
                            width: 56,
                            height: 62,
                            textStyle: TextStyle(
                              fontSize: 20,
                              color: colorScheme.primary,
                              fontWeight: FontWeight.w700,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              border: Border.all(
                                  color: colorScheme.primary, width: 2),
                              borderRadius:
                                  BorderRadius.circular(UIConstants.radius12),
                              boxShadow: [
                                BoxShadow(
                                  color: colorScheme.primary.withOpacity(0.15),
                                  blurRadius: 14,
                                  offset: const Offset(0, 8),
                                ),
                              ],
                            ),
                          ),
                          onCompleted: (_) => _handleVerifyButtonPress(),
                        ),

                        const SizedBox(height: UIConstants.spacing24),

                        // Verify button
                        Consumer<AuthViewModel>(
                          builder: (context, provider, child) {
                            return Column(
                              children: [
                                MyCustomElevatedButton(
                                  isLoading: provider.isLoading,
                                  onPressed: () async {
                                    if (_otpController.text.length < 6) {
                                      ToastMessageUtil.showToast(
                                        message: 'Enter 6-digit OTP',
                                        toastType: ToastType.error,
                                      );
                                      return;
                                    }
                                    final data = {
                                      'email': widget.email,
                                      'otp': _otpController.text,
                                    };
                                    final error =
                                        await provider.verifyOtp(context, data);
                                    if (error == null && mounted) {
                                      Navigator.push(
                                        context,
                                        // MaterialPageRoute(
                                        //     builder: (context) =>
                                        //         AdminRegView()),
                                        MaterialPageRoute(
                                          builder: (context) => SignUpView(
                                            email: widget.email ?? '',
                                          ),
                                        ),
                                      );
                                    } else if (error != null) {
                                      // Inline error under the input
                                      ScaffoldMessenger.of(context)
                                        ..hideCurrentSnackBar()
                                        ..showSnackBar(
                                          SnackBar(
                                            content: Text(error),
                                            backgroundColor: Colors.red,
                                          ),
                                        );
                                    }
                                  },
                                  child: const Text('Verify OTP'),
                                ),
                              ],
                            );
                          },
                        ),

                        const SizedBox(height: UIConstants.spacing16),

                        // Resend timer / action
                        Consumer<AuthViewModel>(
                          builder: (context, provider, child) {
                            return Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text(
                                  provider.isResendEnabled
                                      ? "Didn't receive code?"
                                      : 'Resend in ${provider.start}s',
                                  style: Theme.of(context)
                                      .textTheme
                                      .bodyMedium
                                      ?.copyWith(
                                        color: colorScheme.onSurface
                                            .withOpacity(0.7),
                                      ),
                                ),
                                const SizedBox(width: 8),
                                TextButton(
                                  onPressed: provider.isResendEnabled
                                      ? () {
                                          provider.resendOtp(
                                              context, {'email': widget.email});
                                        }
                                      : null,
                                  child: Text(
                                    'Resend',
                                    style: TextStyle(
                                      color: provider.isResendEnabled
                                          ? colorScheme.primary
                                          : Colors.grey,
                                      fontWeight: FontWeight.w700,
                                    ),
                                  ),
                                ),
                              ],
                            );
                          },
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
