import 'package:base_project/view_model/system_params/system_params_view_model.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../../core/constants/ui_constants.dart';
import '../../../core/providers/theme_provider.dart';
import '../theme_toggle.dart';

class ModernAppBar extends StatelessWidget implements PreferredSizeWidget {
  final String title;
  final List<Widget>? actions;
  final Widget? leading;
  final bool automaticallyImplyLeading;
  final Color? backgroundColor;
  final Color? foregroundColor;
  final double? elevation;
  final bool centerTitle;
  final Widget? titleWidget;
  final VoidCallback? onMenuPressed;
  final VoidCallback? onProfilePressed;
  final String? userAvatar;
  final ImageProvider<Object>? userAvatarImage;
  final String? userName;
  final bool showThemeToggle;
  final bool showUserProfile;
  final bool showLogoInTitle;
  final bool showBackButton;
  final ImageProvider<Object>? logoImage;

  const ModernAppBar({
    super.key,
    required this.title,
    this.actions,
    this.leading,
    this.automaticallyImplyLeading = true,
    this.backgroundColor,
    this.foregroundColor,
    this.elevation,
    this.centerTitle = true,
    this.titleWidget,
    this.onMenuPressed,
    this.onProfilePressed,
    this.userAvatar,
    this.userAvatarImage,
    this.userName,
    this.showThemeToggle = true,
    this.showUserProfile = true,
    this.showLogoInTitle = true,
    this.showBackButton = false,
    this.logoImage,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isDarkMode = theme.brightness == Brightness.dark;

    final Widget computedTitle = _buildTitle(context, theme, colorScheme);

    return AppBar(
      title: computedTitle,
      centerTitle: titleWidget != null
          ? centerTitle
          : (showLogoInTitle ? false : centerTitle),
      backgroundColor: backgroundColor ?? colorScheme.surface,
      foregroundColor: foregroundColor ?? colorScheme.onSurface,
      elevation: elevation ?? 0,
      automaticallyImplyLeading: automaticallyImplyLeading,
      leading: leading ??
          (automaticallyImplyLeading
              ? (showBackButton
                  ? IconButton(
                      icon: Icon(
                        Icons.arrow_back,
                        color: foregroundColor ?? colorScheme.onSurface,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    )
                  : IconButton(
                      icon: Icon(
                        Icons.menu,
                        color: foregroundColor ?? colorScheme.onSurface,
                      ),
                      onPressed: onMenuPressed ??
                          () {
                            Scaffold.of(context).openDrawer();
                          },
                    ))
              : null),
      actions: [
        // Theme Toggle
        if (showThemeToggle) ...[
          Consumer<ThemeProvider>(
            builder: (context, themeProvider, child) {
              return ThemeToggle(
                isDarkMode: themeProvider.isDarkMode,
                onThemeChanged: (isDark) {
                  themeProvider.setTheme(isDark);
                },
                size: UIConstants.iconSizeMedium,
              );
            },
          ),
          const SizedBox(width: UIConstants.spacing8),
        ],

        // User Profile
        if (showUserProfile) ...[
          GestureDetector(
            onTap: onProfilePressed,
            child: Container(
              margin: const EdgeInsets.only(right: UIConstants.spacing16),
              padding: const EdgeInsets.all(UIConstants.spacing4),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                  color: colorScheme.outline.withOpacity(0.3),
                  width: 2,
                ),
              ),
              child: CircleAvatar(
                radius: UIConstants.iconSizeMedium / 2,
                backgroundColor: colorScheme.primaryContainer,
                backgroundImage: userAvatarImage ??
                    (userAvatar != null ? NetworkImage(userAvatar!) : null),
                child: userAvatarImage == null && userAvatar == null
                    ? Icon(
                        Icons.person,
                        color: colorScheme.onPrimaryContainer,
                        size: UIConstants.iconSizeMedium * 0.6,
                      )
                    : null,
              ),
            ),
          ),
        ],

        // Custom Actions
        if (actions != null) ...actions!,
      ],
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          bottom: Radius.circular(UIConstants.radius16),
        ),
      ),
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  Widget _buildTitle(
      BuildContext context, ThemeData theme, ColorScheme colorScheme) {
    if (titleWidget != null) return titleWidget!;

    final effectiveLogo = logoImage ?? _resolveLogoImage(context);

    if (showLogoInTitle) {
      return Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 64,
            height: 64,
            decoration: BoxDecoration(
              color: (backgroundColor ?? colorScheme.surface),
              borderRadius: BorderRadius.circular(UIConstants.radius12),
              border: Border.all(
                  color: colorScheme.outline.withOpacity(0.15), width: 1),
            ),
            clipBehavior: Clip.antiAlias,
            child: FittedBox(
              fit: BoxFit.contain,
              alignment: Alignment.center,
              child: effectiveLogo != null
                  ? Image(
                      image: effectiveLogo,
                      filterQuality: FilterQuality.high,
                    )
                  : Icon(
                      Icons.image_not_supported_outlined,
                      color: colorScheme.onSurface.withOpacity(0.5),
                    ),
            ),
          ),
          const SizedBox(width: UIConstants.spacing12),
          Text(
            title,
            style: theme.textTheme.headlineSmall?.copyWith(
              color: foregroundColor ?? colorScheme.onSurface,
              fontWeight: FontWeight.w600,
            ),
            overflow: TextOverflow.ellipsis,
          ),
        ],
      );
    }

    return Text(
      title,
      style: theme.textTheme.headlineSmall?.copyWith(
        color: foregroundColor ?? colorScheme.onSurface,
        fontWeight: FontWeight.w600,
      ),
    );
  }

  ImageProvider<Object>? _resolveLogoImage(BuildContext context) {
    try {
      final sysVm = Provider.of<SystemParamsViewModel>(context, listen: true);
      if (sysVm.profileImageBytes != null &&
          sysVm.profileImageBytes!.isNotEmpty) {
        return MemoryImage(sysVm.profileImageBytes!);
      }
    } catch (_) {}
    return const AssetImage('assets/images/image_not_found.png');
  }
}
