import 'package:cheminova/notification_services.dart';
import 'package:cheminova/provider/home_provider.dart';
import 'package:cheminova/screens/Announcements_Screen.dart';
import 'package:cheminova/screens/Update_inventorytask_screen.dart';
import 'package:cheminova/screens/calendar_screen.dart';
import 'package:cheminova/screens/daily_tasks_screen.dart';
import 'package:cheminova/screens/mark_attendence_screen.dart';
import 'package:cheminova/screens/notification_screen.dart';
import 'package:cheminova/screens/product_purchase_data.dart';
import 'package:cheminova/screens/products_manual_screen.dart';
import 'package:cheminova/screens/rejected_application_screen.dart';
import 'package:cheminova/screens/sales_task_screen.dart';
import 'package:cheminova/screens/select_taskkyc_screen.dart';
import 'package:cheminova/widgets/common_app_bar.dart';
import 'package:cheminova/widgets/common_background.dart';
import 'package:cheminova/widgets/common_drawer.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

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

  @override
  State<HomePage> createState() => _HomePageState(); // Create state for HomePage
}

class _HomePageState extends State<HomePage> {
  NotificationServices notificationServices = NotificationServices(); // Initialize notification services

  @override
  void initState() {
    super.initState();
    // After the first frame is rendered, perform the following actions
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      Provider.of<HomeProvider>(context, listen: false).getProfile(); // Fetch user profile data
      notificationServices.requestNotificationPermission(); // Request notification permissions
      notificationServices.getDeviceToken().then((value) {
        if (kDebugMode) {
          print('Device Token: $value'); // Print device token in debug mode
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return CommonBackground(
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: CommonAppBar(
          title: Row(children: [
            const SizedBox(width: 10),
            Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              const Text('Welcome',
                  style: TextStyle(
                      color: Colors.black87,
                      fontSize: 14,
                      fontWeight: FontWeight.w400)),
              // Display user's name from profile data if available
              Consumer<HomeProvider>(builder: (context, value, child) =>
              (value.profileResponse == null ||
                  value.profileResponse!.myData == null ||
                  value.profileResponse!.myData!.name == null)
                  ? const SizedBox()
                  : Text(value.profileResponse!.myData!.name ?? '',
                  style: const TextStyle(
                      color: Colors.black87, fontSize: 20)))
            ])
          ]),
          backgroundColor: Colors.transparent,
          elevation: 0, // Remove elevation from the app bar
        ),
        drawer: const CommonDrawer(), // Add custom drawer
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: LayoutBuilder(
              builder: (context, constraints) {
                double screenWidth = constraints.maxWidth; // Get screen width
                double buttonWidth = screenWidth / 2 - 18; // Calculate button width

                return ListView(
                  children: [
                    // Create custom card for marking attendance
                    _buildCustomCard(
                      'Mark Attendance',
                      'Mark Attendance / On Leave',
                      screenWidth,
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const MarkAttendanceScreen(),
                          ),
                        );
                      },
                    ),
                    const SizedBox(height: 5),
                    // Create custom card for daily tasks
                    _buildCustomCard(
                      'Daily Tasks',
                      'Dashboard',
                      screenWidth,
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const DailyTasksScreen(),
                          ),
                        );
                      },
                    ),
                    const SizedBox(height: 5),
                    // Row containing cards for updating sales data and inventory
                    Row(
                      children: [
                        Expanded(
                          child: _buildCustomCard(
                            'Update\nSales data',
                            'Quickly display Sales',
                            buttonWidth,
                            onTap: () {
                              // Navigator.push(
                              //   context,
                              //   MaterialPageRoute(
                              //     builder: (context) => SalesTaskScreen(),
                              //   ),
                              // );
                            },
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: _buildCustomCard(
                            'Update Inventory Data',
                            'Quickly Inventory Data',
                            buttonWidth,
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => const UpdateInventoryTaskScreen(),
                                ),
                              );
                            },
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 5),
                    // Row containing cards for notifications and product purchase data
                    Row(
                      children: [
                        Expanded(
                          child: _buildCustomCard(
                            'Notifications',
                            'Tasks & Alerts\n\n',
                            buttonWidth,
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => const NotificationScreen(),
                                ),
                              );
                            },
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: _buildCustomCard(
                            'Product\nPurchase Data Visibility',
                            '',
                            buttonWidth,
                            onTap: () {
                              // Navigator.push(
                              //   context,
                              //   MaterialPageRoute(
                              //     builder: (context) => const ProductPurchaseData(),
                              //   ),
                              // );
                            },
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 5),
                    // Create custom card for collecting KYC data
                    _buildCustomCard(
                      'Collect \nKYC Data',
                      'Scan and upload KYC Documents',
                      screenWidth,
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const SelectTaskkycScreen(),
                          ),
                        );
                      },
                    ),
                    const SizedBox(height: 5),
                    // Create custom card for rejected applications
                    _buildCustomCard(
                      'Rejected Applications',
                      'Re-upload Rejected Documents',
                      screenWidth,
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const RejectedApplicationScreen(),
                          ),
                        );
                      },
                    ),
                    const SizedBox(height: 5),
                    _buildCustomCard(
                      'Announcements',
                      "View Announcements",
                      screenWidth,
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const AnnouncementsScreen(),
                          ),
                        );
                      },
                    ),
                    const SizedBox(height: 5),
                    // Row containing cards for calendar and products manual
                    Row(
                      children: [
                        Expanded(
                          child: _buildCustomCard(
                            'Calendar',
                            'Appointments & Deadlines',
                            buttonWidth,
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => const CalendarScreen(),
                                ),
                              );
                            },
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: _buildCustomCard(
                            'Products Manual',
                            'Details of products',
                            buttonWidth,
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => const ProductsManualScreen(),
                                ),
                              );
                            },
                          ),
                        ),
                      ],
                    ),
                  ],
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  // Helper method to build a custom card with title, subtitle, and tap action
  Widget _buildCustomCard(String title, String subtitle, double width,
      {void Function()? onTap}) {
    return Container(
      width: width,
      margin: const EdgeInsets.only(bottom: 10), // Add margin at the bottom
      decoration: BoxDecoration(
        color: Colors.indigo, // Set card background color
        border: Border.all(color: Colors.white), // Set border color
        borderRadius: BorderRadius.circular(10), // Set border radius
      ),
      child: ListTile(
        title: Text(
          title,
          style: const TextStyle(
              color: Colors.white, // Set title text color
              fontWeight: FontWeight.w800,
              fontSize: 18,
              fontFamily: 'Anek'),
        ),
        subtitle: subtitle.isNotEmpty
            ? Text(
          subtitle,
          style: const TextStyle(color: Colors.white70, fontSize: 13), // Set subtitle text color
        )
            : null,
        onTap: onTap, // Assign tap action
      ),
    );
  }
}
