import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/screens/hrm/Attendancelist.dart';
import 'package:provider/provider.dart';
import '../../Utils/app_colors.dart';
import 'AdvanceListScreen.dart';
import 'CasualLeaveHistoryScreen.dart';
import 'LeaveApplicationScreen.dart';
import 'TourExpensesListScreen.dart';
import 'RewardListScreen.dart';
import '../../Notifiers/hrmProvider/hrmAccessiblePagesProvider.dart';
import 'oggchart.dart';

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

  @override
  State<HrmdashboardScreen> createState() => _HrmdashboardScreenState();
}

class _HrmdashboardScreenState extends State<HrmdashboardScreen> {
  final allowedPages = [
    "Team Leave Request Approval",
    "Team Attendance Approval",
    "Leave Request List",
    "Tour Bill List",
    "Rewards List",
    "Attendance Request List",
    "Advance List",
    "Casual Leave List"
  ];

  @override
  void initState() {
    super.initState();
    Future.microtask(
      () => Provider.of<HrmAccessiblePagesProvider>(
        context,
        listen: false,
      ).fetchAccessiblePages(context),
    );
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          backgroundColor: const Color(0xFFCEEDFF),
          title: Row(
            children: [
              InkResponse(
                onTap: () => Navigator.pop(context, true),
                child: SvgPicture.asset(
                  "assets/svg/appbar_back_button.svg",
                  height: 25,
                ),
              ),
              const SizedBox(width: 10),
              Text(
                "HRM",
                style: TextStyle(
                  fontSize: 18,
                  fontFamily: "Plus Jakarta Sans",
                  fontWeight: FontWeight.w600,
                  color: AppColors.semi_black,
                ),
              ),
            ],
          ),
        ),
        backgroundColor: AppColors.scaffold_bg_color,
        body: SingleChildScrollView(
          child: Column(
            children: [
              /// Background
              Stack(
                children: [
                  Container(
                    width: double.infinity,
                    height: 490,
                    color: const Color(0xffF6F6F8),
                  ),
                  Container(
                    width: double.infinity,
                    height: 490,
                    padding: const EdgeInsets.only(top: 1, bottom: 30),
                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          Color(0xFFCEEDFF),
                          Color(0xFFf9f9fb),
                          Color(0xffF6F6F8),
                        ],
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                      ),
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.only(top: 1, bottom: 30),
                    child: Image.asset(
                      "assets/images/vector.png",
                      height: 230,
                      width: double.infinity,
                      fit: BoxFit.fitWidth,
                    ),
                  ),

                  /// Content
                  Column(
                    children: [
                      /// Top Illustration & Button
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.only(top: 60, bottom: 30),
                        child: Column(
                          children: [
                            SvgPicture.asset(
                              "assets/images/capa.svg",
                              height: 146,
                              width: 400,
                            ),
                            const SizedBox(height: 32),
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 20,
                                vertical: 8,
                              ),
                              decoration: BoxDecoration(
                                border: Border.all(
                                  color: const Color(
                                    0xFF1487C9,
                                  ), // border color
                                  width: 1.2, // thickness of the border
                                ),
                                color: const Color(0xffEDF8FF),
                                borderRadius: BorderRadius.circular(30),
                              ),
                              child: InkWell(
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => OrgChartt(),
                                    ),
                                  );
                                },
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    SvgPicture.asset(
                                      "assets/svg/hrm/groupIc.svg",
                                      height: 29,
                                      width: 29,
                                      fit: BoxFit.contain,
                                    ),
                                    const SizedBox(width: 7),
                                    const Text(
                                      "Organization Structure",
                                      style: TextStyle(
                                        fontSize: 15,
                                        fontWeight: FontWeight.w500,
                                        fontStyle: FontStyle.normal,
                                        fontFamily: "Plus Jakarta Sans",
                                      ),
                                    ),
                                    const Icon(
                                      Icons.chevron_right,
                                      color: Colors.black54,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      /// Grid Section
                      LayoutBuilder(
                        builder: (context, constraints) {
                          return Padding(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 10,
                            ),
                            child: Consumer<HrmAccessiblePagesProvider>(
                              builder: (context, provider, child) {
                                if (provider.isLoading) {
                                  return const Center(
                                    child: CircularProgressIndicator(),
                                  );
                                }
                                if (provider.errorMessage != null) {
                                  return Center(
                                    child: Text(provider.errorMessage!),
                                  );
                                }

                                final pages =
                                    (provider.response?.pagesAccessible ?? [])
                                        .where(
                                          (page) => allowedPages.contains(
                                            page.pageName,
                                          ),
                                        )
                                        .toList();

                                return GridView.builder(
                                  itemCount: pages.length,
                                  shrinkWrap: true,
                                  physics: const NeverScrollableScrollPhysics(),
                                  gridDelegate:
                                      SliverGridDelegateWithFixedCrossAxisCount(
                                        crossAxisCount: (constraints.maxWidth /
                                                180)
                                            .floor()
                                            .clamp(2, 6),
                                        crossAxisSpacing: 1,
                                        mainAxisSpacing: 2,
                                        childAspectRatio: 1.8,
                                      ),
                                  itemBuilder: (context, index) {
                                    final page = pages[index];

                                    return _buildTile(
                                      label: page.pageName ?? "",//in page number there is 6 items comming from serever it showing only four
                                      subtitle: _getSubtitle(
                                        page.pageName ?? "",
                                      ),
                                      assetIcon: _getIcon(page.pageName ?? ""),
                                      txtColor: const Color(0xff1487C9),
                                      onTap:
                                          () => _handleNavigation(
                                            context,
                                            page.pageName ?? "",
                                            page.mode ?? "",
                                          ),
                                    );
                                  },
                                );
                              },
                            ),
                          );
                        },
                      ),

                      ////////////

                      SizedBox(height: 40,)

                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// Card builder
  Widget _buildTile({
    required String label,
    required String subtitle,
    required String assetIcon,
    required Color txtColor,
    VoidCallback? onTap,
  }) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return InkWell(
          onTap: onTap,
          borderRadius: BorderRadius.circular(14),
          child: Container(
            padding: EdgeInsets.symmetric(
              vertical: constraints.maxHeight * 0.05,
              horizontal: constraints.maxWidth * 0.05,
            ),
            margin: const EdgeInsets.symmetric(vertical: 7, horizontal: 5),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(14),
            ),
            child: Row(
              children: [
                Expanded(
                  flex: 2,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Flexible(
                        child: Text(
                          label,
                          style: TextStyle(
                            fontSize: 14,
                            color: AppColors.app_blue,
                            fontFamily: "JakartaMedium",
                          ),
                          softWrap: true,
                          overflow: TextOverflow.visible,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Flexible(
                        child: Text(
                          subtitle,
                          style: TextStyle(
                            fontSize: 12,
                            color: AppColors.grey_semi,
                            fontFamily: "JakartaMedium",
                          ),
                          softWrap: true,
                          overflow: TextOverflow.visible,
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Container(
                    height: constraints.maxHeight * 0.39,
                    width: constraints.maxHeight * 0.39,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: const Color(0xFFEDF8FF),
                    ),
                    child: Center(
                      child: SvgPicture.asset(
                        assetIcon,
                        height: constraints.maxHeight * 0.19,
                        width: constraints.maxHeight * 0.19,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// Mapping subtitles
  String _getSubtitle(String pageName) {
    switch (pageName) {
      case "Attendance Request List":
        return "Real-time request";
      case "Leave Request List":
        return "Apply & Track";
      case "Rewards List":
        return "Track earned rewards";
      case "Tour Bill List":
        return "Submit and manage claims";
      case "Team Leave Request Approval":
        return "";
      case "Team Attendance Approval":
        return "";
      case "Advance List":
        return "Advance Payment";
      case "Casual Leave List":
        return "Track Casual Leave";
      default:
        return "";
    }
  }

  /// Mapping icons
  String _getIcon(String pageName) {
    switch (pageName) {
      case "Attendance Request List":
        return "assets/svg/hrm/attendanceList.svg";
      case "Leave Request List":
        return "assets/svg/hrm/leaveApplication.svg";
      case "Rewards List":
        return "assets/svg/hrm/rewardList.svg";
      case "Tour Bill List":
        return "assets/svg/hrm/tourExp.svg";
      case "Team Leave Request Approval":
        return "assets/svg/hrm/logout_ic.svg";
      case "Team Attendance Approval":
        return "assets/svg/hrm/check_ic.svg";
      case "Advance List":
        return "assets/svg/hrm/advance_list_ic.svg";
      case "Casual Leave List":
        return "assets/svg/hrm/casual_leave_history_ic.svg";
      default:
        return "assets/svg/hrm/groupIc.svg";
    }
  }

  /// Navigation mapping
  void _handleNavigation(BuildContext context, String pageName, String mode) {
    switch (pageName) {
      case "Attendance Request List":
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => AttendanceListScreen(mode: mode),
          ),
        );
        break;

      case "Leave Request List":
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => LeaveApplicationListScreen(mode: mode),
          ),
        );
        break;

      case "Rewards List":
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => RewardListScreen()),
        );
        break;

      case "Tour Bill List":
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => TourExpensesListScreen()),
        );
        break;

      case "Team Leave Request Approval":
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => LeaveApplicationListScreen(mode: mode),
          ),
        );
        break;

      case "Team Attendance Approval":
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => AttendanceListScreen(mode: mode),
          ),
        );
        break;

      case "Advance List":
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => AdvanceListScreen(),
          ),
        );
        break;

      case "Casual Leave List":
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => CasualLeaveHistoryScreen(),
          ),
        );
        break;
    }
  }
}
