import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/all_requests_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/dashboard_latest/dashboard_provider.dart';
import 'package:test_sa/dashboard_latest/widgets/request_category_list.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/enum_extensions.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/enums/user_types.dart';
import 'package:test_sa/models/new_models/dashboard_detail.dart';
import 'package:test_sa/modules/cm_module/views/components/weekly_calendar_fragment.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/tab_button.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import 'package:test_sa/controllers/providers/settings/setting_provider.dart';

import '../../new_views/pages/land_page/widgets/request_item_view_list.dart';

class RequestCategoryFragment extends StatefulWidget {
  const RequestCategoryFragment({Key? key}) : super(key: key);

  @override
  State<RequestCategoryFragment> createState() => _RequestCategoryFragmentState();
}

class _RequestCategoryFragmentState extends State<RequestCategoryFragment> with SingleTickerProviderStateMixin {
  bool isAscending = false;
  late AnimationController _animationController;
  late Animation<double> _headerFadeAnimation;
  late Animation<Offset> _headerSlideAnimation;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 1200),
      vsync: this,
    );

    // Header animation (appears first, faster)
    _headerFadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: const Interval(0.0, 0.4, curve: Curves.easeOut),
      ),
    );

    _headerSlideAnimation = Tween<Offset>(
      begin: const Offset(0.0, -0.3),
      end: Offset.zero,
    ).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: const Interval(0.0, 0.5, curve: Curves.easeOutCubic),
      ),
    );

    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  void _toggleSort(DashBoardProvider dashboardProvider, UsersTypes? userType) {
    setState(() {
      isAscending = !isAscending;
    });

    // Get current tab info
    List<CategoryTabs> tabs = CategoryTabs.getTabs(userType: userType ?? UsersTypes.normal_user, context: context);

    // Reload data with new sort order
    dashboardProvider.resetRequestDataList();
    Provider.of<AllRequestsProvider>(context, listen: false).reset();

    if (dashboardProvider.listIndex.isEmpty) {
      // No category selected - reload default data with sorting
      Provider.of<AllRequestsProvider>(context, listen: false).getAllRequests(context, isAscending: isAscending);
    } else if (dashboardProvider.listIndex.length == 1 && dashboardProvider.isUnassignedTab(dashboardProvider.listIndex[0])) {
      // UnAssigned only - check by requestType, not by index
      int index = dashboardProvider.listIndex[0];
      dashboardProvider.getRequestDetail(
        usersType: userType ?? UsersTypes.normal_user,
        showLoader: true,
        status: tabs[index].tag,
        tabId: tabs[index].id,
        isAscending: isAscending,
      );
    } else {
      // Multiple categories - call multi-filter API
      dashboardProvider.getMultiSelectCategoryRequests(
        usersType: userType ?? UsersTypes.normal_user,
        showLoader: true,
        context: context,
        isAscending: isAscending,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<DashBoardProvider>(builder: (context, dashboardProvider, child) {
      bool isNurse = (Provider.of<UserProvider>(context, listen: false).user?.type) == UsersTypes.normal_user;
      final user = Provider.of<UserProvider>(context, listen: false).user;
      final settingProvider = Provider.of<SettingProvider>(context, listen: false);

      // Check if user is houseKeeper
      final bool isHouseKeeper = user?.type == UsersTypes.houseKeeper;

      return Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
        // !isNurse && dashboardProvider.tabs.isNotEmpty && dashboardProvider.tabs[dashboardProvider.currentListIndex].tag == 0
        //     ? Column(
        //   crossAxisAlignment: CrossAxisAlignment.start,
        //   children: [
        //     context.translation.allWorkOrder.heading4(context),
        //     // Row(
        //     //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
        //     //   children: [
        //     //     context.translation.allWorkOrder.heading4(context),
        //     //     GestureDetector(
        //     //         onTap: () {
        //     //           dashboardProvider.isShowDashBoardCalendar = !dashboardProvider.isShowDashBoardCalendar;
        //     //         },
        //     //         child: dashboardProvider.isShowDashBoardCalendar ? AppAsset.listIcon.toSvgAsset() : AppAsset.calendarIcon.toSvgAsset())
        //     //   ],
        //     // ),
        //     dashboardProvider.isShowDashBoardCalendar
        //         ? Padding(
        //       padding: EdgeInsets.only(top: 12.toScreenHeight),
        //       child: const WeeklyCalendarFragment(),
        //     )
        //         : const SizedBox(),
        //   ],
        // ).paddingOnly(start: 14, end: 12)
        //     : isHouseKeeper
        //     ? Row(
        //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
        //   children: [
        //     'All Tasks'.addTranslation.heading4(context),
        //     'add_icon'.toSvgAsset(width: 20, height: 20).onPress(() {
        //       Navigator.of(context).pushNamed('/cleaner_search');
        //     }),
        //   ],
        // ).paddingOnly(start: 16, end: 16)
        //     : context.translation.allWorkOrder.heading4(context).paddingOnly(start: 16, end: 16),
        //

        getTabs(
          requestsProvider: dashboardProvider,
          context: context,
          userType: Provider.of<UserProvider>(context, listen: false).user?.type,
        ),
        FadeTransition(
          opacity: _headerFadeAnimation,
          child: SlideTransition(
            position: _headerSlideAnimation,
            child:
                // !isNurse && dashboardProvider.tabs.isNotEmpty
                //     //&& dashboardProvider.tabs[dashboardProvider.currentListIndex].tag == 0
                //     ? Column(
                //         crossAxisAlignment: CrossAxisAlignment.start,
                //         children: [
                //           Text(context.translation.allWorkOrder, style: AppTextStyles.heading4.copyWith(color: AppColor.headingTextColor(context))),
                //           // Row(
                //           //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                //           //   children: [
                //           //     context.translation.allWorkOrder.heading4(context),
                //           //     GestureDetector(
                //           //         onTap: () {
                //           //           dashboardProvider.isShowDashBoardCalendar = !dashboardProvider.isShowDashBoardCalendar;
                //           //         },
                //           //         child: dashboardProvider.isShowDashBoardCalendar ? AppAsset.listIcon.toSvgAsset() : AppAsset.calendarIcon.toSvgAsset())
                //           //   ],
                //           // ),
                //           dashboardProvider.isShowDashBoardCalendar
                //               ? Padding(
                //                   padding: EdgeInsets.only(top: 12.toScreenHeight),
                //                   child: const WeeklyCalendarFragment(),
                //                 )
                //               : const SizedBox(),
                //         ],
                //       ).paddingOnly(start: 14, end: 12)
                //     :

                isHouseKeeper
                    ? Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          'All Tasks'.addTranslation.heading4(context),
                          'add_icon'
                              .toSvgAsset(
                            width: 24,
                            height: 24,
                          )
                              .onPress(() {
                            Navigator.of(context).pushNamed('/cleaner_search');
                          }),
                        ],
                      ).paddingOnly(start: 16, end: 16)
                    : Row(
                        spacing: 16,
                        children: [
                          Text(context.translation.allWorkOrder, style: AppTextStyles.heading4.copyWith(color: AppColor.headingTextColor(context))).expanded,
                          // todo commenting this code, for FM
                          // if (!isFMSEngineer)
                          //   'search'.toSvgAsset(width: 24, height: 24, color: AppColor.headingTextColor(context)).onPress(() {
                          //     Navigator.of(context).pushNamed('/cleaner_search');
                          //   }),

                          if (dashboardProvider.listIndex.isNotEmpty)
                            Text(
                              'Clear Filters',
                              style: AppTextStyles.bodyText2.copyWith(color: AppColor.red30),
                            ).onPress(() {
                              dashboardProvider.resetRequestDataList();
                              dashboardProvider.currentListIndex = null;
                              Provider.of<AllRequestsProvider>(context, listen: false)
                                ..reset()
                                ..getAllRequests(context);
                            }),
                          Transform.flip(
                            flipY: isAscending,
                            child: 'dashboard/sort_descending'.toSvgAsset(width: 24, height: 24, color: AppColor.headingTextColor(context)).onPress(() {
                              _toggleSort(dashboardProvider, user?.type);
                            }),
                          )
                        ],
                      ).paddingOnly(start: 16, end: 16),
          ),
        ),

        // isFMSEngineer
        //         ? Row(
        //             mainAxisAlignment: MainAxisAlignment.spaceBetween,
        //             children: [
        //               context.translation.allWorkOrder.heading4(context),
        //               'search'.toSvgAsset(width: 24, height: 24, color: AppColor.headingTextColor(context)).onPress(() {
        //                 Navigator.of(context).pushNamed('/cleaner_search');
        //               }),
        //             ],
        //           ).paddingOnly(start: 16, end: 16)
        //         : context.translation.allWorkOrder.heading4(context).paddingOnly(start: 16, end: 16),
        (dashboardProvider.listIndex.isEmpty)
            ? Consumer<AllRequestsProvider>(builder: (context, snapshot, _) {
                return RequestItemViewList(
                  snapshot.allRequestsAndCount?.requestsDetails ?? [],
                  snapshot.isAllLoading,
                  disableScroll: true,
                  key: const ValueKey('request_list_'), // Key changes on every tab click
                );
              })
            : dashboardProvider.listIndex.length == 1 && dashboardProvider.isUnassignedTab(dashboardProvider.listIndex[0])
                // UnAssigned selected (check by requestType, not by index) - show requestDetailList
                ? dashboardProvider.isDetailLoading
                    ? Column(
                        mainAxisSize: MainAxisSize.max,
                        children: List.generate(3, (index) {
                          return Padding(
                            padding: EdgeInsets.symmetric(vertical: 10.toScreenHeight, horizontal: 0),
                            child: const SizedBox().toRequestShimmer(context, dashboardProvider.isDetailLoading),
                          );
                        })).paddingOnly(start: 16, end: 16, top: 16)
                    : (dashboardProvider.requestDetailList == null || dashboardProvider.requestDetailList?.data?.isEmpty == true)
                        ? const NoDataFound().paddingOnly(top: 80).center
                        : RequestCategoryList(dashboardProvider.requestDetailList?.data ?? <Data>[], dashboardProvider.isDetailLoading, dashboardProvider.requestDetailList?.totalRows ?? 0)
                // Multi-select categories - show allRequestsAndCount
                : Consumer<AllRequestsProvider>(builder: (context, snapshot, _) {
                    if (snapshot.isMultiFilterLoading) {
                      return Column(
                          mainAxisSize: MainAxisSize.max,
                          children: List.generate(3, (index) {
                            return Padding(
                              padding: EdgeInsets.symmetric(vertical: 10.toScreenHeight, horizontal: 0),
                              child: const SizedBox().toRequestShimmer(context, snapshot.isMultiFilterLoading),
                            );
                          })).paddingOnly(start: 16, end: 16, top: 16);
                    }
                    if (snapshot.allRequestsAndCount == null || snapshot.allRequestsAndCount?.requestsDetails?.isEmpty == true) {
                      return const NoDataFound().paddingOnly(top: 80).center;
                    }
                    return RequestItemViewList(
                      snapshot.allRequestsAndCount?.requestsDetails ?? [],
                      snapshot.isMultiFilterLoading,
                      disableScroll: true,
                      key: ValueKey('multi_filter_list_${dashboardProvider.listIndex.join("_")}'),
                    );
                  }),
      ]);
    });
  }

  Widget getTabs({required BuildContext context, required DashBoardProvider requestsProvider, required UsersTypes? userType}) {
    List<CategoryTabs> tabs = CategoryTabs.getTabs(userType: userType ?? UsersTypes.normal_user, context: context);

    // Calculate item width to show X.5 items (last visible item is exactly 50% visible)
    final screenWidth = MediaQuery.of(context).size.width;
    final isTablet = context.isTablet();

    // Show 3.5 items on phone, 4.5 on tablet (perfect 50% peek)
    final visibleItemsWithPeek = isTablet ? 4.5 : 3.5;
    const spacing = 4.0;
    const horizontalPadding = 16.0;

    // Calculate item width: divide available space by visible items including the half item
    final availableWidth = screenWidth - (horizontalPadding * 2);
    final fullItems = visibleItemsWithPeek.floor(); // 3 or 4
    final totalSpacing = (fullItems - 1) * spacing + (spacing * 0.5); // Full gaps + half gap for peek
    final itemWidth = (availableWidth - totalSpacing) / visibleItemsWithPeek;

    // Check if scrolling is needed
    final needsScrolling = tabs.length > fullItems;

    return SizedBox(
      height: itemWidth + 16, // Height matches item width + bottom padding
      child: _buildHorizontalScrollableList(tabs, requestsProvider, userType, itemWidth, needsScrolling),
    );
  }

  // Horizontal scrollable list
  Widget _buildHorizontalScrollableList(List<CategoryTabs> tabs, DashBoardProvider requestsProvider, UsersTypes? userType, double itemWidth, bool needsScrolling) {
    const leftPadding = 16.0;
    const rightPadding = 16.0; // Equal padding - peek is created by item sizing

    return ListView.separated(
      controller: _scrollController,
      scrollDirection: Axis.horizontal,
      separatorBuilder: (cxt, index) => const SizedBox(width: 4),
      padding: const EdgeInsets.only(bottom: 16, left: leftPadding, right: rightPadding),
      itemBuilder: (cxt, index) {
        // Calculate staggered animation delay
        final delay = index * 0.08;
        final animation = Tween<double>(begin: 0.0, end: 1.0).animate(
          CurvedAnimation(
            parent: _animationController,
            curve: Interval(
              delay.clamp(0.0, 0.8),
              (delay + 0.3).clamp(0.0, 1.0),
              curve: Curves.easeOut,
            ),
          ),
        );

        final slideAnimation = Tween<Offset>(
          begin: const Offset(-0.3, 0.0),
          end: Offset.zero,
        ).animate(
          CurvedAnimation(
            parent: _animationController,
            curve: Interval(
              delay.clamp(0.0, 0.8),
              (delay + 0.3).clamp(0.0, 1.0),
              curve: Curves.easeOutCubic,
            ),
          ),
        );

        return FadeTransition(
          opacity: animation,
          child: SlideTransition(
            position: slideAnimation,
            child: SizedBox(
              width: itemWidth, // Use responsive width
              child: RequestTypeButton(
                label: tabs[index].label,
                loading: requestsProvider.isDetailLoading && requestsProvider.listIndex.contains(index),
                isSelected: requestsProvider.listIndex.contains(index),
                count: requestsProvider.getStatusCount(tabs[index].requestType),
                onPressed: () async {
                  setState(() {
                    isAscending = false;
                  });

                  // Check if this is UnAssigned tab (index 0 for engineer)
                  bool isUnassignedTab = tabs[index].requestType == RequestTypeEnum.unassigned;

                  // Update selection state
                  requestsProvider.currentListIndex = index;

                  // Reset data
                  requestsProvider.resetRequestDataList();
                  Provider.of<AllRequestsProvider>(context, listen: false).reset();

                  // If deselected (listIndex is now empty), show default data
                  if (requestsProvider.listIndex.isEmpty) {
                    Provider.of<AllRequestsProvider>(context, listen: false).getAllRequests(context);
                    return;
                  }

                  // If UnAssigned is selected, call its separate API
                  if (isUnassignedTab) {
                    requestsProvider.getRequestDetail(
                      usersType: userType ?? UsersTypes.normal_user,
                      showLoader: true,
                      status: tabs[index].tag,
                      tabId: tabs[index].id,
                    );
                  } else {
                    // Multiple categories selected - call multi-filter API
                    requestsProvider.getMultiSelectCategoryRequests(
                      usersType: userType ?? UsersTypes.normal_user,
                      showLoader: true,
                      context: context,
                      isAscending: isAscending,
                    );
                  }
                },
                icon: tabs[index].icon,
                iconColor: tabs[index].iconColor,
              ),
            ),
          ),
        );
      },
      itemCount: tabs.length,
    );
  }
}
