import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/ppm/recurrent_wo.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 'package:test_sa/new_views/pages/land_page/land_page.dart';
import 'package:test_sa/views/widgets/loaders/app_loading.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import 'package:test_sa/views/widgets/dialogs/confirm_dialog.dart';

import '../../../../../../controllers/providers/api/all_requests_provider.dart';
import 'components/room_tabs_widget.dart';
import 'components/task_info_widget.dart';

class RecurrentWorkOrderView extends StatefulWidget {
  static const String routeName = "/recurrent_wo";
  final int? taskId;

  RecurrentWorkOrderView({Key? key, required this.taskId}) : super(key: key);

  @override
  _RecurrentWorkOrderViewState createState() {
    return _RecurrentWorkOrderViewState();
  }
}

class _RecurrentWorkOrderViewState extends State<RecurrentWorkOrderView> {
  AllRequestsProvider? allRequestsProvider;

  @override
  void initState() {
    allRequestsProvider = Provider.of<AllRequestsProvider>(context, listen: false);
    Provider.of<AllRequestsProvider>(context, listen: false).getRecurrentWoById(id: widget.taskId!);
    super.initState();
  }

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

  bool isClosed = false;

  @override
  Widget build(BuildContext context) {
    return Consumer<AllRequestsProvider>(builder: (context, requestProvider, child) {
      isClosed = requestProvider.recurrentWoData?.status?.value == 1;
      return Scaffold(
        appBar: DefaultAppBar(
          title: context.translation.recurrentWo,
          onWillPopScope: isClosed
              ? null
              : () {
                  _updateTask(context: context, status: 0);
                },
        ),
        body: allRequestsProvider!.isLoading
            ? const ALoading()
            : requestProvider.recurrentWoData != null
                ? SafeArea(
                    child: Column(
                      children: [
                        SingleChildScrollView(
                          padding: const EdgeInsets.all(16),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              RecurrentTaskInfoWidget(
                                isClosed: isClosed,
                                model: requestProvider.recurrentWoData,
                                isHouseKeeper: false,
                                timerStartTime: null,
                              ),
                              IgnorePointer(
                                ignoring: isClosed,
                                child: requestProvider.recurrentWoData!.planRecurrentMedicalTaskRooms != null && requestProvider.recurrentWoData!.planRecurrentMedicalTaskRooms!.isNotEmpty
                                    ? Column(
                                        children: [
                                          8.height,
                                          RoomTabsWidget(model: requestProvider.recurrentWoData),
                                        ],
                                      )
                                    : const SizedBox(),
                              ),
                            ],
                          ),
                        ).expanded,
                        if (requestProvider.recurrentWoData?.status?.value != 1) ...[
                          FooterActionButton.footerContainer(
                            context: context,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: [
                                AppFilledButton(
                                  label: context.translation.save,
                                  buttonColor: AppColor.background(context),
                                  textColor: AppColor.labelTextStyleColor(context),
                                  showBorder: true,
                                  onPressed: () => _updateTask(context: context, status: 0),
                                ).expanded,
                                12.width,
                                AppFilledButton(
                                  label: context.translation.complete,
                                  buttonColor: AppColor.primary10,
                                  onPressed: () => _updateTask(context: context, status: 1),
                                ).expanded,
                              ],
                            ),
                          ),
                        ]
                      ],
                    ),
                  )
                : NoDataFound(message: context.translation.noDataFound).center,
      ).handlePopScope(
          cxt: context,
          showPopUp: !isClosed,
          onSave: () {
            _updateTask(context: context, status: 0);
          });
    });
  }

  void _updateTask({required BuildContext context, required int status}) async {
    // Proceed with update
    _performUpdate(context: context, status: status);
  }

  void _performUpdate({required BuildContext context, required int status}) async {
    AllRequestsProvider allRequestsProvider = Provider.of<AllRequestsProvider>(context, listen: false);

    if (validate(context: context, model: allRequestsProvider.recurrentWoData!, status: status)) {
      // Use existing timer logic
      allRequestsProvider.recurrentWoData?.planRecurrentTaskTimers = allRequestsProvider.recurrentWoData?.planRecurrentTaskTimers ?? [];

      if (allRequestsProvider.recurrentWoData?.recurrentWoTimePicker != null) {
        int durationInSecond = allRequestsProvider.recurrentWoData!.recurrentWoTimePicker!.endAt!.difference(allRequestsProvider.recurrentWoData!.recurrentWoTimePicker!.startAt!).inSeconds;
        allRequestsProvider.recurrentWoData?.planRecurrentTaskTimers?.add(
          PlanRecurrentTaskTimers(
            id: 0,
            startTime: allRequestsProvider.recurrentWoData!.recurrentWoTimePicker!.startAt!.toIso8601String(),
            endTime: allRequestsProvider.recurrentWoData!.recurrentWoTimePicker!.endAt?.toIso8601String(),
            workingHours: ((durationInSecond) / 60 / 60),
          ),
        );
      }
      allRequestsProvider.recurrentWoData?.timerModelList?.forEach((timer) {
        int durationInSecond = timer.endAt!.difference(timer.startAt!).inSeconds;
        allRequestsProvider.recurrentWoData?.planRecurrentTaskTimers?.add(
          PlanRecurrentTaskTimers(
            id: 0,
            startTime: timer.startAt!.toIso8601String(),
            endTime: timer.endAt?.toIso8601String(),
            workingHours: ((durationInSecond) / 60 / 60),
          ),
        );
      });

      final uniqueTimersMap = <String, PlanRecurrentTaskTimers>{};
      allRequestsProvider.recurrentWoData?.planRecurrentTaskTimers?.forEach((timer) {
        if (timer.startTime != null && timer.endTime != null) {
          final key = '${timer.id}_${timer.startTime}_${timer.endTime}';
          uniqueTimersMap[key] = timer;
        }
      });

      allRequestsProvider.recurrentWoData?.planRecurrentTaskTimers = uniqueTimersMap.values.toList();
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());

      await allRequestsProvider.updateRecurrentWo(status: status, showToast: false).then((result) {
        Navigator.pop(context); // Close loading dialog

        bool success = result['success'] ?? false;
        String message = result['message'] ?? '';

        if (success) {
          if (status == 1) {
            // When complete is clicked, navigate to LandPage (Dashboard)
            allRequestsProvider.reset();
            allRequestsProvider.getAllRequests(context, typeTransaction: 5);
            allRequestsProvider.recurrentWoData?.recurrentWoTimerModel = null;

            // Navigate to LandPage and clear all previous routes
            Navigator.of(context).pushNamedAndRemoveUntil(LandPage.routeName, (routes) => false);
          } else {
            // For save (status 0), just pop the current screen
            allRequestsProvider.recurrentWoData?.recurrentWoTimerModel = null;
            Navigator.pop(context);
          }
        } else {
          // Show error dialog with the exact message from API
          _showErrorDialog(context, message.isNotEmpty ? message : "Failed to update the task. Please try again.");
        }
      }).catchError((error) {
        Navigator.pop(context); // Close loading dialog
        _showErrorDialog(context, error.toString());
      });
    }
  }

  void _showErrorDialog(BuildContext context, String message) {
    showDialog(
      context: context,
      builder: (context) => ConfirmDialog(
        message: message,
        title: 'Error',
        onTap: () => Navigator.pop(context),
      ),
    );
  }
}

bool validate({required BuildContext context, required RecurrentWoData model, required int status}) {
  // Timer validation logic
  bool isTimerPickerEnable = ApiManager.instance.assetGroup?.enabledEngineerTimer ?? false;

  if (isTimerPickerEnable) {
    if (model.recurrentWoTimerModel?.startAt == null && model.recurrentWoTimePicker == null) {
      showDialog(
        context: context,
        builder: (context) => ConfirmDialog(
          message: "Working Hours Required",
          title: 'Validation Error',
          onTap: () => Navigator.pop(context),
        ),
      );
      return false;
    }
    if (model.recurrentWoTimePicker == null) {
      if (model.recurrentWoTimerModel?.startAt == null) {
        showDialog(
          context: context,
          builder: (context) => ConfirmDialog(
            message: "Working Hours Required",
            title: 'Validation Error',
            onTap: () => Navigator.pop(context),
          ),
        );
        return false;
      }
      if (model.recurrentWoTimerModel?.endAt == null) {
        showDialog(
          context: context,
          builder: (context) => ConfirmDialog(
            message: "Please Stop The Timer",
            title: 'Validation Error',
            onTap: () => Navigator.pop(context),
          ),
        );
        return false;
      }
    }
  } else {
    if (model.recurrentWoTimerModel?.startAt == null) {
      showDialog(
        context: context,
        builder: (context) => ConfirmDialog(
          message: "Working Hours Required",
          title: 'Validation Error',
          onTap: () => Navigator.pop(context),
        ),
      );
      return false;
    }
    if (model.recurrentWoTimerModel?.endAt == null) {
      showDialog(
        context: context,
        builder: (context) => ConfirmDialog(
          message: "Please Stop The Timer",
          title: 'Validation Error',
          onTap: () => Navigator.pop(context),
        ),
      );
      return false;
    }
  }

  return true;
}
