import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:real_estate_mobile/core/constants/app_colors.dart';
import 'package:real_estate_mobile/features/auth/presentation/providers/auth_provider.dart';
import 'package:real_estate_mobile/features/notifications/presentation/providers/notification_provider.dart';

class HomeHeader extends ConsumerWidget {
  const HomeHeader({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final authState = ref.watch(authProvider);
    final isAuthenticated = authState.status == AuthStatus.authenticated;
    final unreadCount = isAuthenticated ? ref.watch(unreadCountProvider) : 0;

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 23, vertical: 12),
      decoration: BoxDecoration(
        color: const Color(0xFF648188),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // Logo
          Image.asset(
            'assets/icons/logo.png',
            width: 109,
            height: 29,
          ),
          // Right side: notification + hamburger menu
          Row(
            children: [
              // Notification bell with badge
              GestureDetector(
                onTap: () {
                  if (!isAuthenticated) {
                    context.push('/login');
                    return;
                  }
                  context.go('/notifications');
                },
                child: SizedBox(
                  width: 30,
                  height: 30,
                  child: Stack(
                    clipBehavior: Clip.none,
                    children: [
                      const Center(
                        child: Icon(
                          Icons.notifications_outlined,
                          color: AppColors.primaryDark,
                          size: 26,
                        ),
                      ),
                      if (unreadCount > 0)
                        Positioned(
                          top: -2,
                          right: -4,
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 4, vertical: 1),
                            constraints: const BoxConstraints(minWidth: 18),
                            decoration: BoxDecoration(
                              color: Colors.red,
                              borderRadius: BorderRadius.circular(9),
                            ),
                            child: Text(
                              unreadCount > 99 ? '99+' : '$unreadCount',
                              textAlign: TextAlign.center,
                              style: const TextStyle(
                                fontSize: 10,
                                fontWeight: FontWeight.w700,
                                color: Colors.white,
                                height: 1.4,
                              ),
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              ),
              const SizedBox(width: 16),
              // Hamburger menu
              GestureDetector(
                onTap: () => _openDrawer(context),
                child: const Icon(
                  Icons.menu,
                  color: AppColors.primaryDark,
                  size: 26,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _openDrawer(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => const _MenuDrawer(),
    );
  }
}

class _MenuDrawer extends ConsumerWidget {
  const _MenuDrawer();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final authState = ref.watch(authProvider);
    final isAuthenticated = authState.status == AuthStatus.authenticated;
    final user = authState.user;

    return DraggableScrollableSheet(
      initialChildSize: 0.85,
      minChildSize: 0.5,
      maxChildSize: 0.95,
      builder: (context, scrollController) {
        return Container(
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(15)),
          ),
          child: Column(
            children: [
              // Handle bar
              const SizedBox(height: 12),
              Container(
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  color: AppColors.divider,
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              const SizedBox(height: 12),

              // Header bar with logo and close button
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 23, vertical: 12),
                  decoration: BoxDecoration(
                    color: const Color(0xFF648188),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Image.asset(
                        'assets/icons/logo.png',
                        width: 109,
                        height: 29,
                      ),
                      GestureDetector(
                        onTap: () => Navigator.pop(context),
                        child: const Icon(
                          Icons.close,
                          color: AppColors.primaryDark,
                          size: 24,
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              const SizedBox(height: 20),

              // Profile section (when authenticated)
              if (isAuthenticated && user != null) ...[
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 24),
                  child: Row(
                    children: [
                      // Avatar
                      Container(
                        width: 70,
                        height: 70,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: AppColors.inputFill,
                          border: Border.all(
                            color: AppColors.divider,
                            width: 1,
                          ),
                        ),
                        child: ClipOval(
                          child: user.avatar != null
                              ? Image.network(
                                  user.avatar!,
                                  fit: BoxFit.cover,
                                  errorBuilder: (context, error, stackTrace) =>
                                      const Icon(
                                    Icons.person,
                                    size: 36,
                                    color: AppColors.hintText,
                                  ),
                                )
                              : const Icon(
                                  Icons.person,
                                  size: 36,
                                  color: AppColors.hintText,
                                ),
                        ),
                      ),
                      const SizedBox(width: 12),
                      // Name and welcome text
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            'Welcome Back,',
                            style: TextStyle(
                              fontFamily: 'Fractul',
                              fontSize: 14,
                              fontWeight: FontWeight.w300,
                              color: Colors.black,
                            ),
                          ),
                          const SizedBox(height: 2),
                          Text.rich(
                            TextSpan(
                              children: [
                                TextSpan(
                                  text: user.firstName ?? '',
                                  style: const TextStyle(
                                    fontFamily: 'Fractul',
                                    fontSize: 14,
                                    fontWeight: FontWeight.w700,
                                    color: AppColors.primaryDark,
                                  ),
                                ),
                                TextSpan(
                                  text:
                                      ' ${user.lastName ?? ''}',
                                  style: const TextStyle(
                                    fontFamily: 'Fractul',
                                    fontSize: 14,
                                    fontWeight: FontWeight.w400,
                                    color: AppColors.primaryDark,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 20),
              ],

              const Divider(color: AppColors.divider, height: 1),

              // Menu items
              Expanded(
                child: ListView(
                  controller: scrollController,
                  padding: EdgeInsets.zero,
                  children: [
                    _buildMenuItem(
                      context,
                      icon: Icons.school_rounded,
                      label: 'Education',
                      onTap: () => Navigator.pop(context),
                    ),
                    const Divider(color: AppColors.divider, height: 1),
                    _buildMenuItem(
                      context,
                      icon: Icons.help_rounded,
                      label: "Faq's",
                      onTap: () {
                        Navigator.pop(context);
                        context.push('/faq');
                      },
                    ),
                    const Divider(color: AppColors.divider, height: 1),
                    _buildMenuItem(
                      context,
                      icon: Icons.info_rounded,
                      label: 'About Us',
                      onTap: () {
                        Navigator.pop(context);
                        context.push('/about');
                      },
                    ),
                    const Divider(color: AppColors.divider, height: 1),
                    _buildMenuItem(
                      context,
                      icon: Icons.call_rounded,
                      label: 'Call Us',
                      showChevron: false,
                      onTap: () {
                        Navigator.pop(context);
                        context.push('/contact');
                      },
                    ),
                    const Divider(color: AppColors.divider, height: 1),
                  ],
                ),
              ),

              // Bottom section: Log Out or Login buttons
              Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                child: isAuthenticated
                    ? // Log Out button - filled orange
                    SizedBox(
                        width: double.infinity,
                        height: 54,
                        child: ElevatedButton.icon(
                          onPressed: () {
                            Navigator.pop(context);
                            ref.read(authProvider.notifier).logout();
                          },
                          icon: const Icon(
                            Icons.logout_rounded,
                            color: AppColors.primaryDark,
                            size: 24,
                          ),
                          label: const Text(
                            'Log Out',
                            style: TextStyle(
                              fontFamily: 'Fractul',
                              fontSize: 14,
                              fontWeight: FontWeight.w700,
                              color: AppColors.primaryDark,
                            ),
                          ),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: AppColors.accentOrange,
                            elevation: 0,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(15),
                            ),
                          ),
                        ),
                      )
                    : // Login / Sign Up buttons
                    Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(
                            width: double.infinity,
                            height: 54,
                            child: ElevatedButton.icon(
                              onPressed: () {
                                Navigator.pop(context);
                                context.push('/login');
                              },
                              icon: const Icon(
                                Icons.login,
                                color: Colors.white,
                                size: 20,
                              ),
                              label: const Text(
                                'Log In',
                                style: TextStyle(
                                  fontFamily: 'Fractul',
                                  fontSize: 16,
                                  fontWeight: FontWeight.w700,
                                  color: Colors.white,
                                ),
                              ),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: AppColors.accentOrange,
                                elevation: 0,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(15),
                                ),
                              ),
                            ),
                          ),
                          const SizedBox(height: 12),
                          SizedBox(
                            width: double.infinity,
                            height: 54,
                            child: OutlinedButton.icon(
                              onPressed: () {
                                Navigator.pop(context);
                                context.push('/signup');
                              },
                              icon: const Icon(
                                Icons.person_add_outlined,
                                color: AppColors.accentOrange,
                                size: 20,
                              ),
                              label: const Text(
                                'Sign Up',
                                style: TextStyle(
                                  fontFamily: 'Fractul',
                                  fontSize: 16,
                                  fontWeight: FontWeight.w700,
                                  color: AppColors.accentOrange,
                                ),
                              ),
                              style: OutlinedButton.styleFrom(
                                side: const BorderSide(
                                  color: AppColors.accentOrange,
                                  width: 1.5,
                                ),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(15),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
              ),

              // Version number
              FutureBuilder<PackageInfo>(
                future: PackageInfo.fromPlatform(),
                builder: (context, snapshot) {
                  final version = snapshot.hasData
                      ? 'v${snapshot.data!.version} (${snapshot.data!.buildNumber})'
                      : '';
                  return Padding(
                    padding: const EdgeInsets.only(bottom: 16),
                    child: Text(
                      version,
                      style: const TextStyle(
                        fontFamily: 'SourceSerif4',
                        fontSize: 12,
                        fontWeight: FontWeight.w400,
                        color: AppColors.hintText,
                      ),
                    ),
                  );
                },
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildMenuItem(
    BuildContext context, {
    required IconData icon,
    required String label,
    required VoidCallback onTap,
    bool showChevron = true,
  }) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 18),
        child: Row(
          children: [
            Icon(icon, color: AppColors.accentOrange, size: 30),
            const SizedBox(width: 20),
            Text(
              label,
              style: const TextStyle(
                fontFamily: 'Fractul',
                fontSize: 14,
                fontWeight: FontWeight.w700,
                color: AppColors.primaryDark,
              ),
            ),
            const Spacer(),
            if (showChevron)
              const Icon(
                Icons.chevron_right,
                color: AppColors.hintText,
                size: 22,
              ),
          ],
        ),
      ),
    );
  }
}
