import 'package:base_project/core/constants/ui_constants.dart';
import 'package:base_project/core/providers/dynamic_theme_provider.dart';
import 'package:base_project/routes/route_names.dart';
import 'package:base_project/shared/widgets/app_bar/modern_app_bar.dart';
import 'package:base_project/shared/widgets/buttons/modern_button.dart';
import 'package:base_project/shared/widgets/inputs/modern_text_field.dart';
import 'package:base_project/utils/validator/text_feild_validator.dart';
import 'package:base_project/view_model/auth/auth_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:iconsax/iconsax.dart';
import 'package:provider/provider.dart';

class SignUpView extends StatefulWidget {
  final String email;
  SignUpView({super.key, required this.email});

  @override
  State<SignUpView> createState() => _SignUpViewState();
}

class _SignUpViewState extends State<SignUpView> with TickerProviderStateMixin {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _firstNameController = TextEditingController();
  final TextEditingController _lastNameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _dobController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();
  final ValueNotifier<bool> _obscurePassword = ValueNotifier<bool>(true);
  final ValueNotifier<bool> _obscureConfirm = ValueNotifier<bool>(true);

  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.2), end: Offset.zero).animate(
            CurvedAnimation(
                parent: _animationController, curve: UIConstants.curveNormal));
    WidgetsBinding.instance
        .addPostFrameCallback((_) => _animationController.forward());
  }

  @override
  void dispose() {
    _firstNameController.dispose();
    _lastNameController.dispose();
    _phoneController.dispose();
    _dobController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    _obscurePassword.dispose();
    _obscureConfirm.dispose();
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final isIOS = Theme.of(context).platform == TargetPlatform.iOS;
    final textTheme = Theme.of(context).textTheme;
    final size = MediaQuery.sizeOf(context);

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

        return Scaffold(
          appBar: ModernAppBar(
            title: 'Sign Up',
            automaticallyImplyLeading: true,
            leading: IconButton(
              icon: Icon(
                  isIOS ? Icons.arrow_back_ios_new_rounded : Icons.arrow_back),
              onPressed: () {
                Navigator.pushNamedAndRemoveUntil(
                  context,
                  RouteNames.loginView,
                  (Route<dynamic> route) => false,
                );
              },
            ),
            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: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          _buildHeaderCard(context, textTheme, colorScheme),
                          SizedBox(
                              height: UIConstants.getResponsiveSpacing(
                            context,
                            mobile: UIConstants.spacing32,
                            tablet: UIConstants.spacing40,
                            desktop: UIConstants.spacing48,
                          )),
                          _buildFormCard(context, textTheme, colorScheme, size),
                        ],
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        );
      },
    );
  }

  Widget _buildHeaderCard(
      BuildContext context, TextTheme textTheme, ColorScheme colorScheme) {
    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: [
          Text(
            "Create an Account!",
            textAlign: TextAlign.center,
            style: textTheme.headlineSmall?.copyWith(
              fontWeight: FontWeight.w700,
              color: colorScheme.primary,
            ),
          ),
          const SizedBox(height: UIConstants.spacing8),
          Text(
            "Join us today, it's quick and easy.",
            style: textTheme.bodyMedium
                ?.copyWith(color: colorScheme.onSurfaceVariant),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildFormCard(BuildContext context, TextTheme textTheme,
      ColorScheme colorScheme, Size size) {
    return Form(
      key: _formKey,
      child: 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.stretch,
          children: [
            ModernTextField(
              label: 'First Name',
              hint: 'Enter your first name',
              controller: _firstNameController,
              prefixIcon: const Icon(Icons.person),
              validator: TextFieldValidator.validateField,
            ),
            SizedBox(height: UIConstants.spacing20),
            ModernTextField(
              label: 'Last Name',
              hint: 'Enter your last name',
              controller: _lastNameController,
              prefixIcon: const Icon(Iconsax.profile_circle),
              validator: TextFieldValidator.validateField,
            ),
            SizedBox(height: UIConstants.spacing20),
            ModernTextField(
              label: 'Phone Number',
              hint: 'Enter your phone number',
              controller: _phoneController,
              prefixIcon: const Icon(Icons.phone_outlined),
              validator: TextFieldValidator.validateField,
              keyboardType: const TextInputType.numberWithOptions(),
              inputFormatters: [FilteringTextInputFormatter.digitsOnly],
            ),
            SizedBox(height: UIConstants.spacing20),
            GestureDetector(
              onTap: () async {
                DateTime? pickedDate = await showDatePicker(
                  context: context,
                  initialDate: DateTime.now(),
                  firstDate: DateTime(1900),
                  lastDate: DateTime.now(),
                );
                pickedDate ??= DateTime.now();
                _dobController.text =
                    "${pickedDate.day}/${pickedDate.month}/${pickedDate.year}";
              },
              child: AbsorbPointer(
                child: ModernTextField(
                  label: 'Date of Birth',
                  hint: 'DD/MM/YYYY',
                  controller: _dobController,
                  prefixIcon: const Icon(Icons.cake_outlined),
                  validator: TextFieldValidator.validateField,
                ),
              ),
            ),
            SizedBox(height: UIConstants.spacing20),
            ValueListenableBuilder<bool>(
              valueListenable: _obscurePassword,
              builder: (context, value, _) {
                return ModernTextField(
                  label: 'Password',
                  hint: 'Enter a strong password',
                  controller: _passwordController,
                  prefixIcon: const Icon(Icons.lock_outline),
                  obscureText: value,
                  validator: TextFieldValidator.validatePassword,
                  suffixIcon: IconButton(
                    icon: Icon(value ? Icons.visibility_off : Icons.visibility),
                    onPressed: () => _obscurePassword.value = !value,
                  ),
                );
              },
            ),
            SizedBox(height: UIConstants.spacing20),
            ValueListenableBuilder<bool>(
              valueListenable: _obscureConfirm,
              builder: (context, value, _) {
                return ModernTextField(
                  label: 'Confirm Password',
                  hint: 'Re-enter your password',
                  controller: _confirmPasswordController,
                  prefixIcon: const Icon(Icons.lock_outline),
                  obscureText: value,
                  validator: (val) {
                    if (val != _passwordController.text) {
                      return 'Passwords do not match';
                    }
                    return null;
                  },
                  suffixIcon: IconButton(
                    icon: Icon(value ? Icons.visibility_off : Icons.visibility),
                    onPressed: () => _obscureConfirm.value = !value,
                  ),
                );
              },
            ),
            SizedBox(
                height: UIConstants.getResponsiveSpacing(
              context,
              mobile: UIConstants.spacing32,
              tablet: UIConstants.spacing40,
              desktop: UIConstants.spacing48,
            )),
            Consumer<AuthViewModel>(
              builder: (context, provider, child) {
                return ModernButton(
                  text: 'Sign Up',
                  type: ModernButtonType.primary,
                  size: ModernButtonSize.large,
                  isLoading: provider.isLoading,
                  icon: const Icon(Icons.person_add_alt_1),
                  onPressed: () {
                    if (_formKey.currentState!.validate()) {
                      final Map<String, dynamic> signUpData = {
                        "first_name": _firstNameController.text,
                        "last_name": _lastNameController.text,
                        "email": widget.email,
                        "mob_no": _phoneController.text,
                        "date_of_birth": _dobController.text,
                        "new_password": _passwordController.text,
                        "confirm_password": _confirmPasswordController.text,
                        "usrGrpId": 1,
                      };
                      // provider.signUp(context, signUpData);
                      // Use the new combined registration method
                      provider.signUpWithAccountCreation(context, signUpData);
                    }
                  },
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}
