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

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/http_status_manger.dart';
import 'package:test_sa/controllers/localization/localization.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/controllers/validator/validator.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/device/device.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/service_request/service_request.dart';
import 'package:test_sa/models/subtitle.dart';
import 'package:test_sa/views/app_style/colors.dart';
import 'package:test_sa/views/widgets/app_text_form_field.dart';
import 'package:test_sa/views/widgets/buttons/app_back_button.dart';
import 'package:test_sa/views/widgets/buttons/app_button.dart';
import 'package:test_sa/views/widgets/equipment/device_button.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/record_sound.dart';
import 'package:test_sa/views/widgets/speech_to_text/speech_to_text.dart';
import 'package:test_sa/views/widgets/status/service_request/service_request_defect_types_mune.dart';
import 'package:test_sa/views/widgets/status/service_request/service_request_priority_mune.dart';
import 'package:test_sa/views/widgets/status/service_request/service_request_through_mune.dart';
import 'package:test_sa/views/widgets/status/service_request/service_request_types_mune.dart';
import 'package:test_sa/views/widgets/titles/app_sub_title.dart';
class CreateRequestPage extends StatefulWidget {
  static final String id = "/create-request";

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

class _CreateRequestPageState extends State<CreateRequestPage> {
  double _height;
  UserProvider _userProvider;
  SettingProvider _settingProvider;
  ServiceRequestsProvider _serviceRequestsProvider;
  ServiceRequest _serviceRequest = ServiceRequest();
  List<File> _deviceImages = [];
  bool _isLoading = false;
  Device _device;
  Subtitle _subtitle;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  TextEditingController _controller;

  @override
  void initState() {
    _controller = TextEditingController();
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    _height = MediaQuery.of(context).size.height;
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _serviceRequestsProvider = Provider.of<ServiceRequestsProvider>(context);
    _subtitle = AppLocalization.of(context).subtitle;
    return Scaffold(
      key: _scaffoldKey,
      body: SafeArea(
        child: LoadingManager(
          isLoading: _isLoading,
          isFailedLoading: false,
          stateCode: 200,
          onRefresh: () async {},
          child: Form(
            key: _formKey,
            child: Stack(
              children: [
                ListView(
                  children: [
                    //AppNameBar(),
                    SizedBox(
                      height: 16,
                    ),
                    Hero(
                      tag: "logo",
                      child: Image(
                        height: _height / 6,
                        image: AssetImage("assets/images/logo.png"),
                      ),
                    ),
                    Center(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          _subtitle.newServiceRequest,
                          style: Theme.of(context).textTheme.headline5.copyWith(color: AColors.cyan, fontWeight: FontWeight.w600),
                        ),
                      ),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        12.height,
                        _userProvider.user.hospital == null
                            ? SizedBox.shrink()
                            : ATextFormField(
                                enable: false,
                                initialValue: _userProvider.user.hospital?.name ?? _subtitle.noHospitalFound,
                                hintText: _subtitle.hospital,
                                prefixIconData: FontAwesomeIcons.hospital,
                                style: Theme.of(context).textTheme.subtitle1,
                              ),
                        12.height,
                        _userProvider.user.department == null
                            ? SizedBox.shrink()
                            : ATextFormField(
                                enable: false,
                                initialValue: _userProvider.user.department?.name ?? _subtitle.noUniteFound,
                                hintText: _subtitle.unite,
                                prefixIconData: FontAwesomeIcons.hospitalUser,
                                style: Theme.of(context).textTheme.subtitle1,
                              ),
                        12.height,
                        DeviceButton(
                          device: _device,
                          onDevicePick: (device) {
                            _device = device;
                            setState(() {});
                          },
                        ),
                        const SizedBox(height: 8,),
                        const ASubTitle("Priority"),
                        const SizedBox(height: 4,),
                        ServiceRequestPriorityMenu(
                          initialValue: _serviceRequest.priority,
                          onSelect: (status){
                            _serviceRequest.priority = status;
                          },
                        ),
                        const SizedBox(height: 8,),
                        const ASubTitle("Defect Type"),
                        const SizedBox(height: 4,),
                        ServiceRequestDefectTypesMenu(
                          initialValue: _serviceRequest.defectType,
                          onSelect: (status){
                            _serviceRequest.defectType = status;
                          },
                        ),
                        12.height,
                        const SizedBox(height: 8,),
                        const ASubTitle("Type"),
                        const SizedBox(height: 4,),
                        ServiceRequestTypesMenu(
                          initialValue: _serviceRequest.type,
                          onSelect: (status){
                            _serviceRequest.type = status;
                          },
                        ),
                        const SizedBox(height: 8,),
                        const ASubTitle("Through"),
                        const SizedBox(height: 4,),
                        ServiceRequestedThroughMenu(
                          initialValue: const Lookup(name: "App",value: 3),
                          onSelect: (status){
                            _serviceRequest.requestedThrough = status;
                          },
                        ),
                        12.height,
                        MultiImagesPicker(
                          label: _subtitle.deviceImages,
                          images: _deviceImages,
                        ),
                        12.height,
                        SpeechToTextButton(controller: _controller),
                        12.height,
                        ATextFormField(
                          controller: _controller,
                          initialValue: _serviceRequest.maintenanceIssue,
                          hintText: _subtitle.maintenanceIssue,
                          prefixIconData: FontAwesomeIcons.triangleExclamation,
                          style: Theme.of(context).textTheme.headline6,
                          textInputType: TextInputType.multiline,
                          validator: (value) => Validator.hasValue(value) ? null : _subtitle.maintenanceIssueRequired,
                          onSaved: (value) {
                            _serviceRequest.maintenanceIssue = value;
                          },
                        ),
                        12.height,
                        RecordSound(onRecord: (audio) {
                          _serviceRequest.audio = audio;
                        }),
                        12.height,
                      ],
                    ).paddingOnly(left: 20, right: 20),
                    Padding(
                      padding: const EdgeInsets.all(20.0),
                      child: AButton(
                        text: _subtitle.submit,
                        onPressed: () async {
                          if (!_formKey.currentState.validate()) return;
                          _formKey.currentState.save();
                          _serviceRequest.deviceId = _device?.id ?? "";
                          _isLoading = true;
                          setState(() {});
                          _serviceRequest.devicePhotos = _deviceImages.map(
                                  (e) => "${e.path.split("/").last}|${base64Encode(e.readAsBytesSync())}").toList();
                          if(_serviceRequest.audio != null){
                            final file = File(_serviceRequest.audio);
                            _serviceRequest.audio = "${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}";
                          }
                          int status = await _serviceRequestsProvider.createRequest(
                            user: _userProvider.user,
                            host: _settingProvider.host,
                            serviceRequest: _serviceRequest,
                          );
                          _isLoading = false;
                          setState(() {});
                          if (status >= 200 && status < 300) {
                            Fluttertoast.showToast(
                              msg: _subtitle.requestCompleteSuccessfully,
                            );
                            Navigator.of(context).pop();
                          } else {
                            String errorMessage = HttpStatusManger.getStatusMessage(status: status, subtitle: _subtitle);
                            ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                              content: Text(errorMessage),
                            ));
                          }
                        },
                      ),
                    ),
                  ],
                ),
                ABackButton(),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
