import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.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/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/service_request_latest/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/views/pages/user/ppm/ppm_work_order/recurrent_wo/components/task_info_widget.dart';
import 'package:test_sa/views/widgets/loaders/app_loading.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';

import '../../../../../../controllers/providers/api/all_requests_provider.dart';
import 'components/room_tabs_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();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AllRequestsProvider>(builder: (context, requestProvider, child) {
      return Scaffold(
        appBar: DefaultAppBar(
          title: context.translation.recurrentWo,
          onWillPopScope: () {
            _updateTask(context: context, status: 0);
          },
        ),
        body: allRequestsProvider!.isLoading
            ? const ALoading()
            : requestProvider.recurrentWoData != null
                ? Stack(
                    children: [
                      SingleChildScrollView(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            RecurrentTaskInfoWidget(model: requestProvider.recurrentWoData),
                            requestProvider.recurrentWoData!.planRecurrentMedicalTaskRooms!.isNotEmpty
                                ? Column(
                                    children: [
                                      8.height,
                                      RoomTabsWidget(model: requestProvider.recurrentWoData),
                                    ],
                                  )
                                : const SizedBox(),
                          ],
                        ).paddingAll(12),
                      ).paddingOnly(bottom: 85),
                      if (requestProvider.recurrentWoData?.status?.value != 1) ...[
                        FooterActionButton.footerContainer(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              AppFilledButton(
                                label: context.translation.save,
                                buttonColor: AppColor.white60,
                                textColor: AppColor.black10,
                                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,
          onSave: () {
            _updateTask(context: context, status: 0);
          });
    });
  }
}

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

  if (validate(model: allRequestsProvider.recurrentWoData!)) {
    allRequestsProvider.recurrentWoData?.planRecurrentTaskTimers = allRequestsProvider.recurrentWoData?.planRecurrentTaskTimers ?? [];
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    allRequestsProvider.recurrentWoData?.timerModelList?.forEach((timer) {
      int durationInSecond = timer.endAt!.difference(timer.startAt!).inSeconds;
      allRequestsProvider.recurrentWoData?.planRecurrentTaskTimers?.add(
        PlanRecurrentTaskTimers(
          id: 0,
          startTime: timer.startAt!.toIso8601String(), // Handle potential null
          endTime: timer.endAt?.toIso8601String(), // Handle potential null
          workingHours: ((durationInSecond) / 60 / 60),
        ),
      );
    });

    await allRequestsProvider
        .updateRecurrentWo(
      status: status,
    )
        .whenComplete(() {
      if (status == 1) {
        // when click complete then this request remove from the list and status changes to closed..
        allRequestsProvider.reset();
        allRequestsProvider.getAllRequests(context, typeTransaction: 5);
      }
      allRequestsProvider.recurrentWoData?.recurrentWoTimerModel = null;
      Navigator.pop(context);
      Navigator.pop(context);
    });
  }
}

bool validate({required RecurrentWoData model}) {
  if (model.recurrentWoTimerModel?.startAt == null) {
    Fluttertoast.showToast(msg: "Working Hours Required");
    return false;
  }
  if (model.recurrentWoTimerModel?.endAt == null) {
    Fluttertoast.showToast(msg: "Please Stop The Timer");
    return false;
  }
  return true;
}
