import 'package:base_project/data/response/status.dart';
import 'package:base_project/resources/app_colors.dart';
import 'package:base_project/routes/route_names.dart';
import 'package:base_project/utils/image_constant.dart';
import 'package:base_project/utils/managers/user_manager.dart';
import 'package:base_project/view/dashboard/profile/edit_profile.dart';
import 'package:base_project/view_model/profile/profile_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_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 'account_update.dart';

class ProfileView extends StatefulWidget {
  const ProfileView({super.key});

  @override
  State<ProfileView> createState() => _ProfileViewState();
}

class _ProfileViewState extends State<ProfileView>
    with TickerProviderStateMixin {
  late final ProfileViewModel provider;
  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.3),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: UIConstants.curveNormal,
    ));

    WidgetsBinding.instance.addPostFrameCallback((_) {
      provider = Provider.of<ProfileViewModel>(context, listen: false);
      provider.getProfile();
      provider.getProfileImg();
      _animationController.forward();
    });
  }

  @override
  void 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;
        final size = MediaQuery.of(context).size;

        return Scaffold(
          appBar: ModernAppBar(
            title: '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 Header Section
                          _buildProfileHeader(
                              context, colorScheme, textTheme, size),

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

                          // Profile Actions Section
                          _buildProfileActions(context, colorScheme),
                        ],
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        );
      },
    );
  }

  Widget _buildProfileHeader(BuildContext context, ColorScheme colorScheme,
      TextTheme textTheme, Size size) {
    return Consumer<ProfileViewModel>(
      builder: (context, value, child) {
        switch (provider.userProfile.status) {
          case null:
          case Status.LOADING:
            return Container(
              height: UIConstants.getResponsiveValue(
                context,
                mobile: 200.0,
                tablet: 240.0,
                desktop: 280.0,
              ),
              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: const Center(
                child: CircularProgressIndicator(),
              ),
            );
          case Status.SUCCESS:
            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: [
                  // Profile Avatar with Enhanced Styling
                  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: 50,
                        tablet: 60,
                        desktop: 70,
                      ),
                      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: 40,
                                tablet: 50,
                                desktop: 60,
                              ),
                              color: colorScheme.primary,
                            ),
                    ),
                  ),

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

                  // User Name
                  Text(
                    provider.userProfile.data?.fullName.toString() ?? "N/A",
                    style: textTheme.headlineSmall?.copyWith(
                      fontWeight: FontWeight.w700,
                      color: colorScheme.primary,
                    ),
                    textAlign: TextAlign.center,
                  ),

                  SizedBox(height: UIConstants.spacing8),

                  // Email
                  Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: UIConstants.spacing16,
                      vertical: UIConstants.spacing8,
                    ),
                    decoration: BoxDecoration(
                      color: colorScheme.surfaceVariant.withOpacity(0.3),
                      borderRadius: BorderRadius.circular(UIConstants.radius12),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          Icons.email_outlined,
                          size: UIConstants.iconSizeSmall,
                          color: colorScheme.onSurfaceVariant,
                        ),
                        const SizedBox(width: UIConstants.spacing8),
                        Text(
                          provider.userProfile.data?.email.toString() ?? "N/A",
                          style: textTheme.bodyMedium?.copyWith(
                            color: colorScheme.onSurfaceVariant,
                          ),
                        ),
                      ],
                    ),
                  ),

                  SizedBox(height: UIConstants.spacing12),

                  // Phone Number
                  Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: UIConstants.spacing16,
                      vertical: UIConstants.spacing8,
                    ),
                    decoration: BoxDecoration(
                      color: colorScheme.surfaceVariant.withOpacity(0.3),
                      borderRadius: BorderRadius.circular(UIConstants.radius12),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          Icons.phone_outlined,
                          size: UIConstants.iconSizeSmall,
                          color: colorScheme.onSurfaceVariant,
                        ),
                        const SizedBox(width: UIConstants.spacing8),
                        Text(
                          provider.userProfile.data?.mobNo.toString() ?? "N/A",
                          style: textTheme.bodyMedium?.copyWith(
                            color: colorScheme.onSurfaceVariant,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          case Status.ERROR:
            return Container(
              height: UIConstants.getResponsiveValue(
                context,
                mobile: 200,
                tablet: 240,
                desktop: 280,
              ),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.95),
                borderRadius: BorderRadius.circular(UIConstants.radius24),
                border: Border.all(
                  color: colorScheme.error.withOpacity(0.3),
                  width: 1,
                ),
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.error_outline,
                      size: UIConstants.iconSizeXLarge,
                      color: colorScheme.error,
                    ),
                    const SizedBox(height: UIConstants.spacing16),
                    Text(
                      'Failed to load profile',
                      style: textTheme.bodyLarge?.copyWith(
                        color: colorScheme.error,
                      ),
                    ),
                  ],
                ),
              ),
            );
        }
      },
    );
  }

  Widget _buildProfileActions(BuildContext context, ColorScheme colorScheme) {
    return Container(
      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: [
          _buildModernListTile(
            context,
            colorScheme: colorScheme,
            icon: Icons.edit_outlined,
            title: 'Edit Profile',
            subtitle: 'Update your personal information',
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => EditProfile(
                    userProfile: provider.userProfile.data!,
                  ),
                ),
              );
            },
          ),
          _buildDivider(colorScheme),
          _buildModernListTile(
            context,
            colorScheme: colorScheme,
            icon: Icons.manage_accounts_outlined,
            title: 'Account Update',
            subtitle: 'Update company/workspace details',
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const AccountUpdateView(),
                ),
              );
            },
          ),
          _buildDivider(colorScheme),
          _buildModernListTile(
            context,
            colorScheme: colorScheme,
            icon: Icons.lock_outline,
            title: 'Change Password',
            subtitle: 'Update your account security',
            onTap: () {
              Navigator.pushNamed(context, RouteNames.changePasswordView);
            },
          ),
          _buildDivider(colorScheme),
          _buildModernListTile(
            context,
            colorScheme: colorScheme,
            icon: Icons.logout,
            title: 'Logout',
            subtitle: 'Sign out of your account',
            iconColor: colorScheme.error,
            onTap: () => _showLogoutDialog(context, colorScheme),
          ),
        ],
      ),
    );
  }

  Widget _buildModernListTile(
    BuildContext context, {
    required ColorScheme colorScheme,
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
    Color? iconColor,
  }) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(UIConstants.radius16),
        child: Padding(
          padding: UIConstants.getResponsivePadding(
            context,
            mobile: const EdgeInsets.all(UIConstants.spacing20),
            tablet: const EdgeInsets.all(UIConstants.spacing24),
            desktop: const EdgeInsets.all(UIConstants.spacing24),
          ),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(UIConstants.spacing12),
                decoration: BoxDecoration(
                  color: (iconColor ?? colorScheme.primary).withOpacity(0.1),
                  borderRadius: BorderRadius.circular(UIConstants.radius12),
                ),
                child: Icon(
                  icon,
                  color: iconColor ?? colorScheme.primary,
                  size: UIConstants.iconSizeMedium,
                ),
              ),
              const SizedBox(width: UIConstants.spacing16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.w600,
                            color: colorScheme.onSurface,
                          ),
                    ),
                    const SizedBox(height: UIConstants.spacing4),
                    Text(
                      subtitle,
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                            color: colorScheme.onSurfaceVariant,
                          ),
                    ),
                  ],
                ),
              ),
              Icon(
                Icons.arrow_forward_ios,
                color: colorScheme.onSurfaceVariant,
                size: UIConstants.iconSizeSmall,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDivider(ColorScheme colorScheme) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: UIConstants.spacing20),
      height: 1,
      color: colorScheme.surfaceVariant.withOpacity(0.3),
    );
  }

  void _showLogoutDialog(BuildContext context, ColorScheme colorScheme) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(UIConstants.radius20),
          ),
          title: Row(
            children: [
              Icon(
                Icons.logout,
                color: colorScheme.error,
                size: UIConstants.iconSizeMedium,
              ),
              const SizedBox(width: UIConstants.spacing12),
              const Text("Confirm Logout"),
            ],
          ),
          content: const Text("Are you sure you want to log out?"),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text(
                "Cancel",
                style: TextStyle(color: colorScheme.onSurfaceVariant),
              ),
            ),
            ElevatedButton(
              onPressed: () async {
                await UserManager().clearUser();
                Navigator.of(context).pop();
                Navigator.pushReplacementNamed(context, RouteNames.loginView);
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: colorScheme.error,
                foregroundColor: colorScheme.onError,
              ),
              child: const Text("Log Out"),
            ),
          ],
        );
      },
    );
  }
}
