import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/report/service_report_repair_location_provider.dart';
import 'package:test_sa/controllers/providers/api/user_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/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/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/request_detail_provider.dart';
import 'package:test_sa/service_request_latest/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/service_request_latest/views/forms/maintenance_request/components/external_request.dart';
import 'package:test_sa/service_request_latest/views/forms/maintenance_request/components/internal_request.dart';

class MaintenanceRequestForm extends StatefulWidget {
  const 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();
    RequestDetailProvider requestDetailProvider = Provider.of<RequestDetailProvider>(context, listen: false);

    requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees =
        requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees ?? ActivityMaintenanceAssistantEmployees();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<RequestDetailProvider>(builder: (context, RequestDetailProvider requestDetailProvider, child) {
      return Scaffold(
        backgroundColor: AppColor.neutral110,
        appBar: DefaultAppBar(title: context.translation.maintenanceRequest),
        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,
                ],
              ),
            ),
            FooterActionButton.footerContainer(
              child: AppFilledButton(
                label: requestDetailProvider.activityMaintenanceHelperModel?.id != 0 ? context.translation.update : context.translation.addActivity, // Use the dynamic label
                buttonColor: AppColor.primary10,
                onPressed: () async {
                  //TODO add this as dropdown not added in design yet Bhaa need to confirm with hussain then.
                  requestDetailProvider.activityMaintenanceHelperModel?.lastSituationId = 282;

                  print('model  is ${requestDetailProvider.activityMaintenanceHelperModel?.toJson()}');

                  if (validate(model: requestDetailProvider.activityMaintenanceHelperModel!)) {
                    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
                    int status = -1;
                    if (requestDetailProvider.activityMaintenanceHelperModel?.id == 0) {
                      status = await requestDetailProvider.createActivityMaintenanceRequest();
                      print('status i got is $status');
                    } else {
                      print('going to update..');
                      status = await requestDetailProvider.updateActivityMaintenance();
                    }
                    if (status == 200) {
                      requestDetailProvider.getWorkOrderById(id: requestDetailProvider.currentWorkOrder!.data!.requestId!);
                      print('workorder activities list i got is ${requestDetailProvider.currentWorkOrder?.data?.activities.length}');
                      Navigator.pop(context);
                      Navigator.pop(context);
                    } else {
                      Navigator.pop(context);
                    }
                  }

                  // Handle button press
                },
              ),
            ),
          ],
        ),
      );
    });
  }

  bool validate({required ActivityMaintenanceHelperModel model}) {
    print('employee id is ${model.assignedEmployeeId}');

    if (model.activityStatus == null) {
      Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.activityStatus}");
      return false;
    } else if (model.startTime == null) {
      Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.startTime}");
      return false;
    } else 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;
    // }
    else 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;
  }
}
