import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:inventory_system/screens/nav_bar.dart';
import 'package:inventory_system/screens/title_bar.dart';
import 'package:inventory_system/screens/bottom_nav_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 HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int _selectedIndex = 0;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  
  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 userRole = userInfo['role'];
      final department = userInfo['department'];
      
      int deptId = 0; // Default to 0 (All)
      
      if (userRole == "SuperAdmin" || userRole == "SystemAdmin") {
        deptId = 0;
      } else 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 PopScope(
      canPop: false,
      onPopInvoked: (didPop) async {
        if (didPop) return;
        if (_scaffoldKey.currentState?.isDrawerOpen ?? false) {
          Navigator.of(context).pop();
          return;
        }
        final shouldExit = await showExitConfirmationDialog(context);
        if (shouldExit) {
          SystemNavigator.pop();
        }
      },
      child: Scaffold(
        key: _scaffoldKey,
        backgroundColor: const Color(0xFFF5F5F7),
        appBar: const TitleBar(title: 'Admin Dashboard'),
        drawer: const NavBar(isAdmin: true, selectedScreen: AppScreen.dashboard),
        body: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Dashboard Cards - 2 columns grid
                    GridView.count(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      crossAxisCount: 2,
                      crossAxisSpacing: 12,
                      mainAxisSpacing: 12,
                      childAspectRatio: 1.5,
                      children: [
                        _buildDashboardCard(
                          title: 'Supplier',
                          subtitle: 'Manage suppliers',
                          icon: Icons.local_shipping_rounded,
                          color: Colors.blue.shade700,
                          onTap: () {
                            Navigator.pushNamed(context, '/supplier');
                          },
                        ),
                        _buildDashboardCard(
                          title: 'Manufacturer',
                          subtitle: 'View manufacturers',
                          icon: Icons.factory_rounded,
                          color: Colors.blue.shade700,
                          onTap: () {
                             Navigator.pushNamed(context, '/manufacturer');
                          },
                        ),
                        _buildDashboardCard(
                          title: 'Station',
                          subtitle: 'Location management',
                          icon: Icons.location_on_rounded,
                          color: Colors.blue.shade700,
                          onTap: () {
                            Navigator.pushNamed(context, '/station');
                          },
                        ),
                        _buildDashboardCard(
                          title: 'Product',
                          subtitle: 'Product catalog',
                          icon: Icons.inventory_2_rounded,
                          color: Colors.blue.shade700,
                          onTap: () {
                            Navigator.pushNamed(context, '/product');
                          },
                        ),
                        _buildDashboardCard(
                          title: 'Item',
                          subtitle: 'All inventory items',
                          icon: Icons.category_rounded,
                          color: Colors.blue.shade700,
                          onTap: () {
                            Navigator.pushNamed(context, '/item');
                          },
                        ),
                        _buildDashboardCard(
                          title: 'Item Movement',
                          subtitle: 'Track transfers',
                          icon: Icons.swap_horiz_rounded,
                          color: Colors.blue.shade700,
                          onTap: () {
                            Navigator.pushNamed(context, '/item_movement_all');
                          },
                        ),
                      ],
                    ),
                    const SizedBox(height: 12),
                    // Product Request Card - Centered
                    Center(
                      child: _buildDashboardCard(
                        title: 'Product Request',
                        subtitle: 'Manage requests',
                        icon: Icons.assignment_rounded,
                        color: Colors.blue.shade700,
                        onTap: () {
                          Navigator.pushNamed(context, '/product_request_t_to_im');
                        },
                        width: MediaQuery.of(context).size.width * 0.47,
                      ),
                    ),
                    const SizedBox(height: 12),
                    // Inventory Report
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16),
                        border: Border.all(color: Colors.grey.shade300, width: 1.5),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              const Text(
                                'Inventory Report',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w700,
                                  color: Colors.black87,
                                ),
                              ),
                              if (_isLoadingReport) ...[
                                const SizedBox(width: 10),
                                const SizedBox(
                                  width: 16, 
                                  height: 16, 
                                  child: CircularProgressIndicator(strokeWidth: 2)
                                ),
                              ]
                            ],
                          ),
                          const SizedBox(height: 12),
                          if (_errorMessage != null)
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Text(
                                _errorMessage!,
                                style: const TextStyle(color: Colors.red, fontSize: 12),
                              ),
                            )
                          else
                            Table(
                            border: TableBorder.all(color: Colors.grey.shade300, width: 1),
                            columnWidths: const {
                              0: FlexColumnWidth(1.5),
                              1: FlexColumnWidth(1.5),
                              2: FlexColumnWidth(1.5),
                            },
                            children: [
                              TableRow(
                                decoration: BoxDecoration(color: Colors.grey.shade50),
                                children: [
                                  _buildTableHeader('Statistic'),
                                  _buildTableHeader('Item Registered'),
                                  _buildTableHeader('Item Stock Out'),
                                ],
                              ),
                              TableRow(
                                children: [
                                  _buildTableCell('Item Registered: ${_reportData?['itemCountRegistered'] ?? 0}', isLeft: true),
                                  _buildTableCell('This Month: ${_reportData?['itemCountRegisteredThisMonth'] ?? 0}'),
                                  _buildTableCell('This Month: ${_reportData?['itemCountStockOutThisMonth'] ?? 0}'),
                                ],
                              ),
                              TableRow(
                                children: [
                                  _buildTableCell('Item In Stock: ${_reportData?['itemCountStillInStock'] ?? 0}', isLeft: true),
                                  _buildTableCell('Last Month: ${_reportData?['itemCountRegisteredLastMonth'] ?? 0}'),
                                  _buildTableCell('Last Month: ${_reportData?['itemCountStockOutLastMonth'] ?? 0}'),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        bottomNavigationBar: BottomNavBar(
          selectedIndex: _selectedIndex,
          onItemTapped: (index) {
            setState(() {
              _selectedIndex = index;
            });
          },
        ),
      ),
    );
  }

  Widget _buildDashboardCard({
    required String title,
    required String subtitle,
    required IconData icon,
    required Color color,
    required VoidCallback onTap,
    double? width,
  }) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(16),
        splashColor: Colors.white.withOpacity(0.2),
        highlightColor: Colors.white.withOpacity(0.1),
        child: Ink(
          width: width,
          padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
          decoration: BoxDecoration(
            color: color,
            borderRadius: BorderRadius.circular(16),
            boxShadow: [
              BoxShadow(
                color: color.withOpacity(0.3),
                blurRadius: 8,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(icon, color: Colors.white, size: 36),
              const SizedBox(height: 6),
              Text(
                title,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 2),
              Text(
                subtitle,
                style: const TextStyle(
                  color: Colors.white70,
                  fontSize: 11,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),
      ),
    );
  }

  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,
      ),
    );
  }
}
