import 'dart:convert';

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/ppm_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/widget_extensions.dart';
import 'package:test_sa/models/plan_preventive_visit/plan_preventive_visit_model.dart';
import 'package:test_sa/models/ppm/ppm.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/utilities/service_request_utils.dart';
import 'package:test_sa/views/pages/user/ppm/update_ppm/ppm_external_details_form.dart';

import '../../../../../extensions/text_extensions.dart';
import 'ppm_calibration_tools_form.dart';
import 'ppm_pm_check_list_form.dart';
import 'ppm_pm_kits_form.dart';
import 'wo_info_form.dart';

class UpdatePpm extends StatefulWidget {
  final Ppm? ppm;
  final PlanPreventiveVisit planPreventiveVisit;

  const UpdatePpm({Key? key, this.ppm, required this.planPreventiveVisit}) : super(key: key);

  @override
  State<UpdatePpm> createState() => _UpdatePpmState();
}

class _UpdatePpmState extends State<UpdatePpm> with TickerProviderStateMixin {
  late PlanPreventiveVisit _planPreventiveVisit;

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  TabController? _tabController;
  late PpmProvider ppmProvider;

  _onSubmit({required int status}) async {
    if (ppmProvider.validate()) {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      ppmProvider.planPreventiveVisit?.preventiveVisitAttachments = [];
      for (var item in ppmProvider.ppmPlanAttachments) {
        ppmProvider.planPreventiveVisit?.preventiveVisitAttachments
            ?.add(PreventiveVisitAttachments(id: 0, attachmentName: ServiceRequestUtils.isLocalUrl(item.path) ? "${item.path.split("/").last}|${base64Encode(item.readAsBytesSync())}" : item.path));
      }

      ppmProvider.planPreventiveVisit?.preventiveVisitTimers = ppmProvider.planPreventiveVisit?.preventiveVisitTimers ?? [];
      ppmProvider.planPreventiveVisit?.timerModelList?.forEach((timer) {
        int durationInSecond = timer.endAt!.difference(timer.startAt!).inSeconds;
        ppmProvider.planPreventiveVisit?.preventiveVisitTimers?.add(
          PreventiveVisitTimers(
            id: 0,
            startDateTime: timer.startAt!.toIso8601String(), // Handle potential null
            endDateTime: timer.endAt?.toIso8601String(), // Handle potential null
            workingHours: ((durationInSecond) / 60 / 60),
          ),
        );
      });

      await ppmProvider.updateVisitByEngineer(status: status).whenComplete(() {
        if (status == 1) {
          AllRequestsProvider allRequestsProvider = Provider.of<AllRequestsProvider>(context, listen: false);
          allRequestsProvider.reset();
          allRequestsProvider.getAllRequests(context, typeTransaction: 4);
          ppmProvider.ppmPlanAttachments = [];
        }
        // allRequestsProvider.recurrentWoData?.recurrentWoTimerModel=null;
        Navigator.pop(context);
        Navigator.pop(context);
      });
    }
  }

  @override
  void initState() {

    ppmProvider = Provider.of<PpmProvider>(context, listen: false);
    _planPreventiveVisit = widget.planPreventiveVisit;
    // WidgetsBinding.instance.addPostFrameCallback((_) {
      initTabs(_planPreventiveVisit.typeOfService);
    // });
    super.initState();
  }

  void initTabs(typeOfService) {
    if (typeOfService == null) {
      return;
    }
    if (typeOfService?.id == 66) {
      ppmProvider.totalTabs = 4;
    } else {
      ppmProvider.totalTabs = 3;
    }
    _tabController?.dispose;
    _tabController = TabController(length: ppmProvider.totalTabs, vsync: this);
  }

  int tabIndex = 0;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.neutral110,
      appBar: DefaultAppBar(
        title: context.translation.preventiveMaintenance,
        onWillPopScope:ppmProvider.isReadOnly?null: () {
          _onSubmit(status: 0);
        },
      ),
      key: _scaffoldKey,
      body: SafeArea(
        child: Column(
          children: [
            DefaultTabController(
              length: 2,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(left: 16.toScreenWidth, right: 16.toScreenWidth, top: 16.toScreenHeight, bottom: 8),
                    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),
                      ),
                      onTap: (index) {
                        tabIndex = index;
                        if (tabIndex == 0) {
                          _tabController?.animateTo(0);
                        }
                        setState(() {});
                      },
                      tabs: [
                        Tab(text: "WO Info".addTranslation, height: 57.toScreenHeight),
                        Tab(text: "WO Inspection".addTranslation, height: 57.toScreenHeight),
                      ],
                    ),
                  ),
                  TabBarView(
                    physics: const NeverScrollableScrollPhysics(),
                    children: [
                      WoInfoForm(
                          planPreventiveVisit: _planPreventiveVisit,
                          onTypeOfServiceChange: (selectedTypeOfService) {
                            initTabs(selectedTypeOfService);
                          }),
                      TabBarView(
                        physics: const NeverScrollableScrollPhysics(),
                        controller: _tabController,
                        children: [
                          if (ppmProvider.totalTabs == 4) ...[
                            PpmExternalDetailsForm(models: _planPreventiveVisit.preventiveVisitSuppliers),
                          ],
                          PpmCalibrationToolsForm(models: _planPreventiveVisit.preventiveVisitCalibrations),
                          PpmPMKitsForm(models: _planPreventiveVisit.preventiveVisitKits, assetId: _planPreventiveVisit.asset?.id),
                          PpmPmChecklistForm(checkList: _planPreventiveVisit.preventiveVisitChecklists),
                        ],
                      )
                    ],
                  ).expanded,
                ],
              ),
            ).expanded,
            Row(
              children: [
                if (tabIndex == 1) ...[
                  AppFilledButton(
                    buttonColor: _tabController!.index == 0 ? null : AppColor.background(context),
                    textColor: _tabController!.index == 0 ? null : AppColor.blueStatus(context),
                    showBorder: true,
                    disableButton: _tabController!.index == 0,
                    onPressed: () {
                      if (_tabController!.index == 0) {
                        return;
                      }
                      _tabController?.animateTo(_tabController!.index - 1);
                      setState(() {});
                      return;
                    },
                    label: context.translation.back,
                  ).expanded,
                  8.width,
                ],
                if (!ppmProvider.isReadOnly) ...[
                  AppFilledButton(
                    buttonColor: AppColor.white60,
                    textColor: AppColor.neutral50,
                    onPressed: () {
                      _onSubmit(status: 0);
                    },
                    label: context.translation.save,
                  ).expanded,
                  8.width,
                  AppFilledButton(
                    onPressed: () {
                      if (tabIndex == 0) {
                        _onSubmit(status: 1);
                        return;
                      }
                      if (ppmProvider.totalTabs == _tabController!.index + 1) {
                        _onSubmit(status: 1);
                      } else {
                        _tabController?.animateTo(_tabController!.index + 1);
                        setState(() {});
                      }
                    },
                    label: tabIndex == 0 ? "Complete".addTranslation : ((ppmProvider.totalTabs == _tabController!.index + 1) ? "Complete".addTranslation : context.translation.next),
                  ).expanded,
                ] else ...[
                  Visibility(
                    visible: tabIndex != 0,
                    child: AppFilledButton(
                      onPressed: () {
                        if(ppmProvider.totalTabs == _tabController!.index + 1){
                          Navigator.pop(context);
                          return;
                        }
                          _tabController?.animateTo(_tabController!.index + 1);
                          setState(() {});
                      },
                      label:ppmProvider.totalTabs == _tabController!.index + 1? context.translation.close: context.translation.next,
                    ).expanded,
                  ),
                ]
              ],
            ).toShadowContainer(context, showShadow: false, borderRadius: 0),
          ],
        ),
      ),
    ).handlePopScope(cxt: context, showPopUp:!ppmProvider.isReadOnly ,onSave:  () {
      _onSubmit(status: 0);
    });
  }
}
