//request main page

import 'dart:developer';

import 'package:flutter/cupertino.dart';
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/device_transfer_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_provider.dart';
import 'package:test_sa/extensions/context_extension.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/search_all_requests_model.dart';
import 'package:test_sa/modules/export_module/models/export_module_type.dart';
import 'package:test_sa/modules/export_module/pages/export_form_view.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/pages/land_page/my_request/all_requests_filter_page.dart';
import 'package:test_sa/new_views/pages/land_page/my_request/all_requests_search_page.dart';
import 'package:test_sa/new_views/pages/land_page/widgets/request_item_view_list.dart';
import 'package:test_sa/views/widgets/loaders/lazy_loading.dart';

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

  @override
  State<MyRequestsPage> createState() => _MyRequestsPageState();
}

class _MyRequestsPageState extends State<MyRequestsPage> with SingleTickerProviderStateMixin {
  AllRequestsProvider? _provider;
  SearchAllRequestsModel? _search;

  late List<Request> requestsList;
  int selectedRequest = 0;
  late AnimationController _tabAnimationController;
  late Animation<double> _tabContainerAnimation;
  late Animation<Offset> _tabContainerSlideAnimation;
  int _listAnimationKey = 0; // Key to force list re-animation

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

    // Container entrance animation (faster than individual tabs)
    _tabContainerAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _tabAnimationController,
        curve: const Interval(0.0, 0.4, curve: Curves.easeOut),
      ),
    );

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

    _tabAnimationController.forward();
  }

  @override
  void dispose() {
    _tabAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
//TODO need to refactor this and move out of build...
    if (_provider == null) {
      requestsList = [
        Request(null, context.translation.allWorkOrder),
        Request(1, context.translation.correctiveMaintenance),
        Request(2, context.translation.gasRefill),
        Request(3, context.translation.transferAsset),
        Request(4, context.translation.preventiveMaintenance),
      ];
      if (Provider.of<UserProvider>(context, listen: false).user!.type != UsersTypes.normal_user) {
        requestsList.add(Request(5, context.translation.recurrentWo));
      }
      //TODO unCommit this to enable task
      requestsList.add(Request(6, context.translation.taskRequest));
      //after confirm name add this to translation...
      if (context.settingProvider.isUserFlowMedical && Provider.of<UserProvider>(context, listen: false).user!.type != UsersTypes.normal_user) {
        requestsList.add(Request(7, 'Recall and Alert'));
      }

      // switching asset inventory to users permissions
      context.userProvider.modulesPermissionsList.forEach((module) {
        ///todo uncommit this in prod currently apis is not giving the correct name for traf
        if (module.module!.value! == 8 || module.module!.value! == 9 || module.module!.value! == 15) {
          requestsList.add(Request(module.module!.value!, module.module!.name!.addTranslation));
        }
      });
      //Hide TRAF.
      // if (context.settingProvider.isUserFlowMedical && context.userProvider.user!.type == UsersTypes.normal_user) {
      //   requestsList.add(Request(9, 'Assessment of Need & Technology'));
      // }
      if (context.userProvider.isEngineer && context.settingProvider.isUserFlowMedical) {
        requestsList.add(Request(10, 'Equipment Internal Audit'));
        requestsList.add(Request(11, 'System Internal Audit'));
        //Need to be added for new user role commissioning engineer
        // requestsList.add(Request(13, "Asset Delivery"));
        requestsList.add(Request(14, "Medical Gas Inspection"));
      }

      if (context.settingProvider.isUserFlowMedical) {
        requestsList.add(Request(12, "Loan Equipment"));
        // requestsList.add(Request(15, "Demo")); moved to permission api
      }

      if (context.userProvider.isAssessor) {
        requestsList = [
          Request(null, context.translation.allWorkOrder),
          // Request(9, 'TRAF'),
          //name changed as requested by client
          Request(9, 'Assessment of Need & Technology'),
          // Request(15, 'Demo'), moved to permission api
        ];
      }
      if (context.userProvider.isCommissioningEngineer && context.settingProvider.isUserFlowMedical) {
        ///TODO need to show only allowed ids for all workOrder
        requestsList = [
          Request(null, context.translation.allWorkOrder),
          Request(13, "Asset Delivery"),
        ];
      }
      if (context.userProvider.isQualityUser) {
        requestsList = [
          Request(null, context.translation.allWorkOrder),
          if (context.settingProvider.isUserFlowMedical) Request(7, 'Recall and Alert'),
          if (context.settingProvider.isUserFlowMedical) Request(10, 'Equipment Internal Audit'),
          if (context.settingProvider.isUserFlowMedical) Request(11, 'System Internal Audit'),
        ];
      }

      if (context.settingProvider.isUserFlowMedical && !context.userProvider.isNurse) {
        requestsList.add(Request(16, "Incidents"));
      }

      if (context.userProvider.isHouseKeeper) {
        requestsList = [
          Request(null, context.translation.allWorkOrder),
          Request(5, context.translation.recurrentWo),
          // Request(15, 'Demo'), moved to permission api
        ];
      }

      _provider = Provider.of<AllRequestsProvider>(context, listen: false);
      _provider!.reset();
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _provider!.getAllRequests(context);
      });
    }
    return Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          titleSpacing: 0,
          title: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                height: 40.toScreenHeight,
                padding: const EdgeInsets.only(left: 16, right: 8),
                alignment: Alignment.center,
                decoration: ShapeDecoration(
                  color: AppColor.dropDownBackground(context),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(6),
                    side: BorderSide(color: AppColor.borderColor(context)),
                  ),
                ),
                child: Row(
                  children: [
                    Icon(Icons.search, color: context.isDark ? AppColor.neutral10 : AppColor.neutral20, size: 19),
                    8.width,
                    Text(
                      context.translation.search,
                      style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20),
                    ).expanded,
                  ],
                ),
              ).onPress(() async {
                final result = await Navigator.push(context, CupertinoPageRoute(fullscreenDialog: true, builder: (context) => AllRequestsSearchPage(data: _search)));
                if (result != null) {
                  _search = result;
                  setState(() {});
                }
              }).expanded,
              12.width,
              IconButton(
                icon: "download".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)),
                padding: EdgeInsets.zero,
                visualDensity: VisualDensity.compact,
                tooltip: "Export",
                onPressed: () async {
                  final provider = Provider.of<AllRequestsProvider>(context, listen: false);
                  await Navigator.push(
                    context,
                    CupertinoPageRoute(
                      builder: (context) => ExportFormView(
                        searchModel: _search,
                        moduleType: ExportModuleType.callRequest,
                        pageNo: provider.pageItemNumber,
                        pageSize: (provider.allRequestsAndCount?.requestsDetails?.length ?? 0) ~/ (provider.pageItemNumber > 0 ? provider.pageItemNumber : 1) + 1,
                      ),
                    ),
                  );
                },
              ),
              IconButton(
                icon: "filter".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)),
                padding: EdgeInsets.zero,
                visualDensity: VisualDensity.compact,
                tooltip: "Filter",
                onPressed: () async {
                  final result = await Navigator.push(context, CupertinoPageRoute(fullscreenDialog: true, builder: (context) => AllRequestsFilterPage(data: _search)));
                  if (result != null) {
                    _search = result;
                    setState(() {});
                  }
                },
              ),
            ],
          ).paddingOnly(start: 16, end: 8),
        ),
        body: Consumer<AllRequestsProvider>(builder: (context, snapshot, _) {
          return Column(
            children: [
              if (!_filterIsEmpty()) _buildActiveFiltersChips(),
              if (_filterIsEmpty())
                FadeTransition(
                  opacity: _tabContainerAnimation,
                  child: SlideTransition(
                    position: _tabContainerSlideAnimation,
                    child: SizedBox(
                      height: 50.toScreenHeight,
                      child: ListView.separated(
                          scrollDirection: Axis.horizontal,
                          padding: const EdgeInsets.only(top: 16, right: 16, left: 16),
                          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: _tabAnimationController,
                                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.0, 0.3),
                              end: Offset.zero,
                            ).animate(
                              CurvedAnimation(
                                parent: _tabAnimationController,
                                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: Container(
                                  alignment: Alignment.center,
                                  padding: const EdgeInsets.symmetric(horizontal: 12),
                                  decoration: ShapeDecoration(
                                    color: AppColor.background(context),
                                    shape: RoundedRectangleBorder(
                                      side: BorderSide(width: 1, color: selectedRequest == index ? AppColor.primary10 : AppColor.borderColor(context)),
                                      borderRadius: BorderRadius.circular(6),
                                    ),
                                    shadows: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 14, offset: const Offset(0, 0), spreadRadius: 0)],
                                  ),
                                  child: Text(
                                    requestsList[index].value,
                                    style: AppTextStyles.tinyFont.copyWith(height: 1, color: selectedRequest == index ? AppColor.primary10 : AppColor.filterButtonTextColor(context)),
                                  ),
                                ).onPress(() {
                                  if (snapshot.isAllLoading) {
                                    return;
                                  }

                                  setState(() {
                                    selectedRequest = index;
                                    _listAnimationKey++; // Force list to re-animate
                                  });

                                  _provider!.reset();
                                  _provider!.getAllRequests(context, typeTransaction: requestsList[selectedRequest].id);
                                }),
                              ),
                            );
                          },
                          separatorBuilder: (cxt, index) => 8.width,
                          itemCount: requestsList.length),
                    ),
                  ),
                ),
              LazyLoading(
                nextPage: snapshot.nextPage,
                onLazyLoad: () async {
                  snapshot.getAllRequests(context, typeTransaction: requestsList[selectedRequest].id, search: _search);
                },
                child: RequestItemViewList(
                  snapshot.allRequestsAndCount?.requestsDetails ?? [],
                  snapshot.isAllLoading,
                  key: ValueKey('request_list_${selectedRequest}_$_listAnimationKey'), // Key changes on every tab click
                ),
              ).expanded,
            ],
          );
        }));
  }

  bool _filterIsEmpty() {
    if (_search == null) return true;
    if ((_search!.requestNumber?.value?.isNotEmpty ?? false) ||
        (_search!.assetNo?.value?.isNotEmpty ?? false) ||
        (_search!.assetName?.value?.isNotEmpty ?? false) ||
        (_search!.manufacture?.value?.isNotEmpty ?? false) ||
        (_search!.sn?.value?.isNotEmpty ?? false) ||
        (_search!.statuses?.isNotEmpty ?? false) ||
        (_search!.typeTransaction?.isNotEmpty ?? false) ||
        (_search!.startDate != null) ||
        (_search!.endDate != null) ||
        (_search!.selectedSortOption?.isNotEmpty ?? false)) {
      return false;
    }
    return true;
  }

  Widget _buildActiveFiltersChips() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      decoration: BoxDecoration(
        color: AppColor.background(context),
        border: Border(
          bottom: BorderSide(color: AppColor.borderColor(context), width: 1),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        spacing: 4,
        children: [
          Text(
            'Active Filters',
            style: AppTextStyles.tinyFont2.copyWith(color: AppColor.labelTextStyleColor(context), fontWeight: FontWeight.w600),
          ),
          Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            spacing: 16,
            children: [
              SizedBox(
                height: 40.toScreenHeight,
                child: ListView.separated(
                    scrollDirection: Axis.horizontal,
                    padding: EdgeInsets.zero,
                    itemBuilder: (cxt, index) => _getActiveFilterChips()[index],
                    separatorBuilder: (cxt, index) => 8.width,
                    itemCount: _getActiveFilterChips().length),
              ).expanded,
              TextButton(
                onPressed: _clearAllFilters,
                style: TextButton.styleFrom(padding: EdgeInsets.zero, tapTargetSize: MaterialTapTargetSize.shrinkWrap),
                child: Text(
                  'Clear Filters',
                  style: AppTextStyles.tinyFont.copyWith(color: AppColor.red30),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }

  List<Widget> _getActiveFilterChips() {
    List<Widget> chips = [];

    // Request Number
    if (_search?.requestNumber?.value?.isNotEmpty ?? false) {
      chips.add(_buildFilterChip(
        label: '${context.translation.woNumber}: ${_search!.requestNumber!.value}',
        onDelete: () {
          setState(() {
            _search!.requestNumber!.value = null;
            _search!.requestNumber!.controller?.clear();
            _refreshWithFilters();
          });
        },
      ));
    }

    // Asset Name
    if (_search?.assetName?.value?.isNotEmpty ?? false) {
      chips.add(_buildFilterChip(
        label: '${context.translation.assetName}: ${_search!.assetName!.value}',
        onDelete: () {
          setState(() {
            _search!.assetName!.value = null;
            _search!.assetName!.controller?.clear();
            _refreshWithFilters();
          });
        },
      ));
    }

    // Asset Number
    if (_search?.assetNo?.value?.isNotEmpty ?? false) {
      chips.add(_buildFilterChip(
        label: '${context.translation.assetNo}: ${_search!.assetNo!.value}',
        onDelete: () {
          setState(() {
            _search!.assetNo!.value = null;
            _search!.assetNo!.controller?.clear();
            _refreshWithFilters();
          });
        },
      ));
    }

    // Manufacturer
    if (_search?.manufacture?.value?.isNotEmpty ?? false) {
      chips.add(_buildFilterChip(
        label: '${context.translation.manufacture}: ${_search!.manufacture!.value}',
        onDelete: () {
          setState(() {
            _search!.manufacture!.value = null;
            _search!.manufacture!.controller?.clear();
            _refreshWithFilters();
          });
        },
      ));
    }

    // Serial Number
    if (_search?.sn?.value?.isNotEmpty ?? false) {
      chips.add(_buildFilterChip(
        label: '${context.translation.sn}: ${_search!.sn!.value}',
        onDelete: () {
          setState(() {
            _search!.sn!.value = null;
            _search!.sn!.controller?.clear();
            _refreshWithFilters();
          });
        },
      ));
    }

    // Model
    if (_search?.model?.value?.isNotEmpty ?? false) {
      chips.add(_buildFilterChip(
        label: '${context.translation.model}: ${_search!.model!.value}',
        onDelete: () {
          setState(() {
            _search!.model!.value = null;
            _search!.model!.controller?.clear();
            _refreshWithFilters();
          });
        },
      ));
    }

    // Statuses
    if (_search?.statuses?.isNotEmpty ?? false) {
      for (var statusId in _search!.statuses!) {
        String statusName = _getStatusName(statusId);
        chips.add(_buildFilterChip(
          label: 'Status: $statusName',
          onDelete: () {
            setState(() {
              _search!.statuses!.remove(statusId);
              _refreshWithFilters();
            });
          },
        ));
      }
    }

    // Type Transactions
    if (_search?.typeTransaction?.isNotEmpty ?? false) {
      for (var typeId in _search!.typeTransaction!) {
        String typeName = _getTypeName(typeId);
        chips.add(_buildFilterChip(
          label: 'Type: $typeName',
          onDelete: () {
            setState(() {
              _search!.typeTransaction!.remove(typeId);
              _refreshWithFilters();
            });
          },
        ));
      }
    }

    // Date Range
    if (_search?.startDate != null || _search?.endDate != null) {
      String dateLabel = 'Date: ';
      if (_search!.startDate != null && _search!.endDate != null) {
        dateLabel += '${_formatDate(_search!.startDate!)} - ${_formatDate(_search!.endDate!)}';
      } else if (_search!.startDate != null) {
        dateLabel += 'From ${_formatDate(_search!.startDate!)}';
      } else if (_search!.endDate != null) {
        dateLabel += 'To ${_formatDate(_search!.endDate!)}';
      }

      chips.add(_buildFilterChip(
        label: dateLabel,
        onDelete: () {
          setState(() {
            _search!.startDate = null;
            _search!.endDate = null;
            _refreshWithFilters();
          });
        },
      ));
    }

    // Sort Option
    if (_search?.selectedSortOption?.isNotEmpty ?? false) {
      String sortLabel = 'Sort: ${_getSortLabel(_search!.selectedSortOption!)}';
      chips.add(_buildFilterChip(
        label: sortLabel,
        showDelete: false,
      ));
    }
    return chips;
  }

  Widget _buildFilterChip({required String label, VoidCallback? onDelete, bool showDelete = true}) {
    return Theme(
      data: Theme.of(context).copyWith(splashColor: Colors.transparent, highlightColor: Colors.transparent),
      child: Chip(
        backgroundColor: AppColor.backgroundTabBarColor(context),
        side: BorderSide(color: AppColor.border2Color(context)),
        label: Text(label),
        visualDensity: VisualDensity.compact,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30.0)),
        labelStyle: AppTextStyles.tinyFont2.copyWith(color: AppColor.labelTextStyleColor(context)),
        deleteIconColor: showDelete ? AppColor.icon2Color(context) : null,
        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
        onDeleted: showDelete ? onDelete : null,
      ),
    );
  }

  String _getStatusName(int statusId) {
    switch (statusId) {
      case 0:
        return "All WO";
      case 1:
        return context.translation.open;
      case 2:
        return context.translation.inProgress;
      case 3:
        return context.translation.closed;
      case 4:
        return context.translation.completed;
      case 5:
        return "Canceled";
      default:
        return "Status $statusId";
    }
  }

  String _getTypeName(int typeId) {
    switch (typeId) {
      case 1:
        return context.translation.correctiveMaintenance;
      case 2:
        return context.translation.gasRefill;
      case 3:
        return context.translation.transferAsset;
      case 4:
        return context.translation.preventiveMaintenance;
      case 5:
        return context.translation.recurrentWo;
      case 6:
        return context.translation.taskRequest;
      case 7:
        return 'Recall and Alert';
      case 8:
        return 'Asset Inventory';
      case 9:
        return 'Assessment of Need & Technology';
      case 10:
        return 'Equipment Internal Audit';
      case 11:
        return 'System Internal Audit';
      case 12:
        return 'Loan Equipment';
      case 13:
        return 'Asset Delivery';
      case 14:
        return 'Medical Gas Inspection';
      case 15:
        return 'Demo';
      case 16:
        return 'Incidents';
      default:
        return "Type $typeId";
    }
  }

  String _formatDate(DateTime date) {
    return '${date.day}/${date.month}/${date.year}';
  }

  String _getSortLabel(String sortOption) {
    switch (sortOption.toLowerCase()) {
      case 'ascending':
        return 'Ascending';
      case 'descending':
        return 'Descending';
      default:
        return sortOption;
    }
  }

  void _clearAllFilters() {
    setState(() {
      _search?.requestNumber?.value = null;
      _search?.requestNumber?.controller?.clear();
      _search?.assetName?.value = null;
      _search?.assetName?.controller?.clear();
      _search?.assetNo?.value = null;
      _search?.assetNo?.controller?.clear();
      _search?.manufacture?.value = null;
      _search?.manufacture?.controller?.clear();
      _search?.sn?.value = null;
      _search?.sn?.controller?.clear();
      _search?.model?.value = null;
      _search?.model?.controller?.clear();
      _search?.statuses?.clear();
      _search?.typeTransaction?.clear();
      _search?.startDate = null;
      _search?.endDate = null;
      _search?.isArchived = false;
      _search?.selectedSortOption = null;
      _search = null; // Clear the entire search object
      _provider?.searchedModel = null;
      _refreshWithFilters();
    });
  }

  void _refreshWithFilters() {
    _provider?.reset();
    _provider?.getAllRequests(context, typeTransaction: requestsList[selectedRequest].id, search: _search);
  }
}

class Request {
  int? id;
  String value;

  Request(this.id, this.value);
}
