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

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/service_requests_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_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/generic_attachment_model.dart';
import 'package:test_sa/models/service_request/pending_service_request_model.dart';
import 'package:test_sa/models/service_request/service_request.dart';
import 'package:test_sa/modules/cm_module/utilities/service_request_utils.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/providers/service_request_providers/equipment_status_provider.dart';
import 'package:test_sa/providers/service_request_providers/requested_through_provider.dart';
import 'package:test_sa/views/pages/user/requests/pending_requests_screen.dart';
import 'package:test_sa/views/widgets/bottom_sheets/pending_request_bottom_sheet.dart';
import 'package:test_sa/views/widgets/equipment/asset_picker.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
import 'package:test_sa/views/widgets/sound/TextSpeechRecordWidget.dart';

import '../../../../new_views/app_style/app_color.dart';
import '../../../../new_views/common_widgets/default_app_bar.dart';
import '../../../../providers/service_request_providers/priority_provider.dart';
import '../../../../providers/service_request_providers/type_of_request_provider.dart';

class CreateServiceRequestPage extends StatefulWidget {
  static const String id = "/create-request";
  final ServiceRequest? serviceRequest;

  const CreateServiceRequestPage({this.serviceRequest, Key? key}) : super(key: key);

  @override
  CreateServiceRequestPageState createState() => CreateServiceRequestPageState();
}

class CreateServiceRequestPageState extends State<CreateServiceRequestPage> {
  late TextEditingController _commentController;

  late double _height;
  late UserProvider _userProvider;
  late SettingProvider _settingProvider;
  late ServiceRequestsProvider _serviceRequestsProvider;
  late ServiceRequest _serviceRequest;
  final List<GenericAttachmentModel> attachments = [];
  final bool _isLoading = false;
  bool _showDatePicker = false;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  DateTime? _dateTime;

  bool isFirstActionSubmitted = false;

  @override
  void initState() {
    _commentController = TextEditingController();
    if (widget.serviceRequest != null) {
      _serviceRequest = widget.serviceRequest!;
      attachments.addAll(_serviceRequest.devicePhotos!.map((e) => GenericAttachmentModel(name: e)).toList());
      _showDatePicker = _serviceRequest.firstAction != null && _serviceRequest.firstAction?.name == "Need a visit";
      if (_showDatePicker && _serviceRequest.visitDate != null) {
        _dateTime = DateTime.tryParse(_serviceRequest.visitDate!);
      }
    } else {
      _serviceRequest = ServiceRequest();
    }
    isFirstActionSubmitted = _serviceRequest.firstAction != null;
    super.initState();
  }

  //
  // getServiceRequestById(String id) async {
  //   try {
  //     ServiceRequest request = await _serviceRequestsProvider.getServiceRequestObjectById(requestId: id) ?? "";
  //     _serviceRequest = request;
  //     _device = _serviceRequest.device;
  //     attachments.addAll(_serviceRequest.devicePhotos.map((e) {
  //       return File(e);
  //     }).toList());
  //     _showDatePicker = _serviceRequest.firstAction != null && _serviceRequest.firstAction.name == "Need a visit";
  //     if (_showDatePicker && _serviceRequest.visitDate != null) {
  //       _dateTime = DateTime.tryParse(_serviceRequest.visitDate);
  //     }
  //     _isLoading = false;
  //   } catch (ex) {
  //     _isLoading = false;
  //   }
  //   setState(() {});
  // }

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

  bool _isLocalUrl(String url) {
    if (url.isEmpty != false) return false;
    return url.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\');
  }

  // bool priority;

  void getData() {
    Provider.of<RequestedThroughProvider>(context).getDate();
    Provider.of<TypeOfRequestProvider>(context).getDate();
    Provider.of<PriorityProvider>(context).getDate();
    Provider.of<EquipmentStatusProvider>(context).getDate();
  }

  PendingAssetServiceRequest? pendingAssetServiceRequest;

  @override
  Widget build(BuildContext context) {
    _height = MediaQuery.of(context).size.height;
    _userProvider = Provider.of<UserProvider>(context);

    _serviceRequestsProvider = Provider.of<ServiceRequestsProvider>(context);

    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: context.translation.newServiceRequest),
      body: SafeArea(
        child: LoadingManager(
          isLoading: _isLoading,
          isFailedLoading: false,
          stateCode: 200,
          onRefresh: () async {},
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          AssetPicker(
                            device: _serviceRequest.device,
                            showLoading: checkPendingRequest,
                            onPick: (asset) async {
                              pendingAssetServiceRequest = null;
                              _serviceRequest.device = asset;
                              await checkAssetForPendingServiceRequest(asset.id!.toInt());

                              if (pendingAssetServiceRequest != null && pendingAssetServiceRequest!.details!.isNotEmpty) {
                                showPendingRequestBottomSheet();
                              }
                            },
                          ),
                          if (pendingAssetServiceRequest != null && pendingAssetServiceRequest!.details!.isNotEmpty) ...[
                            8.height,
                            Row(
                              children: [
                                const Icon(Icons.warning, color: Color(0xffEE404C), size: 14),
                                8.width,
                                Text(
                                  "This asset already have ${pendingAssetServiceRequest!.details!.length} request pending",
                                  style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: Color(0xff7D859A), decoration: TextDecoration.underline),
                                ).expanded,
                              ],
                            ).onPress(() {
                              showPendingRequests();
                            }),
                          ],
                          16.height,
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(context.translation.priority, style: Theme.of(context).textTheme.bodyLarge),
                              Consumer<PriorityProvider>(builder: (cxt, snapshot, _) {
                                _serviceRequest.priority ??= snapshot.items.firstWhere((element) => element.value == 0, orElse:  null);

                                return Transform.scale(
                                  scale: 0.8,
                                  child: CupertinoSwitch(
                                      thumbColor: _serviceRequest.priority?.value != 0 ? const Color(0xffF63939) : Colors.blueGrey.withOpacity(.5),
                                      activeColor: AppColor.blueStatus(context).withOpacity(.25),
                                      value: _serviceRequest.priority?.value != 0,
                                      onChanged: (state) {
                                        if (state) {
                                          _serviceRequest.priority = snapshot.items.firstWhere((element) => element.value == 1, orElse:  null);
                                        } else {
                                          _serviceRequest.priority = snapshot.items.firstWhere((element) => element.value == 0, orElse:  null);
                                        }
                                        setState(() {});
                                      }).toShimmer(isShow: snapshot.loading,context: context),
                                );
                              }),
                            ],
                          ),
                          16.height,
                          Consumer<EquipmentStatusProvider>(builder: (cxt, snapshot, _) {
                            try {
                              _serviceRequest.defectType ??= snapshot.items.first;
                            } catch (ex) {
                              print("snapshot.items:${snapshot.items.length}");
                            }

                            return Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text(context.translation.equipmentStatus, style: Theme.of(context).textTheme.bodyLarge),
                                8.height,
                                Wrap(
                                  runSpacing: 8,
                                  spacing: 8,
                                  children: [
                                    for (var element in snapshot.items)
                                      Row(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          SizedBox(
                                            width: 24,
                                            height: 24,
                                            child: Radio(
                                                value: element,
                                                activeColor: Colors.red,
                                                fillColor: WidgetStateColor.resolveWith((states) {
                                                  if (states.contains(WidgetState.selected)) return const Color(0xff3DA5E5);
                                                  return const Color(0xffE0E0E0);
                                                }),
                                                groupValue: _serviceRequest.defectType,
                                                onChanged: (state) {
                                                  setState(() {
                                                    _serviceRequest.defectType = element;
                                                  });
                                                }),
                                          ),
                                          8.width,
                                          Text(element.name!, style: Theme.of(context).textTheme.bodySmall),
                                        ],
                                      )
                                  ],
                                ).toShimmer(isShow: snapshot.loading,context: context),
                              ],
                            );
                          }),
                          16.height,
                          AttachmentPicker(label: context.translation.attachImage, attachment: attachments, showAsGrid: true),
                        ],
                      ).toShadowContainer(context),

                      // SingleItemDropDownMenu<Lookup, PriorityProvider>(
                      //   context: context,
                      //   title: context.translation.priority,
                      //   initialValue: _serviceRequest?.priority,
                      //   onSelect: (value) {
                      //     _serviceRequest.priority = value;
                      //   },
                      // ),
                      // 8.height,
                      // SingleItemDropDownMenu<Lookup, EquipmentStatusProvider>(
                      //   context: context,
                      //   title: context.translation.equipmentStatus,
                      //   initialValue: _serviceRequest?.defectType,
                      //   onSelect: (value) {
                      //     _serviceRequest.defectType = value;
                      //   },
                      // ),

                      // Consumer<RequestedThroughProvider>(builder: (context, snapshot, _) {
                      //   return SingleItemDropDownMenu<Lookup, RequestedThroughProvider>(
                      //     context: context,
                      //     enabled: false,
                      //     title: context.translation.source,
                      //     initialValue: snapshot.items?.firstWhere((element) => element.value == 3, orElse:  null),
                      //   );
                      // }),
                      // 8.height,
                      // Consumer<TypeOfRequestProvider>(builder: (context, snapshot, _) {
                      //   return SingleItemDropDownMenu<Lookup, TypeOfRequestProvider>(
                      //     context: context,
                      //     title: context.translation.requestType,
                      //     enabled: false,
                      //     initialValue: snapshot.items?.firstWhere((element) => element.value == 1, orElse:  null),
                      //     // onSelect: (value) {
                      //     //   _serviceRequest.type = value;
                      //     // },
                      //   );
                      // }),

                      // Align(
                      //   alignment: AlignmentDirectional.centerStart,
                      //   child: context.translation.callComments.heading5(context),
                      // ),
                      8.height,
                      // SpeechToTextButton(
                      //   controller: _commentController,
                      // ),
                      // 8.height,
                      // AppTextFormField(
                      //   controller: _commentController,
                      //   labelText: context.translation.problemDesc,
                      //   suffixIcon: "warning".toSvgAsset(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20, width: 24).paddingOnly(end: 16),
                      //   initialValue: _serviceRequest.callComments,
                      //   onSaved: (text) {
                      //     _serviceRequest.callComments = text;
                      //   },
                      // ),
                      // 8.height,
                      // RecordSound(
                      //   onRecord: (audio) {
                      //     _serviceRequest.audio = audio;
                      //   },
                      //   enabled: widget.serviceRequest == null ? true : false,
                      // ),
                      8.height,
                      TextSpeechRecordWidget(
                        initialMessage: _serviceRequest.callComments!,
                        onMessageChange: (message) {
                          _serviceRequest.callComments = message;
                        },
                        onRecord: (audio) {
                          _serviceRequest.audio = audio;
                        },
                        enabled: widget.serviceRequest == null ? true : false,
                      ),
                      16.height,
                    ],
                  ),
                ).expanded,
                AppFilledButton(
                  onPressed: checkPendingRequest ? null : _submit,
                  loading: checkPendingRequest,
                  label: (pendingAssetServiceRequest != null && (pendingAssetServiceRequest!.details?.isNotEmpty ?? false)) ? "Submit Duplicate Request" : "Submit New Request",
                ),
              ],
            ),
          ).paddingOnly(start: 16, end: 16, bottom: 24, top: 16),
        ),
      ),
    );
  }

  bool checkPendingRequest = false;

  void showPendingRequests() {
    Navigator.of(context).push(MaterialPageRoute(builder: (_) => PendingServiceRequestScreen(pendingAssetServiceRequest!)));
  }

  void showPendingRequestBottomSheet() async {
    bool view = (await showModalBottomSheet(
      context: context,
      isDismissible: false,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(20),
        ),
      ),
      clipBehavior: Clip.antiAliasWithSaveLayer,
      builder: (BuildContext context) => PendingRequestBottomSheet(pendingAssetServiceRequest!, _serviceRequest.device!),
    )) as bool;
    if (view) {
      showPendingRequests();
    }
  }

  Future<void> checkAssetForPendingServiceRequest(int assetId) async {
    checkPendingRequest = true;
    setState(() {});

    pendingAssetServiceRequest = await _serviceRequestsProvider.checkAssetPendingRequest(assetId);
    await Future.delayed(const Duration(milliseconds: 250));

    checkPendingRequest = false;
    setState(() {});
  }

  Future<void> _submit() async {
    _serviceRequest.requestedThrough = Provider.of<RequestedThroughProvider>(context, listen: false).items.firstWhere((element) => element.value == 3, orElse:  null);
    _serviceRequest.type = Provider.of<TypeOfRequestProvider>(context, listen: false).items.firstWhere((element) => element.value == 1, orElse:  null);

    if (_formKey.currentState!.validate() && await _serviceRequest.validateNewRequest(context)) {
      _formKey.currentState!.save();

      // bool canSubmitRequest = await checkAssetForPendingServiceRequest(_serviceRequest.device.id);
      // if (!canSubmitRequest) {
      //   return;
      // }


      _serviceRequest.devicePhotos = attachments.map((item) => ServiceRequestUtils.isLocalUrl(item.name??'') ? "${item.name?.split("/").last}|${base64Encode(File(item.name??'').readAsBytesSync())}" : item.name??'').toList();
      if (_serviceRequest.audio != null) {
        if (_isLocalUrl(_serviceRequest.audio!)) {
          final File file = File(_serviceRequest.audio!);
          _serviceRequest.audio = "${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}";
        }
      }
      await _serviceRequestsProvider.createRequest(
        context: context,
        user: _userProvider.user!,
        host: _settingProvider.host!,
        serviceRequest: _serviceRequest,
      );
    }
  }
}
