import 'package:flutter/material.dart';
import 'package:inventory_system/screens/bottom_nav_bar.dart';
import 'package:inventory_system/screens/nav_bar.dart';
import 'package:inventory_system/screens/title_bar.dart';
import 'package:inventory_system/utils/exit_dialog.dart';
import 'package:inventory_system/services/user_service.dart';
import 'package:inventory_system/services/report_service.dart';

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

  @override
  State<UserHomeScreen> createState() => _UserHomeScreenState();
}

class _UserHomeScreenState extends State<UserHomeScreen> {
  int _selectedIndex = 0;
  Map<String, dynamic>? _reportData;
  bool _isLoadingReport = true;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _loadReportData();
  }

  Future<void> _loadReportData() async {
    setState(() {
      _isLoadingReport = true;
      _errorMessage = null;
    });

    try {
      final userService = UserService();
      final userInfoData = await userService.getUserInfo();
      
      if (userInfoData.isEmpty || !userInfoData.containsKey('userInfo')) {
        throw Exception("Failed to retrieve user information");
      }

      final userInfo = userInfoData['userInfo'];
      final department = userInfo['department'];
      
      int deptId = 0;
      if (department != null && department['departmentId'] != null) {
        deptId = department['departmentId'];
      }

      final reportService = ReportService();
      final data = await reportService.fetchInventoryReport(deptId);
      
      if (mounted) {
        setState(() {
          _reportData = data;
          _isLoadingReport = false;
        });
      }
    } catch (e) {
      debugPrint("Error loading report data: $e");
      if (mounted) {
        setState(() {
          _isLoadingReport = false;
          _errorMessage = "Failed to load report";
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        final shouldExit = await showExitConfirmationDialog(context);
        return shouldExit;
      },
      child: Scaffold(
        backgroundColor: const Color(0xFFF5F5F7),
        appBar: const TitleBar(title: 'User Dashboard'),
        drawer: const NavBar(isAdmin: false, selectedScreen: AppScreen.dashboard),
        body: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Information Section
              Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Text(
                      'INFORMATION',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w700,
                        color: Colors.black87,
                        letterSpacing: 1,
                      ),
                    ),
                    if (_isLoadingReport) ...[
                      const SizedBox(width: 10),
                      const SizedBox(
                        width: 16, 
                        height: 16, 
                        child: CircularProgressIndicator(strokeWidth: 2)
                      ),
                    ]
                  ],
                ),
              ),
              const SizedBox(height: 16),
              // Information Card
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [Colors.orange.shade300, Colors.orange.shade200],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(color: Colors.orange.shade400, width: 2),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.orange.withOpacity(0.2),
                      blurRadius: 8,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: Column(
                  children: [
                    if (_errorMessage != null)
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          _errorMessage!,
                          style: const TextStyle(color: Colors.red, fontSize: 14, fontWeight: FontWeight.bold),
                        ),
                      )
                    else ...[
                      Row(
                        children: [
                          Expanded(
                            child: _buildInfoItem('Total Items', _isLoadingReport ? '...' : '${_reportData?['itemCountRegistered'] ?? 0}'),
                          ),
                          Container(
                            width: 1,
                            height: 40,
                            color: Colors.orange.shade400,
                          ),
                          Expanded(
                            child: _buildInfoItem('Current Stock', _isLoadingReport ? '...' : '${_reportData?['itemCountStillInStock'] ?? 0}'),
                          ),
                        ],
                      ),
                      const SizedBox(height: 16),
                      Container(
                        height: 1,
                        color: Colors.orange.shade400,
                      ),
                      const SizedBox(height: 16),
                      Row(
                        children: [
                          Expanded(
                            child: _buildInfoItem('New (Month)', _isLoadingReport ? '...' : '${_reportData?['itemCountRegisteredThisMonth'] ?? 0}'),
                          ),
                          Container(
                            width: 1,
                            height: 40,
                            color: Colors.orange.shade400,
                          ),
                          Expanded(
                            child: _buildInfoItem('Stock Out (Month)', _isLoadingReport ? '...' : '${_reportData?['itemCountStockOutThisMonth'] ?? 0}'),
                          ),
                        ],
                      ),
                    ],
                  ],
                ),
              ),
              const SizedBox(height: 24),
              // Action Cards
              Row(
                children: [
                  Expanded(
                    child: Material(
                      color: Colors.transparent,
                      child: InkWell(
                        onTap: () {
                          Navigator.pushNamed(context, '/product_request_user');
                        },
                        borderRadius: BorderRadius.circular(16),
                        splashColor: Colors.white.withOpacity(0.2),
                        highlightColor: Colors.white.withOpacity(0.1),
                        child: Ink(
                          padding: const EdgeInsets.symmetric(vertical: 28, horizontal: 16),
                          decoration: BoxDecoration(
                            color: Colors.blue.shade700,
                            borderRadius: BorderRadius.circular(16),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.purple.withOpacity(0.3),
                                blurRadius: 8,
                                offset: const Offset(0, 4),
                              ),
                            ],
                          ),
                          child: const Column(
                            children: [
                              Icon(Icons.assignment_rounded, color: Colors.white, size: 48),
                              SizedBox(height: 12),
                              Text(
                                'Product Request',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                  fontWeight: FontWeight.w600,
                                ),
                                textAlign: TextAlign.center,
                              ),
                              SizedBox(height: 4),
                              Text(
                                'Manage requests',
                                style: TextStyle(
                                  color: Colors.white70,
                                  fontSize: 12,
                                ),
                                textAlign: TextAlign.center,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Material(
                      color: Colors.transparent,
                      child: InkWell(
                        onTap: () {
                          Navigator.pushNamed(context, '/item_movement_all_user');
                        },
                        borderRadius: BorderRadius.circular(16),
                        splashColor: Colors.white.withOpacity(0.2),
                        highlightColor: Colors.white.withOpacity(0.1),
                        child: Ink(
                          padding: const EdgeInsets.symmetric(vertical: 28, horizontal: 16),
                          decoration: BoxDecoration(
                            color: Colors.blue.shade700,
                            borderRadius: BorderRadius.circular(16),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.cyan.withOpacity(0.3),
                                blurRadius: 8,
                                offset: const Offset(0, 4),
                              ),
                            ],
                          ),
                          child: const Column(
                            children: [
                              Icon(Icons.swap_horiz_rounded, color: Colors.white, size: 48),
                              SizedBox(height: 12),
                              Text(
                                'Item Movement',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                  fontWeight: FontWeight.w600,
                                ),
                                textAlign: TextAlign.center,
                              ),
                              SizedBox(height: 4),
                              Text(
                                'Track transfers',
                                style: TextStyle(
                                  color: Colors.white70,
                                  fontSize: 12,
                                ),
                                textAlign: TextAlign.center,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16),
            ],
          ),
        ),
        bottomNavigationBar: BottomNavBar(
          selectedIndex: _selectedIndex,
          // isAdmin: false,
          onItemTapped: (index) {
            setState(() {
              _selectedIndex = index;
            });
          },
        ),
      ),
    );
  }

  Widget _buildTableHeader(String text) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Text(
        text,
        style: const TextStyle(
          fontSize: 11,
          fontWeight: FontWeight.w600,
          color: Colors.black87,
        ),
        textAlign: TextAlign.center,
      ),
    );
  }

  Widget _buildTableCell(String text, {bool isLeft = false}) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 10,
          color: Colors.grey.shade700,
        ),
        textAlign: isLeft ? TextAlign.left : TextAlign.center,
      ),
    );
  }

  Widget _buildInfoItem(String label, String value) {
    return Column(
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 13,
            fontWeight: FontWeight.w600,
            color: Colors.black87,
          ),
          textAlign: TextAlign.center,
        ),
        const SizedBox(height: 8),
        Text(
          value,
          style: const TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.w700,
            color: Colors.black87,
          ),
        ),
      ],
    );
  }
}
