import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/service_requests_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/models/enums/user_types.dart';
import 'package:test_sa/modules/cm_module/create_cm_request.dart';
import 'package:test_sa/modules/demo_module/create_demo_request_page.dart';
import 'package:test_sa/modules/incident_module/create_incident_request_page.dart';
import 'package:test_sa/modules/internal_audit_module/pages/equipment_internal_audit/create_equipment_internal_audit_form.dart';
import 'package:test_sa/modules/internal_audit_module/pages/system_internal_audit/create_system_internal_audit_form.dart';
import 'package:test_sa/modules/loan_module/pages/create_loan_request_page.dart';
import 'package:test_sa/modules/medical_gas_inspection/create_medical_gas_request_page.dart';
import 'package:test_sa/modules/tm_module/device_transfer/create_device_transfer_request.dart';
import 'package:test_sa/modules/tm_module/tasks/create_task_view.dart';
import 'package:test_sa/modules/traf_module/create_traf_request_page.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/modules/tm_module/gas_refill/gas_refill_request_form.dart';

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

  @override
  State<CreateRequestTypeBottomSheet> createState() => _CreateRequestTypeBottomSheetState();
}

class _CreateRequestTypeBottomSheetState extends State<CreateRequestTypeBottomSheet> with SingleTickerProviderStateMixin {
  late AnimationController _animationController;

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

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

  @override
  Widget build(BuildContext context) {
    List<CreateRequestModel> requestList = CreateRequestModel.requestsList(context);

    return SafeArea(
      top: false,
      child: Container(
        padding: const EdgeInsets.all(16.0),
        width: double.infinity,
        color: AppColor.bottomSheetColor(context),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            context.translation.selectWorkOrder.heading4(context),
            GridView.builder(
              padding: const EdgeInsets.only(top: 16, bottom: 0),
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, childAspectRatio: 1, crossAxisSpacing: 16, mainAxisSpacing: 16),
              itemCount: requestList.length,
              itemBuilder: (context, 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.0, 0.3),
                  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: listCard(
                      context: context,
                      icon: requestList[index].icon,
                      label: requestList[index].title,
                      onTap: () {
                        Navigator.pushReplacementNamed(context, requestList[index].routeName);
                      },
                    ),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget listCard({required String icon, required String label, required VoidCallback onTap, required BuildContext context}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        constraints: BoxConstraints(minWidth: 111.toScreenWidth, minHeight: 111.toScreenHeight),
        padding: EdgeInsets.all(12.toScreenWidth),
        decoration: BoxDecoration(
          color: AppColor.background(context),
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: AppColor.borderColor(context), width: 2),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            icon.toSvgAsset(width: 24, height: 24, color: AppColor.icon2Color(context)),
            label.bodyText2(context).custom(color: AppColor.labelTextStyleColor(context), fontSize: context.isTablet() ? 10.toScreenWidth : null),
          ],
        ),
      ),
    );
  }
}

class CreateRequestModel {
  String title;
  String icon;
  String routeName;

  CreateRequestModel(this.title, this.icon, this.routeName);

  static List<CreateRequestModel> requestsList(BuildContext context) {
    List<CreateRequestModel> list = [];
    // switching to users permissions
    // context.userProvider.modulesPermissionsList.where((module) => module.canAdd!).toList().forEach((module) {
    //   switch (module.module!.value) {
    //     case 1:
    //       list.add(CreateRequestModel(module.module!.name!, "add_icon", CreateNewRequest.id));
    //
    //     case 2:
    //       list.add(CreateRequestModel(module.module!.name!, "add_icon", GasRefillRequestForm.routeName));
    //
    //     case 3:
    //       list.add(CreateRequestModel(module.module!.name!, "add_icon", CreateDeviceTransferRequest.id));
    //
    //     case 4:
    //       list.add(CreateRequestModel(module.module!.name!, "add_icon", CreateTaskView.id));
    //   }
    // });
    if (context.userProvider.isQualityUser && context.settingProvider.isUserFlowMedical) {
      list.add(CreateRequestModel("Equipment Internal Audit Checklist".addTranslation, "wo/equipment_audit_wo", CreateEquipmentInternalAuditForm.id));
      list.add(CreateRequestModel("System Internal Audit Checklist".addTranslation, "wo/system_audit_wo", CreateSystemInternalAuditForm.id));
    } else if (context.userProvider.isAssessor && context.settingProvider.isUserFlowMedical) { // todo: handled in permission api, so no need to check here
      // list.add(CreateRequestModel("TRAF".addTranslation, "wo/traf_wo", CreateTRAFRequestPage.id));
    } else if (context.userProvider.isEngineer) {
      if (Provider.of<SettingProvider>(context, listen: false).engineerCanCreateCM) {
        list.add(CreateRequestModel(context.translation.correctiveMaintenance, "wo/cm_wo", CreateCMRequest.id));
      }

      //TODO uncommit this to enable task.
      list.add(CreateRequestModel(context.translation.task, "wo/task_wo", CreateTaskView.id));
      //Need to add check from permission Api.
      if ((context.settingProvider.isUserFlowMedical)) {
        list.add(CreateRequestModel('Medical Gas'.addTranslation, "wo/gas_refill_wo", CreateMedicalGasRequestPage.id));
      }
    } else {
      list.add(CreateRequestModel(context.translation.correctiveMaintenance, "wo/cm_wo", CreateCMRequest.id));
      list.add(CreateRequestModel(context.translation.gasRefill, "wo/gas_refill_wo", GasRefillRequestForm.routeName));
      list.add(CreateRequestModel(context.translation.transferAsset, "wo/device_transfer_wo", CreateDeviceTransferRequest.id));
      list.add(CreateRequestModel(context.translation.task, "wo/task_wo", CreateTaskView.id));
      // context.userProvider.modulesPermissionsList.forEach((module) {
      //   if (module.module!.value! == 9) {
      //     list.add(CreateRequestModel("TRAF".addTranslation, "add_icon", CreateTRAFRequestPage.id));
      //   }
      // });

      if (context.settingProvider.isUserFlowMedical) {
        list.add(CreateRequestModel('Loan Equipment Request'.addTranslation, "wo/loan_wo", CreateLoanRequestPage.id));
        // list.add(CreateRequestModel('Demo Request'.addTranslation, "add_icon", CreateDemoRequestPage.id));
      }
    }
    // if (context.settingProvider.isUserFlowMedical && (context.userProvider.isAssessor || context.userProvider.isEngineer || context.userProvider.isNurse)) {
    //   //Traf name changed to Assessment of Need & Technology by client .
    //   list.add(CreateRequestModel("Assessment of Need & Technology".addTranslation, "add_icon", CreateTRAFRequestPage.id));
    // }

    context.userProvider.modulesPermissionsList.forEach((module) {
      ///TODO uncommit this to enable TRAF in production.
      if (module.module!.value! == 9 && (module.canAdd ?? false)) {
        list.add(CreateRequestModel(module.module?.name ?? "Assessment of Need & Technology".addTranslation, "wo/traf_wo", CreateTRAFRequestPage.id));
      }
      if (module.module!.value! == 15 && (module.canAdd ?? false)) {
        list.add(CreateRequestModel('Demo Request'.addTranslation, "wo/demo_wo", CreateDemoRequestPage.id));
      }
    });
    if (!context.userProvider.isNurse && context.settingProvider.isUserFlowMedical) {
      list.add(CreateRequestModel("Incident Management", "wo/incident_wo", CreateIncidentRequestPage.id));
    }
    return list;
  }
}
