import 'package:base_project/commans/widgets/custom_textform_field.dart';
import 'package:base_project/commans/widgets/custome_elevated_button.dart';
import 'package:base_project/model/user/user_profile.dart';
import 'package:base_project/resources/app_colors.dart';
import 'package:base_project/view_model/profile/profile_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.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';

import '../../../utils/image_constant.dart';

class EditProfile extends StatefulWidget {
  final UserProfile userProfile;
  const EditProfile({super.key, required this.userProfile});

  @override
  State<EditProfile> createState() => _EditProfileState();
}

class _EditProfileState extends State<EditProfile>
    with TickerProviderStateMixin {
  late TextEditingController _emailController;
  late TextEditingController _userNameController;
  late TextEditingController _mobNoController;
  late TextEditingController _fullNameController;
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    _emailController = TextEditingController(text: widget.userProfile.email);
    _userNameController =
        TextEditingController(text: widget.userProfile.username);
    _mobNoController =
        TextEditingController(text: widget.userProfile.mobNo.toString());
    _fullNameController =
        TextEditingController(text: widget.userProfile.fullName.toString());

    _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() {
    _emailController.dispose();
    _userNameController.dispose();
    _mobNoController.dispose();
    _fullNameController.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: 'Edit Profile',
            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: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          // Profile Photo Section
                          _buildProfilePhotoSection(context, colorScheme),

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

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

  Widget _buildProfilePhotoSection(
      BuildContext context, 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(
            'Profile Picture',
            style: Theme.of(context).textTheme.titleLarge?.copyWith(
                  fontWeight: FontWeight.w600,
                  color: colorScheme.primary,
                ),
          ),
          SizedBox(height: UIConstants.spacing24),
          Consumer<ProfileViewModel>(
            builder: (context, provider, _) {
              return Center(
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Container(
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(
                          color: colorScheme.primary.withOpacity(0.3),
                          width: 3,
                        ),
                        boxShadow: [
                          BoxShadow(
                            color: colorScheme.primary.withOpacity(0.2),
                            blurRadius: 20,
                            offset: const Offset(0, 10),
                            spreadRadius: 5,
                          ),
                        ],
                      ),
                      child: CircleAvatar(
                        radius: UIConstants.getResponsiveValue(
                          context,
                          mobile: 60,
                          tablet: 70,
                          desktop: 80,
                        ),
                        backgroundColor: colorScheme.primary.withOpacity(0.1),
                        backgroundImage: provider.profileImageBytes != null
                            ? MemoryImage(provider.profileImageBytes!)
                            : null,
                        child: provider.profileImageBytes != null
                            ? null
                            : Icon(
                                Icons.person,
                                size: UIConstants.getResponsiveValue(
                                  context,
                                  mobile: 50,
                                  tablet: 60,
                                  desktop: 70,
                                ),
                                color: colorScheme.primary,
                              ),
                      ),
                    ),
                    Positioned(
                      bottom: 0,
                      right: 0,
                      child: Container(
                        decoration: BoxDecoration(
                          color: colorScheme.primary,
                          shape: BoxShape.circle,
                          border: Border.all(
                            color: Colors.white,
                            width: 3,
                          ),
                          boxShadow: [
                            BoxShadow(
                              color: colorScheme.primary.withOpacity(0.3),
                              blurRadius: 10,
                              offset: const Offset(0, 5),
                              spreadRadius: 2,
                            ),
                          ],
                        ),
                        child: IconButton(
                          icon: const Icon(Icons.camera_alt),
                          color: Colors.white,
                          onPressed: () {
                            provider.pickImg(context);
                          },
                        ),
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildFormSection(
      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(
            'Personal Information',
            style: textTheme.titleLarge?.copyWith(
              fontWeight: FontWeight.w600,
              color: colorScheme.primary,
            ),
          ),
          SizedBox(height: UIConstants.spacing24),

          // Full Name Field
          ModernTextField(
            label: 'Full Name',
            hint: 'Enter your full name',
            controller: _fullNameController,
            prefixIcon: Icon(Icons.person_outline),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Full name is required';
              }
              return null;
            },
          ),

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

          // Email Field
          ModernTextField(
            label: 'Email Address',
            hint: 'Enter your email',
            controller: _emailController,
            prefixIcon: Icon(Icons.email_outlined),
            keyboardType: TextInputType.emailAddress,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Email is required';
              }
              if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$')
                  .hasMatch(value)) {
                return 'Please enter a valid email';
              }
              return null;
            },
          ),

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

          // Phone Field
          ModernTextField(
            label: 'Phone Number',
            hint: 'Enter your phone number',
            controller: _mobNoController,
            prefixIcon: Icon(Icons.phone_outlined),
            keyboardType: TextInputType.phone,
            inputFormatters: [
              FilteringTextInputFormatter.digitsOnly,
              LengthLimitingTextInputFormatter(10),
            ],
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Phone number is required';
              }
              if (value.length != 10) {
                return 'Phone number must be 10 digits';
              }
              return null;
            },
          ),

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

          // Save Button
          Consumer<ProfileViewModel>(
            builder: (context, provider, _) {
              return ModernButton(
                text: 'Save Changes',
                type: ModernButtonType.primary,
                size: ModernButtonSize.large,
                isLoading: provider.isUpdating,
                icon: Icon(Icons.save_outlined),
                onPressed: () {
                  final data = {
                    'email': _emailController.text,
                    'fullName': _fullNameController.text,
                    'mob_no': _mobNoController.text,
                  };
                  provider.updateProfile(context, data);
                },
              );
            },
          ),
        ],
      ),
    );
  }
}
