import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/report/service_report_repair_location_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/helper/utils.dart';
import 'package:test_sa/models/helper_data_models/maintenance_request/activity_maintenance_model.dart';
import 'package:test_sa/models/new_models/work_order_detail_model.dart';
import 'package:test_sa/modules/cm_module/service_request_detail_provider.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';

import 'components/external_request.dart';
import 'components/internal_request.dart';

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

  @override
  _MaintenanceRequestFormState createState() => _MaintenanceRequestFormState();
}

class _MaintenanceRequestFormState extends State<MaintenanceRequestForm> with SingleTickerProviderStateMixin {
  int initialIndex = 0;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInitialData();
    });
    super.initState();
  }

  Future<void> getInitialData() async {
    Provider.of<ServiceReportRepairLocationProvider>(context, listen: false).getTypes();
    ServiceRequestDetailProvider requestDetailProvider = Provider.of<ServiceRequestDetailProvider>(context, listen: false);
    // requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees =
    //     requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees ?? ActivityMaintenanceAssistantEmployees();
    requestDetailProvider.activityMaintenanceHelperModel?.assistantEmployList = requestDetailProvider.activityMaintenanceHelperModel?.assistantEmployList ?? [];
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ServiceRequestDetailProvider>(builder: (context, ServiceRequestDetailProvider requestDetailProvider, child) {
      bool isUpdate = requestDetailProvider.activityMaintenanceHelperModel?.id != 0;
      return Scaffold(
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        appBar: DefaultAppBar(
          title: "CM Activity",
          onWillPopScope: requestDetailProvider.isReadOnlyRequest
              ? null
              : () {
                  save(requestDetailProvider);
                },
        ),
        body: Stack(
          children: [
            DefaultTabController(
              length: 2,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(left: 16.toScreenWidth, right: 16.toScreenWidth, top: 12.toScreenHeight),
                    decoration: BoxDecoration(
                      color: context.isDark ? AppColor.neutral50 : AppColor.white10,
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: TabBar(
                      padding: EdgeInsets.symmetric(vertical: 4.toScreenHeight, horizontal: 4.toScreenWidth),
                      labelColor: context.isDark ? AppColor.neutral30 : AppColor.black20,
                      unselectedLabelColor: context.isDark ? AppColor.neutral30 : AppColor.black20,
                      unselectedLabelStyle: AppTextStyles.bodyText,
                      labelStyle: AppTextStyles.bodyText,
                      indicatorPadding: EdgeInsets.zero,
                      indicatorSize: TabBarIndicatorSize.tab,
                      dividerColor: Colors.transparent,
                      indicator: BoxDecoration(
                        color: context.isDark ? AppColor.neutral60 : AppColor.neutral110,
                        borderRadius: BorderRadius.circular(7),
                      ),
                      tabs: [
                        Tab(text: context.translation.internal, height: 57.toScreenHeight),
                        Tab(text: context.translation.external, height: 57.toScreenHeight),
                      ],
                    ),
                  ),
                  // 12.height,
                  const TabBarView(
                    children: [
                      InternalMaintenanceRequest(),
                      ExternalMaintenanceRequest(),
                    ],
                  ).expanded,
                ],
              ),
            ),
            if (!requestDetailProvider.isReadOnlyRequest)
              FooterActionButton.footerContainer(
                context: context,
                child: AppFilledButton(
                  label: requestDetailProvider.activityMaintenanceHelperModel?.id != 0 ? context.translation.update : context.translation.addActivity, // Use the dynamic label
                  buttonColor: AppColor.primary10,
                  onPressed: () async {
                    save(requestDetailProvider);
                  },
                ),
              ),
          ],
        ),
      ).handlePopScope(
          cxt: context,
          showPopUp: !requestDetailProvider.isReadOnlyRequest,
          onSave: () {
            save(requestDetailProvider);
          });
    });
  }

  void save(ServiceRequestDetailProvider requestDetailProvider) async {
    if (validate(model: requestDetailProvider.activityMaintenanceHelperModel!)) {
      requestDetailProvider.activityMaintenanceHelperModel?.activityMaintenanceTimers = requestDetailProvider.activityMaintenanceHelperModel?.activityMaintenanceTimers ?? [];
      if (requestDetailProvider.activityMaintenanceHelperModel?.activityTimePicker != null) {
        int durationInSecond =
            requestDetailProvider.activityMaintenanceHelperModel!.activityTimePicker!.endAt!.difference(requestDetailProvider.activityMaintenanceHelperModel!.activityTimePicker!.startAt!).inSeconds;
        requestDetailProvider.activityMaintenanceHelperModel?.activityMaintenanceTimers?.add(
          ActivityMaintenanceTimers(
            id: 0,
            startTime: requestDetailProvider.activityMaintenanceHelperModel?.activityTimePicker!.startAt!.toIso8601String(), // Handle potential null
            endTime: requestDetailProvider.activityMaintenanceHelperModel?.activityTimePicker!.endAt?.toIso8601String(), // Handle potential null
            workingHours: ((durationInSecond) / 60 / 60),
          ),
        );
      }
      requestDetailProvider.activityMaintenanceHelperModel?.timerModelList?.forEach((timer) {
        int durationInSecond = timer.endAt!.difference(timer.startAt!).inSeconds;
        requestDetailProvider.activityMaintenanceHelperModel?.activityMaintenanceTimers?.add(
          ActivityMaintenanceTimers(
            id: 0,
            startTime: timer.startAt!.toIso8601String(), // Handle potential null
            endTime: timer.endAt?.toIso8601String(), // Handle potential null
            workingHours: ((durationInSecond) / 60 / 60),
          ),
        );
      });

      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      if (requestDetailProvider.activityMaintenanceHelperModel?.id == 0) {
        await requestDetailProvider.createActivityMaintenanceRequest().then((success) {
          Navigator.pop(context);
          if (success) {
            requestDetailProvider.getWorkOrderById(id: requestDetailProvider.currentWorkOrder!.data!.requestId!);
            Navigator.pop(context);
          }
        });
      } else {
        await requestDetailProvider.updateActivityMaintenance().then((success) {
          Navigator.pop(context);
          if (success) {
            requestDetailProvider.getWorkOrderById(id: requestDetailProvider.currentWorkOrder!.data!.requestId!);
            Navigator.pop(context);
          }
        });
      }
    }
  }

  bool validate({required ActivityMaintenanceHelperModel model}) {
    if (model.activityStatus == null) {
      Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.activityStatus}");
      return false;
    }

    bool isTimerPickerEnable = ApiManager.instance.assetGroup?.enabledEngineerTimer ?? false;

    if (isTimerPickerEnable) {
      if (model.activityMaintenanceTimerModel?.startAt == null && model.activityTimePicker == null) {
        Fluttertoast.showToast(msg: "Working Hours Required");
        return false;
      }
      if (model.activityTimePicker == null) {
        if (model.activityMaintenanceTimerModel?.startAt == null) {
          Fluttertoast.showToast(msg: "Working Hours Required");
          return false;
        }
        if (model.activityMaintenanceTimerModel?.endAt == null) {
          Fluttertoast.showToast(msg: "Please Stop The Timer");
          return false;
        }
      }
    } else {
      if (model.activityMaintenanceTimerModel?.startAt == null) {
        Fluttertoast.showToast(msg: "Working Hours Required");
        return false;
      }
      if (model.activityMaintenanceTimerModel?.endAt == null) {
        Fluttertoast.showToast(msg: "Please Stop The Timer");
        return false;
      }
    }
// assistant employee validation
    if (model.assistantEmployList?.isNotEmpty ?? false) {
      for (int i = 0; i < model.assistantEmployList!.length; i++) {
        final employee = model.assistantEmployList![i];
        final position = Utils.getOrdinal(i + 1);

        if (employee.user == null) {
          Fluttertoast.showToast(
            msg: "Please select the $position assistant employee",
          );
          return false;
        }

        if (employee.user?.userId != null) {
          if (employee.startDate == null) {
            Fluttertoast.showToast(
              msg: "Please select start time for assistant employee ${employee.user?.userName}",
            );
            return false;
          }

          if (employee.endDate == null) {
            Fluttertoast.showToast(
              msg: "Please select end time for assistant employee ${employee.user?.userName}",
            );
            return false;
          }
        }
      }
    }

    //
    // if (model.activityMaintenanceTimerModel?.startAt == null) {
    //   Fluttertoast.showToast(msg: "Working Hours Required");
    //   return false;
    // }
    // if (model.activityMaintenanceTimerModel?.endAt == null) {
    //   Fluttertoast.showToast(msg: "Please Stop The Timer");
    //   return false;
    // }
    //  if (model.startTime == null) {
    //   Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.startTime}");
    //   return false;
    // }
    //  if (model.endTime == null) {
    //   Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.endTime}");
    //   return false;
    // }
    // else if (model.travelHours == null) {
    //   Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.travelingHours}");
    //   return false;
    // }
    if (model.repairLocation == null) {
      Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.repairLocation}");
      return false;
    }
    // else if (model.assignedEmployeeId == null) {
    //   Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.assignedEmployee}");
    //   return false;
    // }
    //write all other missing conditions..

    return true;
  }
}
