import 'dart:convert';
import 'dart:developer';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/service_requests_provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/report/service_types_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/call_request_for_work_order_model.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/service_report.dart';
import 'package:test_sa/models/service_request/search_work_order.dart';
import 'package:test_sa/views/app_style/colors.dart';
import 'package:test_sa/views/pages/sub_workorder/spare_parts_details_bottom_sheet.dart';
import 'package:test_sa/views/pages/sub_workorder/work_order_details_bottom_sheet.dart';
import 'package:test_sa/views/pages/sub_workorder/workorder_details.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/loaders/app_loading.dart';
import 'package:test_sa/views/widgets/status/service_request/service_request_defect_types_mune.dart';

import '../../../controllers/api_routes/http_status_manger.dart';
import '../../../controllers/localization/localization.dart';
import '../../../controllers/providers/api/status_drop_down/report/service_report_fault_description_provider.dart';
import '../../widgets/app_text_form_field.dart';
import '../../widgets/buttons/app_back_button.dart';
import '../../widgets/buttons/app_button.dart';
import '../../widgets/date_and_time/date_picker.dart';
import '../../widgets/status/report/service_report_fault_description.dart';
import '../../widgets/status/report/service_report_reasons.dart';
import '../../widgets/titles/app_sub_title.dart';

class CreateSubWorkOrderPage extends StatefulWidget {
  static const id = "/CreateSubWorkOrder";
  final SearchWorkOrder workOrder;

  const CreateSubWorkOrderPage({this.workOrder, Key key}) : super(key: key);

  @override
  State<CreateSubWorkOrderPage> createState() => _CreateSubWorkOrderPageState();
}

class _CreateSubWorkOrderPageState extends State<CreateSubWorkOrderPage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  SearchWorkOrder _subWorkOrders;
  Lookup _serviceReportReason = Lookup();
  ServiceReport _serviceReport;
  final List<File> _files = [];
  bool _isLoading = false;
  bool _validate = false;

  @override
  void initState() {
    _subWorkOrders = SearchWorkOrder(
      assignedEmployee: widget?.workOrder?.callRequest?.assignedEmployee,
      callRequest: CallRequest(id: widget?.workOrder?.callRequest?.id),
      currentSituation: null,
      supplier: null,
      parentWOId: widget.workOrder.id,
    );
    _serviceReport = ServiceReport(id: widget.workOrder.id, type: widget.workOrder.assetType, equipmentStatus: widget.workOrder.equipmentStatus);
    _isLoading = true;
    super.initState();
  }

  var assetTypesProvider;
  CallRequestForWorkOrder _callRequestForWorkOrder;

  Future getAssetType() async {
    //if (assetTypesProvider == null) {
    final serviceRequestProvider = Provider.of<ServiceRequestsProvider>(context);
    Provider.of<ServiceRequestFaultDescriptionProvider>(context, listen: false).reset();
    assetTypesProvider = Provider.of<ServiceStatusProvider>(context, listen: false);
    _callRequestForWorkOrder = await serviceRequestProvider.getCallRequestForWorkOrder(callId: widget.workOrder.callRequest.id.toString());
    if (_subWorkOrders?.parentWOId != null) {
      print(_subWorkOrders?.parentWOId.toString());
      final subWoDetails = await serviceRequestProvider.getSubWorkOrderDetails(parentId: _subWorkOrders?.parentWOId.toString());
      _subWorkOrders.copyDetails(subWoDetails);
      _serviceReport.equipmentStatus = subWoDetails.equipmentStatus;
      _serviceReport.reason = subWoDetails.reason;
      _serviceReport.faultDescription = subWoDetails.faultDescription;
      _serviceReportReason = _subWorkOrders.reason;
    }
    await assetTypesProvider.getTypes();
    _subWorkOrders?.assetType = assetTypesProvider.statuses?.firstWhere(
      (element) => element.value == _callRequestForWorkOrder?.assetType,
      orElse: () => null,
    );
    setState(() {
      _isLoading = false;
    });
    //}
  }

  @override
  Widget build(BuildContext context) {
    if (_callRequestForWorkOrder == null) {
      getAssetType();
    }

    return Scaffold(
      body: SafeArea(
        child: _isLoading
            ? const ALoading()
            : Column(
                children: [
                  SingleChildScrollView(
                    child: Form(
                      key: _formKey,
                      child: Column(
                        children: [
                          Container(
                            color: AColors.primaryColor,
                            padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 4),
                            child: Column(
                              children: [
                                Row(
                                  children: [
                                    const ABackButton(),
                                    Expanded(
                                      child: Center(
                                        child: Text(
                                          "New Sub Work Order",
                                          style: Theme.of(context).textTheme.titleLarge.copyWith(color: AColors.white, fontStyle: FontStyle.italic),
                                        ),
                                      ),
                                    ),
                                    const SizedBox(
                                      width: 48,
                                    )
                                  ],
                                ),
                              ],
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
                            child: Column(
                              children: [
                                WorkOrderDetails(item: widget.workOrder, assetType: _subWorkOrders?.assetType),
                                const SizedBox(height: 8),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    const ASubTitle("Equipment status"),
                                    if (_validate && _subWorkOrders?.equipmentStatus == null)
                                      ASubTitle(
                                        context.translation.requiredWord,
                                        color: Colors.red,
                                      ),
                                    const SizedBox(
                                      height: 4,
                                    ),
                                    ServiceRequestDefectTypesMenu(
                                      initialValue: _serviceReport.equipmentStatus,
                                      onSelect: (status) {
                                        _subWorkOrders.equipmentStatus = status;
                                        _serviceReport.equipmentStatus = status;
                                        setState(() {});
                                      },
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 8),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    const ASubTitle("Return to Service"),
                                    // if (_validate && _subWorkOrders.visitDate == null)
                                    //   ASubTitle(
                                    //     context.translation.requiredWord,
                                    //     color: Colors.red,
                                    //   ),
                                    const SizedBox(
                                      height: 4,
                                    ),
                                    Row(
                                      children: [
                                        Expanded(
                                          child: ADatePicker(
                                            date: DateTime.tryParse(_subWorkOrders.visitDate ?? ""),
                                            from: DateTime(1950),
                                            onDatePicker: (date) {
                                              _subWorkOrders.visitDate = date?.toIso8601String();
                                              setState(() {});
                                            },
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 8),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    ASubTitle("Failure ${context.translation.reasons}"),
                                    if (_validate && _subWorkOrders.reason == null)
                                      ASubTitle(
                                        context.translation.requiredWord,
                                        color: Colors.red,
                                      ),
                                    const SizedBox(
                                      height: 4,
                                    ),
                                    ServiceReportReasonsMenu(
                                      initialValue: _serviceReportReason,
                                      onSelect: (status) {
                                        _serviceReportReason = status;
                                        _subWorkOrders.reason = status;
                                        // setState(() {});
                                      },
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 8),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    ASubTitle(context.translation.faultDescription),
                                    if (_validate && _subWorkOrders.faultDescription == null)
                                      ASubTitle(
                                        context.translation.requiredWord,
                                        color: Colors.red,
                                      ),
                                    const SizedBox(
                                      height: 4,
                                    ),
                                    ServiceReportFaultDescription(
                                      requestId: widget.workOrder?.callRequest?.id?.toString(),
                                      initialValue: _subWorkOrders?.faultDescription,
                                      onSelect: (status) {
                                        _subWorkOrders.faultDescription = status;
                                        if (mounted) setState(() {});
                                      },
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 8),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    const ASubTitle("Solution"),
                                    const SizedBox(height: 4),
                                    ATextFormField(labelText: _subWorkOrders?.faultDescription?.workPerformed ?? "", textInputType: TextInputType.multiline, enable: false),
                                  ],
                                ),
                                const SizedBox(height: 8),
                                MultiFilesPicker(label: "Attachments", files: _files),
                                const SizedBox(height: 8),
                                InkWell(
                                  onTap: () async {
                                    await showModalBottomSheet(
                                      context: context,
                                      useSafeArea: true,
                                      isScrollControlled: true,
                                      backgroundColor: Colors.transparent,
                                      builder: (context) => WorkOrderDetailsBottomSheet(subWorkOrder: _subWorkOrders),
                                    );
                                    //log(_subWorkOrders?.toJson()?.toString());
                                  },
                                  child: Card(
                                    child: ListTile(
                                      title: Row(
                                        children: [
                                          Text(
                                            "WO Details",
                                            style: Theme.of(context).textTheme.bodyMedium,
                                          ),
                                          const Text("*", style: TextStyle(color: Colors.red)),
                                        ],
                                      ),
                                      trailing: const Icon(Icons.arrow_forward_ios, size: 14, color: AColors.primaryColor),
                                    ),
                                  ),
                                ),
                                const SizedBox(height: 8),
                                InkWell(
                                  onTap: () async {
                                    await showModalBottomSheet(
                                      context: context,
                                      useSafeArea: true,
                                      isScrollControlled: true,
                                      backgroundColor: Colors.transparent,
                                      builder: (context) => SparePartsBottomSheet(
                                        subWorkOrder: _subWorkOrders,
                                        assetId: widget.workOrder?.callRequest?.asset?.id,
                                      ),
                                    );
                                    log(_subWorkOrders?.toJson()?.toString());
                                  },
                                  child: Card(
                                    child: ListTile(
                                      title: Row(
                                        children: [
                                          Text(
                                            "Spare Parts",
                                            style: Theme.of(context).textTheme.bodyMedium,
                                          ),
                                          const Text("*", style: TextStyle(color: Colors.red)),
                                        ],
                                      ),
                                      trailing: const Icon(Icons.arrow_forward_ios, size: 14, color: AColors.primaryColor),
                                    ),
                                  ),
                                ),
                                // AMiniOneFilePicker(
                                //   file: _file,
                                //   onPick: (file) {
                                //     _file = file;
                                //     _subWorkOrders.attachmentsWorkOrder ??= [];
                                //     _subWorkOrders.attachmentsWorkOrder.add(AttachmentsWorkOrder(name: "${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}"));
                                //   },
                                // ),
                                const SizedBox(height: 50),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ).expanded,
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: AButton(
                      text: context.translation.create,
                      onPressed: () async {
                        _validate = true;
                        setState(() {});
                        if (validate()) {
                          if (_subWorkOrders.calllastSituation.value == 12 && (_subWorkOrders.sparePartsWorkOrders == null || _subWorkOrders.sparePartsWorkOrders.isEmpty)) {
                            await Fluttertoast.showToast(msg: "You have to add parts");
                            return;
                          }
                          _subWorkOrders.attachmentsWorkOrder ??= [];
                          for (var file in _files) {
                            _subWorkOrders.attachmentsWorkOrder.add(AttachmentsWorkOrder(name: "${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}"));
                          }
                          if (_subWorkOrders.timer?.startAt == null || _subWorkOrders.timer?.endAt == null) {
                            Fluttertoast.showToast(msg: "Working hours required");
                            return;
                          } else if (_subWorkOrders.calllastSituation == null) {
                            Fluttertoast.showToast(msg: "${context.translation.callLastSituation} required");
                            return;
                          }
                          _validate = false;
                          _isLoading = true;
                          setState(() {});
                          if (_formKey.currentState?.validate() ?? false) {}
                          _formKey.currentState?.save();
                          final serviceRequestsProvider = Provider.of<ServiceRequestsProvider>(context, listen: false);
                          for (var element in (_subWorkOrders?.suppEngineerWorkOrders ?? [])) {
                            if (element != null) {
                              element.id = 0;
                            }
                          }
                          final status = await serviceRequestsProvider.createSubWorkOrder(workOrder: _subWorkOrders);
                          _isLoading = false;
                          setState(() {});
                          if (status >= 200 && status < 300) {
                            Fluttertoast.showToast(msg: context.translation.successfulRequestMessage);
                            Navigator.of(context).pop();
                            Navigator.of(context).pop();
                          } else {
                            String errorMessage = HttpStatusManger.getStatusMessage(status: serviceRequestsProvider.stateCode, subtitle: context.translation);
                            ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                              content: Text(errorMessage),
                            ));
                          }
                        }
                      },
                    ),
                  ),
                ],
              ),
      ),
    );
  }

  bool validate() {
    if (_subWorkOrders.faultDescription == null || _subWorkOrders.reason == null || _subWorkOrders.equipmentStatus == null) {
      return false;
    } else {
      return true;
    }
  }
}
