// lib/features/auth/widgets/home_feed_tab.dart
// ignore_for_file: duplicate_import, dead_null_aware_expression
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import '../../../../core/constants/app_colors.dart';
import '../../../../core/models/user.dart';
import '../admin/widgets/user_card.dart'; 

// =====================================================================
// HELPER FOR IMAGES (Handles URLs, Files, and Base64 Safely)
// =====================================================================
ImageProvider? getSmartImageProvider(String? imageString) {
  if (imageString == null || imageString.trim().isEmpty) return null;
  
  if (imageString.startsWith('http://') || imageString.startsWith('https://')) {
    return NetworkImage(imageString);
  } 
  else if (imageString.startsWith('/data') || imageString.startsWith('C:\\') || imageString.startsWith('storage')) {
    final file = File(imageString);
    if (file.existsSync()) return FileImage(file);
  } 
  else {
    try {
      String cleanBase64 = imageString;
      if (cleanBase64.contains(',')) {
        cleanBase64 = cleanBase64.split(',').last;
      }
      cleanBase64 = cleanBase64.replaceAll(RegExp(r'\s+'), '');
      return MemoryImage(base64Decode(cleanBase64));
    } catch (e) {
      debugPrint('Error decoding base64 image: $e');
    }
  }
  return null;
}

class HomeFeedTab extends StatefulWidget {
  final LocalUser? currentUser;
  final bool isLoadingUser;
  final String currentAddress; 
  final bool isLoadingLocation;
  final List<dynamic> users; 
  final bool isLoadingUsers;
  final String userError;
  
  final VoidCallback onUpdateProfile;
  final Future<void> Function() onRefresh;
  final bool isDesktop;

  const HomeFeedTab({
    super.key,
    required this.currentUser,
    required this.isLoadingUser,
    required this.currentAddress,
    required this.isLoadingLocation,
    required this.users,
    required this.isLoadingUsers,
    required this.userError,
    required this.onUpdateProfile,
    required this.onRefresh,
    required this.isDesktop,
  });

  @override
  State<HomeFeedTab> createState() => _HomeFeedTabState();
}

class _HomeFeedTabState extends State<HomeFeedTab> {
  // Controls the visibility of the local slide-in panel
  bool _showInfoPanel = false;

  void _toggleInfoPanel() {
    setState(() {
      _showInfoPanel = !_showInfoPanel;
    });
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        // Calculate dynamic width for the sliding panel
        final double panelWidth = constraints.maxWidth > 400 ? 400 : constraints.maxWidth * 0.85;
        final double padding = constraints.maxWidth > 900 ? 32.0 : 16.0;

        return Stack(
          children: [
            // =========================================================
            // MAIN FEED LAYER (Bottom Layer)
            // =========================================================
            Positioned.fill(
              child: RefreshIndicator(
                onRefresh: widget.onRefresh,
                color: AppColors.brandBlue ?? Colors.blue,
                backgroundColor: Colors.white,
                child: SingleChildScrollView(
                  physics: const AlwaysScrollableScrollPhysics(),
                  padding: EdgeInsets.all(padding),
                  child: Center(
                    child: ConstrainedBox(
                      constraints: const BoxConstraints(maxWidth: 1200),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // Injected the User Banner here
                          if (widget.currentUser != null) ...[
                            _buildCurrentUserBanner(),
                            const SizedBox(height: 32),
                          ],
                          _buildFeedHeader(context),
                          const SizedBox(height: 24),
                          _buildUsersFeed(),
                          const SizedBox(height: 100), 
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),

            // =========================================================
            // DIMMING OVERLAY LAYER (Middle Layer)
            // =========================================================
            if (_showInfoPanel)
              Positioned.fill(
                child: GestureDetector(
                  onTap: _toggleInfoPanel,
                  child: Container(
                    color: Colors.black.withOpacity(0.4),
                  ),
                ),
              ),

            // =========================================================
            // SLIDE-IN INFO PANEL LAYER (Top Layer)
            // =========================================================
            AnimatedPositioned(
              duration: const Duration(milliseconds: 350),
              curve: Curves.easeOutCubic,
              top: 0,
              bottom: 0,
              // Slides completely off-screen to the left when closed
              left: _showInfoPanel ? 0 : -panelWidth - 20, 
              width: panelWidth,
              child: Material(
                color: Colors.white,
                elevation: 16,
                borderRadius: BorderRadius.zero, // SHARP CORNERS
                child: Column(
                  children: [
                    // Panel Header
                    Padding(
                      padding: const EdgeInsets.only(top: 24, left: 24, right: 16, bottom: 8),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          const Text(
                            'Portal Information',
                            style: TextStyle(
                              fontSize: 18, 
                              fontWeight: FontWeight.w900, 
                              color: Color(0xFF1A1F36)
                            ),
                          ),
                          Container(
                            decoration: BoxDecoration(
                              color: Colors.grey.shade100,
                              shape: BoxShape.rectangle, // SHARP CORNERS
                            ),
                            child: IconButton(
                              icon: const Icon(Icons.close_rounded, size: 20),
                              color: Colors.grey.shade700,
                              onPressed: _toggleInfoPanel,
                            ),
                          ),
                        ],
                      ),
                    ),
                    
                    // Scrollable Panel Content
                    Expanded(
                      child: SingleChildScrollView(
                        padding: const EdgeInsets.fromLTRB(24, 16, 24, 40),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            _buildLocationBar(),
                            const SizedBox(height: 32),
                            _buildSystemInfoSection(),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  // =====================================================================
  // STUNNING LOGGED-IN USER BANNER (NO ROUNDED CORNERS)
  // =====================================================================
  Widget _buildCurrentUserBanner() {
    final user = widget.currentUser!;
    final imageProvider = getSmartImageProvider(user.profilePicture);

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(28),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.zero, // SHARP CORNERS
        gradient: LinearGradient(
          colors: [
            const Color.fromARGB(255, 9, 146, 71) ?? const Color(0xFF0D47A1),
            const Color.fromARGB(255, 6, 139, 62) ?? const Color(0xFF00C853),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        boxShadow: [
          BoxShadow(
            color: (AppColors.brandBlue ?? Colors.blue).withOpacity(0.3),
            blurRadius: 20,
            offset: const Offset(0, 10),
          )
        ],
      ),
      child: Row(
        children: [
          // Squared Profile Picture
          Container(
            padding: const EdgeInsets.all(4),
            decoration: const BoxDecoration(
              color: Colors.white,
              shape: BoxShape.rectangle, // SHARP CORNERS
            ),
            child: Container(
              width: 80,
              height: 80,
              decoration: BoxDecoration(
                color: Colors.grey.shade200,
                shape: BoxShape.rectangle, // SHARP CORNERS
                image: imageProvider != null 
                    ? DecorationImage(image: imageProvider, fit: BoxFit.cover) 
                    : null,
              ),
              child: imageProvider == null
                  ? Center(
                      child: Text(
                        user.fullName.isNotEmpty ? user.fullName[0].toUpperCase() : 'U',
                        style: TextStyle(
                          fontSize: 32,
                          color: AppColors.brandBlue ?? Colors.blue,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    )
                  : null,
            ),
          ),
          const SizedBox(width: 24),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "Welcome back,",
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.white.withOpacity(0.8),
                    fontWeight: FontWeight.w600,
                    letterSpacing: 1.2,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  user.fullName,
                  style: const TextStyle(
                    fontSize: 28,
                    fontWeight: FontWeight.w900,
                    color: Colors.white,
                    letterSpacing: -0.5,
                  ),
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    // Squared Role Badge
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.2),
                        borderRadius: BorderRadius.zero, // SHARP CORNERS
                      ),
                      child: Text(
                        user.role.toUpperCase(),
                        style: const TextStyle(
                          fontSize: 11,
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          letterSpacing: 1.2,
                        ),
                      ),
                    ),
                    if (user.campus != null && user.campus!.isNotEmpty) ...[
                      const SizedBox(width: 12),
                      Icon(Icons.location_on, color: Colors.white.withOpacity(0.8), size: 14),
                      const SizedBox(width: 4),
                      Text(
                        user.campus!,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.white.withOpacity(0.9),
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ]
                  ],
                ),
              ],
            ),
          ),
          // Squared Edit Button
          Container(
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              shape: BoxShape.rectangle, // SHARP CORNERS
            ),
            child: IconButton(
              icon: const Icon(Icons.edit_rounded, color: Colors.white),
              onPressed: widget.onUpdateProfile,
              tooltip: "Edit Profile",
            ),
          )
        ],
      ),
    );
  }

  // =====================================================================
  // WIDGET COMPOSERS
  // =====================================================================
  
  Widget _buildFeedHeader(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                'Suggested Connections', 
                style: TextStyle(
                  fontSize: 26, 
                  fontWeight: FontWeight.w900, 
                  color: Color(0xFF1A1F36),
                  letterSpacing: -0.5,
                ),
              ),
              const SizedBox(height: 6),
              Text(
                'Grow your network by connecting with peers, alumni, and faculty.', 
                style: TextStyle(fontSize: 15, color: Colors.grey.shade600, fontWeight: FontWeight.w500),
              ),
            ],
          ),
        ),
        const SizedBox(width: 16),
        // Beautiful Sharp Info Icon
        Material(
          color: (AppColors.brandBlue ?? Colors.blue).withOpacity(0.1),
          shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero), // SHARP CORNERS
          child: InkWell(
            customBorder: const RoundedRectangleBorder(borderRadius: BorderRadius.zero), // SHARP CORNERS
            onTap: _toggleInfoPanel,
            child: Padding(
              padding: const EdgeInsets.all(12.0),
              child: Icon(
                Icons.info_outline_rounded, 
                color: AppColors.brandBlue ?? Colors.blue, 
                size: 26
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildLocationBar() {
    final String currentCampus = widget.currentUser?.campus ?? 'Rockview University, Ndola Campus';

    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white, 
        borderRadius: BorderRadius.zero, // SHARP CORNERS
        border: Border.all(color: Colors.grey.shade200), 
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03), 
            blurRadius: 16, 
            offset: const Offset(0, 6),
          )
        ],
      ),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: (AppColors.brandBlue ?? Colors.blue).withOpacity(0.08), 
              shape: BoxShape.rectangle, // SHARP CORNERS
            ),
            child: Icon(Icons.account_balance_rounded, color: AppColors.brandBlue ?? Colors.blue, size: 24),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'CAMPUS DESIGNATION', 
                  style: TextStyle(
                    fontSize: 11, 
                    color: Colors.grey.shade500, 
                    fontWeight: FontWeight.w800,
                    letterSpacing: 0.8,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  currentCampus, 
                  style: TextStyle(
                    fontSize: 16, 
                    color: AppColors.brandGreen ?? Colors.green, 
                    fontWeight: FontWeight.w900,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSystemInfoSection() {
    final features = [
      {'icon': Icons.groups_rounded, 'title': 'Student Networking', 'desc': 'Find peers in your program and build study groups easily.', 'color': AppColors.brandBlue ?? Colors.blue},
      {'icon': Icons.storefront_rounded, 'title': 'Campus Marketplace', 'desc': 'Buy, sell, and trade books and items securely with other students.', 'color': AppColors.brandGreen ?? Colors.green},
      {'icon': Icons.apartment_rounded, 'title': 'Housing Finder', 'desc': 'Discover verified student accommodations and roommates near campus.', 'color': const Color(0xFFF57C00)},
      {'icon': Icons.forum_rounded, 'title': 'Academic Q&A', 'desc': 'Ask complex questions, share knowledge, and get help from top students.', 'color': Colors.purple.shade600},
      {'icon': Icons.event_available_rounded, 'title': 'University Events', 'desc': 'Stay updated on crucial campus gatherings, deadlines, and guest lectures.', 'color': Colors.pink.shade600},
      {'icon': Icons.work_outline_rounded, 'title': 'Alumni Mentorship', 'desc': 'Network with successful graduates and uncover potential career opportunities.', 'color': Colors.teal.shade700},
    ];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          'Discover Connect Portal', 
          style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900, color: Color(0xFF1A1F36)),
        ),
        const SizedBox(height: 6),
        Text(
          'Everything you need to succeed, all in one place.', 
          style: TextStyle(fontSize: 14, color: Colors.grey.shade600, fontWeight: FontWeight.w500),
        ),
        const SizedBox(height: 20),
        
        ...features.map((f) => Container(
          margin: const EdgeInsets.only(bottom: 14),
          padding: const EdgeInsets.all(18),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.zero, // SHARP CORNERS
            border: Border.all(color: Colors.grey.shade200),
            boxShadow: [
              BoxShadow(color: Colors.black.withOpacity(0.02), blurRadius: 12, offset: const Offset(0, 4))
            ],
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: (f['color'] as Color).withOpacity(0.1), 
                  borderRadius: BorderRadius.zero, // SHARP CORNERS
                ),
                child: Icon(f['icon'] as IconData, color: f['color'] as Color, size: 24),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      f['title'] as String, 
                      style: const TextStyle(fontWeight: FontWeight.w800, fontSize: 15, color: Color(0xFF1A1F36)),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      f['desc'] as String, 
                      style: TextStyle(color: Colors.grey.shade600, fontSize: 13, height: 1.4),
                    ),
                  ],
                ),
              ),
            ],
          ),
        )),
      ],
    );
  }

  // =====================================================================
  // USERS CONNECTIONS FEED
  // =====================================================================
  Widget _buildUsersFeed() {
    if (widget.isLoadingUsers) {
      return Padding(
        padding: const EdgeInsets.all(40.0), 
        child: Center(child: CircularProgressIndicator(color: AppColors.brandBlue ?? Colors.blue)),
      );
    }
    if (widget.userError.isNotEmpty) {
      return Center(
        child: Text(
          widget.userError, 
          style: TextStyle(color: Colors.red.shade800, fontWeight: FontWeight.bold),
        ),
      );
    }
    if (widget.users.isEmpty) {
      return Container(
        padding: const EdgeInsets.all(32),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.zero, // SHARP CORNERS
          border: Border.all(color: Colors.grey.shade200),
        ),
        child: const Center(
          child: Text(
            "No connections available yet.", 
            style: TextStyle(color: Colors.grey, fontSize: 15, fontWeight: FontWeight.w600),
          ),
        ),
      );
    }

    return LayoutBuilder(
      builder: (context, constraints) {
        double availableWidth = constraints.maxWidth;
        int crossAxisCount;
        
        if (availableWidth > 800) {
          crossAxisCount = 3;
        } else if (availableWidth > 500) {
          crossAxisCount = 2; 
        } else {
          crossAxisCount = 1; 
        }
        
        double spacing = 20.0;
        double itemWidth = (availableWidth - (spacing * (crossAxisCount - 1))) / crossAxisCount;

        return Wrap(
          spacing: spacing,
          runSpacing: spacing,
          children: widget.users.map((user) {
            return SizedBox(
              width: itemWidth, 
              child: UserCard(user: user), 
            );
          }).toList(),
        );
      },
    );
  }
}